问题
Assume we have a website that asks the user for his name.
The website then stores this value in a cookie, and on the next page, retrieves it via PHP and uses it somehow (perhaps the page displays the name as text).
Could a user modify the cookie data to inject malicious code? Should cookie data be sanitized as it's retrieved by the script?
(This is a hypothetical scenario. Obviously a cookie wouldn't be necessary here.)
回答1:
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.
回答2:
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>
回答3:
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.
回答4:
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.
来源:https://stackoverflow.com/questions/8992415/are-cookies-a-security-risk