Do I need to avoid cookie values ​​when setting from the servlet API?

The Servlet API provides a convenient way to set cookies:

response.addCookie(new Cookie(name, value)) 

JavaDoc reports:

When using cookies of version 0, the values ​​must not contain spaces, brackets, parentheses, equal signs, commas, double quotation marks, slashes, question marks, signs, colons, and semicolons. Empty values ​​may not behave the same in all browsers.

However, he does not say what will happen if these characters are present in the value.

If the value is obtained from an unreliable source, can I use the API to safely set the value without additional preprocessing or open the door for some kind of injection?

+7
source share
1 answer

If the value is obtained from an untrusted source, can I use the API to safely set the value without additional preprocessing?

No, you can’t. The API will not take care of this for you. Otherwise, this would be explicitly stated in Javadoc. The API may not know in advance if you are using version 0 ( Netscape ) or version 1 ( RFC2965 ).

It would be best to just URL-encode the cookie name / value in advance so you can make sure that you end up with a secure 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 can also use regex to pre-remove all illegal characters. Only alphabetic characters, numbers, hyphens, underscores, periods, tildes, and possibly a few more are allowed (browser dependent!). All others must be deleted.

+6
source

All Articles