开发者

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 val开发者_StackOverflowue.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜