I am getting a String into Java program from a user via command line arguments.
The question is what kind of checks I should perform to prevent possible attacks and vulnerabilities?
I am not expert in security area, but as far as I know
- In C too long line specified by user and handled improperly could lead to buffer overflow
- In PHP line containing ` characters and handled improperly could lead to SQL injection
For now I can not think about any specific format of a String to apply some regex to check. It can be arbitrary, but if is looks harmful I want to quit immediately. The string might to send to a Java server with network, there it might be used for an SQL query.
if (args.length > 0) {
String arg0 = args[0];
if (!isValidString(arg0)){
System.exit(1);
}
}
public boolean isValidString (String str) {
if (str == null) return false;
//TODO: many more checks here
return true;
}
I am sure Java is much more secure than C or early PHP, but what should I be aware about?
If this main class does nothing other than passing its argument to somewhere else, then it’s not its responsibility to validate the string.
If this string finally goes to a class which uses it in a SQL query, then it’s the responsibility of this class to use a prepared statement and thus make sure no SQL injection attack is possible.
If this string ends up being part of a generated HTML page, then it’s the responsibility of the HTML generator to HTML-escape the string.
A string, by itself, is never harmful. If you have to validate it, then you need to know when it is valid, and when it’s not. And it depends on the context.