Servlet API provides a convenient way to set cookies:
response.addCookie(new Cookie(name, value))
JavaDoc tells:
With Version 0 cookies, values should not contain white space, brackets, parentheses, equals signs, commas, double quotes, slashes, question marks, at signs, colons, and semicolons. Empty values may not behave the same way on all browsers.
However it doesn't tell what happens if these characters are present in the value.
If value comes from untrusted source, may I use the API to safely set the value without extra pre-processing or do I open the door for some kind of injection?
If value comes from untrusted source, may I use the API to safely set the value without extra pre-processing?
No, you may not. The API does not take care of this for you. This would otherwise be explicitly specified in the Javadoc. The API may not know beforehand if you're using version 0 (Netscape) or version 1 (RFC2965) cookies.
Best would be to just URL-encode the cookie name/value beforehand so that you can ensure that you end up with a safe cookie name/value.
String safeCookieName = URLEncoder.encode(name, "UTF-8");
String safeCookieValue = URLEncoder.encode(value, "UTF-8");
response.addCookie(new Cookie(safeCookieName, safeCookieValue));
// ...
Alternatively, you could also use regex to strip all illegal characters off beforehand. Only alphabetic characters, digits, hyphens, underscores, periods, tildes and probably a few more (browser dependent!) are allowed. All others needs to be stripped off.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With