How to prevent reflected XSS on PHP website basically?

How to prevent reflected XSS on PHP website basically?

XSS7-SedatOzdemir

Hello all,
Today I’m gonna tell you how can we prevent XSS attacks on our PHP projects basically. First of all, we can understand the attack:

Proof of Concept

Attack:

There is input fields and this fields reflected to another page when I filled.

XSS1-SedatOzdemir.png

Image 1. Add new user into system

So If we using database, we have to list that record some data table. Example, I used PDO and while loop for listing my records.

Image 2. Listing to data table functions

But this method is unsafe. Because if we want to add user into system (ex: Image 1) and if there any blocks for special character like ‘, <, &, /, we can write any javascript/ html code here. And after that, If we visit to users page, all javascript will be listed and executed. The real risk is hackers can be steal your cookies and can be hijack your account. Example:

I’m going to write some javascript code into username field.

Image 3. Add new user page

As you can see, javascript code executed my users page.

Image 4. Executed javascript code

 

Prevent:

Well, what can we do? We can use HTML encoding method (htmlspecialchars).

Image 5.  Using htmlspecialchars function

Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with these conversions made. If you require all input substrings that have associated named entities to be translated, use htmlentities() instead.

If the input string passed to this function and the final document share the same character set, this function is sufficient to prepare input for inclusion in most contexts of an HTML document. If, however, the input can represent characters that are not coded in the final document character set and you wish to retain those characters (as numeric or named entities), both this function and htmlentities() (which only encodes substrings that have named entity equivalents) may be insufficient. You may have to use mb_encode_numericentity() instead.

Performed translations

 
Character Replacement
& (ampersand) &amp;
 (double quote) &quot;, unless ENT_NOQUOTES is set
 (single quote) &#039; (for ENT_HTML401) or &apos; (for ENT_XML1ENT_XHTML or ENT_HTML5), but only when ENT_QUOTES is set
< (less than) &lt;
> (greater than) &gt;

 

As you can see, all malicious characters are encoded and no longer executed.

Image 6.  HTML encoding

Referances:

https://www.php.net/manual/en/function.htmlspecialchars.php
https://portswigger.net/web-security/cross-site-scripting/reflected

See other posts

Tarafından yazıldı
Sedat Ozdemir
Bir yorum bırak

Teşekkürler!

Bloğumu ziyaret ettiğiniz ve yazılarımı okuduğunuz için teşekkürler!