XSS Attacks and Prevention Methods in PHP

logo.png


XSS Attacks and Prevention Methods in PHP


The PHP code writers who read this article will learn;

What XSS is,
How cookies work,
How to protect themselves easily from XSS.


What is XSS?

XSS (Cross Site Scripting) is briefly described as running code on a site using HTML and JavaScript in a way that poses a danger to the user entering the site. Malicious users can steal cookies sent to users for the purpose of obtaining information from visitors or allowing them to use their accounts without repeatedly entering passwords, using XSS, and impersonate themselves as if they were that visitor in the system.

How Do Cookies Work?
A cookie can be described as a tool that allows the client - that's you - to store any information, session number, etc. for a domain and provides information only for the domain and file path to which it is sent. So, when you enter any site, a cookie may be sent from the other side to keep your information. (If your browser's security settings are not very strict, it will automatically accept these cookies)

Use cases are generally for comparing user information or your session number on the other side. At this point, you may suspect the other side of capturing information from your other cookies, but as mentioned earlier, browsers only send this information if the domain and file path (e.g., a cookie set for www.foo.com/hede address will never be sent to www.foo.com/hodo address) match, and unless there is an extraordinary situation, this does not pose a security issue.

How Does XSS Work?

Since this article may be read by individuals inclined to do dangerous things, I won't go into explicit details. In summary:

There is a cookie method in the JavaScript language (i.e., ********.cookie) that manages cookies in JavaScript. Using this method, cookies belonging to the page can be obtained, read, and modified. Malicious individuals exploiting XSS vulnerabilities use this feature of JavaScript to capture the cookie information of the user browsing the page and try to replace it with their own. Therefore, visitors browsing a page with an XSS vulnerability, especially if they have an account on that page, need to be very careful. In addition, site owners taking serious precautions in this regard can prevent incidents from occurring. We'll discuss solutions shortly...

[1] With the HttpOnly statement that will be added to the Set-Cookie feature in HTTP headers that comes with the new versions of PHP, browsers will not retrieve/show the cookie through JavaScript if the statement is present...

Now let's learn how to protect against these attacks...

What Are the Protection Methods?

To effectively protect against the XSS attacks mentioned above, let's first consider how we can filter incoming data from the user... To execute the code required to steal cookies, it is necessary to write it between (Read Forum Rules)(Read Forum Rules) tags so that proper filtering of the < and > characters required in HTML tags can solve a significant part of our problem. So:

Code:

Kod:
<?php
htmlentities($xss_potential_data);
// The htmlentities() function replaces characters such as <, >, & in the parameter with character groups that are practically harmless and look normal on an HTML page, such as '<', '>', etc.
// For additional protection, you can specify 'ENT_QUOTES' as the second parameter and also filter quotes...
// (see php.net/htmlentities)
?>

Let's do something like this. But is this one function enough? Actually, no... Since the data sent from the URL can be in hexadecimal format for any ASCII character (e.g., %20 for space), we can use the urldecode() function to decode the data, including ASCII format data sent from the URL, to ensure security:

Code:
Kod:
<?php
htmlentities(urldecode($xss_potential_data));
?>

Is this enough? Sometimes, depending on where the data is used, we may need to make different filterings. For such filterings, the quote****() [2] and addslashes() [3] functions are suitable. Taking all this into account, let's write a function as follows:

[2] Adds a backslash () in front of characters ., \, +, *, ?, [^], ($).
[3] Adds a backslash () in front of the quotation mark.


Code:


Kod:
<?php
function dataFilter($data, $mode = 1, $option = 0) {
    // We set the default function operation level to 1 and the option to 0.
    $data = urldecode($data);
    // We decode the data coming from the URL for secure filtering.

    if ($mode == 0) {
        // If the level is 0, return only the decoded version:
        return $data;
    } else if ($mode == 1) {
        // If the level is 1, return the version with htmlentities() applied.
        // If the option is 1, ensure that the function also filters quotes:
        return ($option == 0) ? htmlentities($data) : htmlentities($data, ENT_QUOTES);
    } else if ($mode == 2) {
        // If the level is 2, return only the version with quote****() applied.
        // If the option is 1, add htmlentities(), and if the option is 2, also filter quotes:
        return ($option == 0) ? quote****($data) :
               (($option == 2) ? htmlentities(quote****($data), ENT_QUOTES) : htmlentities(quote****($data)));
    } else if ($mode == 3) {
        // If the level is 3, return the version with addslashes() applied.
        // If the option is 1, add the result of addslashes() and quote****() function.
        // If the option is 2, add htmlentities() to the unopinionated state.
        // If the option is 3, add htmlentities() to the first option:
        if ($option == 0)
            return addslashes($data);
        else if ($option == 1)
            return addslashes(quote****($data));
        else if ($option == 2)
            return htmlentities(addslashes($data));
        else if ($option == 3)
            return htmlentities(addslashes(quotem eta($data)));
    }
}
?>

This function aims to use all the information mentioned by adding an operational level, so that it can be managed with a single function in different areas before using it more generally in the continuation of the article.)
We will use the function above more generally later in the article, but before that, a few examples of its usage:

dataFilter($data, 1): htmlentities() is applied to the $data variable. An average filtering.
dataFilter($data, 2, 2): An option level where quotes are also filtered with htmlentities(), and quote****() is used... It may cause problems to use it for every data because it filters too many characters.
dataFilter($data, 3, 3): A paranoid filtering where all mentioned functions are used. I don't think you will need it very much; it usually causes problems when they are all together.
Arrays Received from $_POST and $_GET
In this final part of our article, we will show how to filter both the useful but very confusing function we wrote above - who memorizes it anyway? :D - and the two important arrays received from the user...


So:

Let's filter these two constant arrays with the htmlentities() and addslashes() functions of our dataFilter() function at the operational level, and
Create arrays named $_POSTS and $_GETS to store the filtered data:
Code:


Kod:
<?php
$_GETS = array();
$_POSTS = array();

foreach ($_GET as $key => $value) {
    $_GETS[$key] = dataFilter($value, 3, 2);
}

foreach ($_POST as $key => $value) {
    $_POSTS[$key] = dataFilter($value, 3, 2);

 
Üst

Turkhackteam.org internet sitesi 5651 sayılı kanun’un 2. maddesinin 1. fıkrasının m) bendi ile aynı kanunun 5. maddesi kapsamında "Yer Sağlayıcı" konumundadır. İçerikler ön onay olmaksızın tamamen kullanıcılar tarafından oluşturulmaktadır. Turkhackteam.org; Yer sağlayıcı olarak, kullanıcılar tarafından oluşturulan içeriği ya da hukuka aykırı paylaşımı kontrol etmekle ya da araştırmakla yükümlü değildir. Türkhackteam saldırı timleri Türk sitelerine hiçbir zararlı faaliyette bulunmaz. Türkhackteam üyelerinin yaptığı bireysel hack faaliyetlerinden Türkhackteam sorumlu değildir. Sitelerinize Türkhackteam ismi kullanılarak hack faaliyetinde bulunulursa, site-sunucu erişim loglarından bu faaliyeti gerçekleştiren ip adresini tespit edip diğer kanıtlarla birlikte savcılığa suç duyurusunda bulununuz.