We know that using string concatenation to form SQL queries renders a program vulnerable to SQL injection. I usually get around that by using parameter features provided by the API of whatever database software I’m using.
But I haven’t heard of this being a problem in regular system programming. Consider the following code as part of a program that allows a user to write to files in his private directory only.
Scanner scanner = new Scanner(System.in);
String directoryName = "Bob";
String filePath = null;
String text = "some text";
System.out.print("Enter a file to write to: ");
filePath = scanner.nextLine();
// Write to the file in Bob's personal directory for this program (i.e. Bob/textfile.txt)
FileOutputStream file = new FileOutputStream(directoryName + "/" + filePath);
file.write(text.getBytes());
Is the second-last line a vulnerability? If so, how can the program be made more secure (particularly in Java, C++ and C#)? One way is to validate input for escape characters. Anything else?
The simplest solution here is to have a whitelist of acceptable characters. Modifying your original code (to include Java conventions, since you said you’re new…)
The default implementation of any JVM runs with all the access permissions of the user. Using the
File.canWrite()method will help ensure that the user won’t write over a file he/she has no permission to. The MOST secure solution (specifying EXACTLY where the file will go) would be to usecom.sun.security.auth.module.UnixSystem.getName()and use that to build the
/home/$USERpart of the directory name. Some solutions might tell you to use
System.getProperty("user.home"):or some such, but those rely upon easily changeable environment variables.
I tried to be thorough, I hope this helps.