Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is ouputing html through php security risk using cookie?

Tags:

html

php

im relatively new to php and was hoping you could help me understand why you should sanitize html when 'echo'ing , specially if data is from cookie..

i.e instead of

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

you should do

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

this is what i understand.

cookies are stored on client side, hence are a security risk since the data in them can be manipulated/changed by evil users (lol @ evil) .

but since the cookie is stored on client side, it means a client can only change his own cookie, which means if he adds some kind of malicious code to $_COOKIE['user'] , when the cookie does run, the malicious code will only be shown to one user (who changed the cookie in the first place) and no one else!? so whats the problem?

like image 258
Ahmed-Anas Avatar asked Feb 21 '23 06:02

Ahmed-Anas


2 Answers

You're assuming that the user changed his own cookie. Cookies can be changed by a third-party (Edit: Using additional software. Third-party websites cannot change the cookie directly). This would enable someone to inject malicious code into the user's browser, changing their user experience and potentially posing an additional security risk for your code.

like image 138
Chuck Callebs Avatar answered Feb 23 '23 00:02

Chuck Callebs


Instead of just looking security aspect, there is a user experience aspect. The code you present is not really useful for security because risk are very poors in this case BUT if username can contains quote or < > signs, the user will not understand why its login is not displayed correctly.

Using such a code garanties that you will display correctly the username (and add extra security), no matter what kind of characters you allow during the registering process.

like image 35
Jerome Cance Avatar answered Feb 23 '23 00:02

Jerome Cance