Tutorials PHP XSS injections

XSS injections

Today will be how to secure your website from XSS injections. Injections are ways for hackers to break your website. Fortunately, they are easily prevented with a few lines of code.

What are injections?

Injections are when you allow users to submit anything to your site without filtering the data. It's when you allow users to submit forms that enter data into your database or display it on your web page.

What is an XSS injection?

XSS stands for cross site scripting and it happens when you display user data on your website. Hackers will use the opportunity to insert malicious code, usually JavaScript, into your site to affect other users.

What can XSS do?

Anything client side code can do, meaning HTML, CSS, JavaScript or anything coded to the browser. They can create a fake login form to steal user passwords or use JavaScript to steal cookies. They can redirect unknowing users to their look alike site to ask them to login, also known as phishing. They can even override your code and replace your content. Basically, they can do whatever they want.

Am I vulnerable to XSS right now?

To find out if you're currently vulnerable to XSS right now, throw this little piece of code on anything that that will display your data. Forums, blogs, comments, ect... View the page where you display the data and if you get a pop up message, you are vulnerable to XSS.

<script>alert("You got hacked!");</script>

How do I stop XSS injection?

It's pretty easy actually; one line of code will do the trick. PHP has a built in function that converts all HTML tags to their code form. Browsers will display this code for its literal meaning without processing it. This will protect you against most XSS attacks. htmlEntities encodes all characters to their HTML counterparts. The second parameter, ENT_QUOTES, encodes single quotes since the function by default allows single quotes to pass through.

$user_data = '<script>alert("You got hacked!");</script>';

// Browsers see &lt;script&gt;alert(&quot;You got hacked!&quot;);&lt;/script&gt;
// Users see <script>alert("You got hacked!");</script>
echo htmlEntities($user_data, ENT_QUOTES);

What other types of injections are there?

The most common are XSS, SMTP and SQL injections. SQL injection is when hackers try to manipulate your database. I'll dedicate an entire tutorial to SQL injection in a later tutorial. SMTP is mail injection and I'll talk about it in the mail tutorial that's coming soon.

Go through your code and patch up anything that has a security hole. You should always escape anything that users are allowed to touch before displaying it on the page. See you next time on PHP Trainee!

Posted by on . Category: PHP


Comments

No comments posted yet

You need to register or login to post new comments.