I’m writing a Ruby on Rails app which with user input will generate some Java code that the server will then compile & execute. (Don’t ask why 😉
The problem is the users are able to enter in strings which need to be used as string literals in the Java. I was previously white-listing the characters but this approach is providing insufficient flexibility for the users. How can I sanitize the string in RoR in order to prevent users terminating the strings and thus being able to execute arbitrary code on the server.
The only way to terminate a string in java is
", but you wil also want to check for Unicode literals\u...as users could enter the Unicode char of illegal chars (the first thing the java compile does is search for Unicode literals and replace them with the correct character). If you disallow both"and\you should not be able to terminate java strings.You have not mentioned what you are using this input for but a safer way would be to save user input to a separate file next to your java class and instead of doing something like:
You can read the text from the user input file you saved:
and
readUserInputFile()is something like:This way a user can enter whatever they want and there is a clear boundary between the generated java code and the user input which cannot be crossed.