Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to escape cookie values when setting from servlet API?

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?

like image 904
Vilmantas Baranauskas Avatar asked Jul 29 '11 07:07

Vilmantas Baranauskas


1 Answers

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.

like image 91
BalusC Avatar answered Oct 03 '22 02:10

BalusC