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;
}










