Are cookies a security risk?

Suppose we have a website that asks the user for his name.

Then the website saves this value in a cookie, and on the next page it extracts it through PHP and uses it somehow (perhaps the page displays the name as text).

Can a user modify cookie data to enter malicious code? Should cookie data be sanitized as it is received with a script?

(This is a hypothetical scenario. Obviously, a cookie is not needed here.)

+3
source share
4 answers

Can a user modify cookie data to enter malicious code? Should cookies be cleared as they will be restored using a script?

Enter malicious code? Not PHP code, but you’re right that you must sanitize cookie values ​​before working with them.

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

In addition, if you do not use SSL, cookies are as prone to sniff as the GET or POST data in the request. Malicious Internet services may intercept or modify cookies. Also see Firesheep for an example of how cookies can be misused and untrusted.

+4
source

There is no built-in security risk in using cookies. Security risks come from the processing of cookie data and data stored in cookies. If, for example, you do something like this:

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

... then the user can enter arbitrary code on your page (XSS vulnerability). To resolve this security issue, you must properly avoid the cookie data for the HTML context:

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

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

You can use htmlentities( $str ) to protect most of the injections.

+1
source

Cookies are just another form of input from the client, as the client can send you whatever he wants to the cookie, and your application should not trust what is sent to the cookie until you sanitize / verify it.

A good guide to perform data validation , which should be appropriately applied to all the inputs to your application, including cookies, is provided by OWASP and can be found here . Short form: accept acceptable-well-validation, where you clearly define acceptable input and accept it only. Having a blacklist in addition to blocking known bad templates (combined with good agreement, well known and non-substitute) is also a good idea.

0
source

All Articles