Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent XSS in the following code?

I wrote some code in HTML5 + Javascript, that when a User enters his name in User, then it gets reflected back like "Hello <user>" .Now this script is vulnerable to XSS (Cross site scripting).

Here is my code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Forms Welcome</title>

<script>
function write_name(){

    var welcome_parra = document.getElementById('welcome');
    var name =  document.getElementById('name');
    welcome_parra.innerHTML = "welcome " + name.value;
}
</script>
</head>

<body>
    <p id="welcome"></p>
    <form>
        Username: <input type="text" name="username" maxlength="20" id="name"/>
        <input type="button" value="done"onclick="write_name();">
    </form>
 /body>

</title>

Now, when I enter the payload "><img src=x onerror=prompt(404)>, I get a prompt of XSS. So how do I rectify it?

Can anyone please check the host, try and patch the bug and give me a reason?

like image 577
Yada Rahall Avatar asked Dec 14 '15 07:12

Yada Rahall


People also ask

How can XSS be prevented?

In general, effectively preventing XSS vulnerabilities is likely to involve a combination of the following measures: Filter input on arrival. At the point where user input is received, filter as strictly as possible based on what is expected or valid input. Encode data on output.

What is XSS attack with example?

Examples of reflected cross-site scripting attacks include when an attacker stores malicious script in the data sent from a website's search or contact form. A typical example of reflected cross-site scripting is a search form, where visitors sends their search query to the server, and only they see the result.

What is XSS protection?

The HTTP X-XSS-Protection response header is a feature of Internet Explorer, Chrome and Safari that stops pages from loading when they detect reflected cross-site scripting (XSS) attacks.


1 Answers

You can HTML-encode the input to make it XSS-safe. Add function:

function escapeInput(input) {
    return String(input)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
}

And encode user input:

<script>
function write_name(){

    var welcome_parra = document.getElementById('welcome');
    var name =  document.getElementById('name');
    welcome_parra.innerHTML = "welcome " + escapeInput(name.value);
}
</script>
like image 141
Pavel Morshenyuk Avatar answered Sep 21 '22 11:09

Pavel Morshenyuk