xss attacks

you may have heard of xss before but thought, “wtf is that”. xss stands for Cross-Site-Scripting(XSS). you’re probably thinking: okay… so what. xss is not as dangerous as most vulnrebilities in website scripts but can still be very serious.

examples

okay i’ll show you what exactly happens with an xss attack and why its bad.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
 
    if ( isset( $_SESSION['name'] ) )
    {
        echo 'Your name is:<br />'.
              $_SESSION['name'];
    }
    else
    {
        $_SESSION['name'] = $_GET['name'];
        echo 'Session set as: '. $_GET['name'];
    }
 
 
?>

okay so that looks pretty harmless right? wrong. if i were to send this link to my friend: http://site.com/page.php?name= the part in bold is the script that is being injected into your code. the user would be redirected to an evil site because of your insecure script.this is not however all the xss is. xss can be used for various other malicious things such as cross-site-request-forgery. i wont go into too much detail because it can seem daunting for beginners so if you google CSRF then you can read about it on wikipedia or something.

how to prevent it

okay so now you know why its bad and what can happen its time to stop it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
 
function clean ( $string )
{
    $malicious = array( 'javascript' , 'script>' , 'style>' , 'meta>' );
    $string    = str_replace( $malicious , '' , $string );
    $string    = htmlspecialchars( mysql_real_escape_string( $string ) );
    return $string;
}
 
    if ( isset( $_SESSION['name'] ) )
    {
        echo 'Your name is:<br />'.
              $_SESSION['name'];
    }
    else
    {
        $_SESSION['name'] = clean( $_GET['name'] );
        echo 'Session set as: '. $_GET['name'];
    }
 
 
?>

so in our php code we have created a function called clean. this function will take the value of $string and use str_replace to remove malicious code parts, use htmlspecialchars to turn <, >, ; etc.. into hex values so that they can not be used in a malicious way in our script and will just be displayed as text instead of executing code. just for an added measure we use mysql_real_escape_string to stop any sql injection even though our script doesn’t have an sql query its there incase you decide to use this function in the future. thanks if you read it all it took me a while to write :3