Are Cookies a Security Risk?

谁说胖子不能爱 提交于 2019-12-04 14:43:44

Could a user modify the cookie data to inject malicious code? Should cookies be sanitized as they're retrieved by the script?

Inject malicious code? Not PHP code, but you are right that you should sanitize cookie values before working with them.

Cookies can be easily modified, added and deleted by users and should be treated as untrusted user input. They are just as prone to XSS and SQL injection vunlerabilities as any other user input.

Further, unless you're using SSL, cookies are just as prone to sniffing as GET or POST data in a request. Malicious internet services can intercept or modify cookies. Also see Firesheep for an example of how cookies can be misused and mistrusted.

There is no inherent security risk in using cookies. The security risks come from your handling of the cookie data, and what data you store in the cookies. If, for example, you do something like this:

<h3>Hello, <?php echo $_COOKIE['user']; ?>!</h3>

...then the user will be able to inject arbitrary code into your page (XSS vulnerability). To fix this security problem, you must properly escape the cookie data for the HTML context:

<h3>Hello, <?php echo htmlspecialchars($_COOKIE['user']); ?>!</h3>

All vars in PHP with $_ ($_POST, $_GET, $_COOKIE, $_FILE, $_SESSION) in the front of the name should checked before you put them on the page or in a database.

You could use htmlentities( $str ) to protected most of the injections.

Cookies are just another form of input from the client, in that a client can send you anything they want in a cookie and your app must not trust what is submitted in a cookie until you sanitize/validate it.

Good guidance on performing data validation, which should be properly applied to all inputs into your application, including cookies, is provided by OWASP and can be found here. The short form is: do accept-known-good validation where you clearly define acceptable inputs and only accept those. Having a blacklist in addition to block known-bad patterns (in concert with a good accept-known-good approach, not to replace it) is a good idea too.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!