Archive

Posts Tagged ‘javascript’

Detecting and Fixing XSS using OWASP tools

Much have been written about XSS vulnerabilities scanning. In this article we will try to go a little further and show how to fix them.

To illustrate the whole process, going from initial detection to providing a fix, we will use a very simple app consisting of two JSP pages: one is a payment form for credit card transactions and contains some XSS exploitable code. The other one has such code fixed: the later is just a patched version of the former. We will see how an attacker could trick users, exploiting the present XSS vulnerability, to collect their credit card data.

(Download vulnerable app)

XSS Attacks

 

The goal of XSS attacks is to have a injected script executed by the user web browser. In most cases, user is not even aware of what is going on. For further information about XSS please have a look at OWASP XSS Attack Description.

Let us have a look at our sample app. The vulnerable JSP (xss_html.jsp) contains the following code fragment:


<% 
final String amount = request.getParameter("amount"); 
Enumeration pNames = request.getParameterNames(); 
while (pNames.hasMoreElements()){     
   final String pName = pNames.nextElement();     
   final String pVal = request.getParameter(pName);     
%>
    <input type="hidden" name="<%=pName%>" />" value="" />;</pre>
<table>
<tbody>
<tr>
<td>Credit card</td>
<td><input type="text" maxlength="16" name="cc" size="16" value="" /></td>
</tr>
<tr>
<td>Exp Date (mm/yy)</td>
<td><input type="text" maxlength="2" name="expMonth" size="2" value="" />
/<input type="text" maxlength="2" name="expYear" size="2" value="" /></td>
</tr>
<tr>
<td>CVV2</td>
<td><input type="text" maxlength="2" name="expMonth" size="2" value="" />
/<input type="text" maxlength="2" name="expYear" size="2" value="" /></td>
</tr>
<tr>
<td colspan="2"><input id="button1" type="submit" name="button1" value="Pay" /></td>
</tr>
</tbody>
</table>

The form receives amount to charge as an HTTP Request parameter, collects credit card data form user and them charges her (of course, such last step is not included, you can try with any non-real credit card data). Users could be redirected here from any ecommerce site using a URL such as http://……/XSS_Vulnerable/xss_html.jsp?amount=12.25 (again, nobody would choose such a path for a payment gateway pretending to be a trusted one). But let us see what happens if an attacker tricks someone into loading a malicious URL as the one included in index.jsp instead when the user press Pay button (Firefox 24.0 for Linux):

firefox_vulnerable

Just an alert, but injected Javascript code could have created an image or some other kind of link, so the attacker would have been able to collect the data by just looking at Apache access logs. Indeed, some browsers are able to identify such threats and will not execute injected scripts, as shown (Chromium 28.0 for Linux).

chrome_refuses_exec_script

XSS Detection

 

Fortunately, there are a lot of tools that perform XSS threats scanning so, for the most common issues, there is no need to look at every line of code in every web page when trying to locate such vulnerabilities. One of those tools is OWASP Zed Attack Proxy Object (ZAP). Although it would not be fair to say it is just a XSS scanner, as it provides many many more interesting features.

ZAP can be used as a proxy (indeed, it is based on older Paros Proxy) being able to scan all pages accesed during the session. However, we are just going to introduce the URL( http://……/XSS_Vulnerable/xss_html.jsp?amount=12.25) and press the Attack button (we are using ZAP 2.2.2). To avoid several warnings and making scanning faster we disabled all scan types except for XSS.

ZAP_XSS_vulnerable

Starting from provided URL ( http://……/XSS_Vulnerable/xss_html.jsp?amount=12.25) ZAP has made several checks adding javascript code to be injected.

The tab at the bottom shows one successful attempt of a XSS attack. ZAP has replaced the numeric value of amount parameter by and URL encoded javascript code (as seen in URL field) which is just “><script>alert(1);</script> in plain text (as seen in Evidence field).

Moreover, in the tab above, where HTTP response is shown, the result of the XSS attack is clearly shown: the injected code in amount parameter first closes the double quotes (“) around value for amount field and closes HTML input (>). Afterwards, it adds the script alert(1); (<script>alert(1);</script>). The resulting HTML code to be executed by web browser contains:

<input type="hidden" name="amount" value=""><script>alert(1);</script>" />

XSS Fix

 
Although there is not a single fix for all XSS attacks, all of them are based on input validation, where “input” could be any from HTTP Request parameters, HTTP Headers values or even names… all depends on what the code uses as input.

In our sample app, a HTTP Request parameter is being used to write HTML code.

OWASP provides OWASP Enterprise Security API (ESAPI) in several languages, including, of course Java. ESAPI includes much more functionality related to security, from XSS and CSRF to crypto.

To fix our XSS vulnerability, we are just using a ESAPI encoder (ESAPI 2.1.0). The fix is based on writing the received amount parameter HTML encoded instead of as just received. This way, the user web browser will not execute the javascript code, as it will be seen as the value of the amount parameter.

The fix requires just HTML encoding the amount parameter (see xss_html_esapi.jsp) as follows:

<form method="POST" name="sendForm" id="sendForm" onsubmit="return sendPaymentRequest()">

<%
final String amount = request.getParameter("amount");
Enumeration<String> pNames = request.getParameterNames();
while (pNames.hasMoreElements()){
    final String pName = pNames.nextElement();
    final String pVal = request.getParameter(pName);

    final org.owasp.esapi.Encoder esapiEnc = DefaultEncoder.getInstance();
    final String encPVal = esapiEnc.encodeForHTML(pVal);

    %>
    <input type="hidden" name="<%=pName%>" value="<%=encPVal%>" />
    <%
}
%>

<table>

Running ZAP against fixed JSP (xss_html_esapi.jsp) does not report XSS Vulnerabilities.

Advertisements

XSS: detectar, explotar y corregir vulnerabilidades (II, inyección JS)

En el post anterior vimos cómo inyectar un script en un formulario HTML. También vimos cómo corregir la vulnerabilidad usando la librería ESAPI.

Sin embargo, cómo explotar y corregir la vulnerabilidad depende de cómo se estén usando los parámetros vulnerables. En el ejemplo anterior se usaban para completar código HTML. A continuación veremos una situación en la que el parámetro vulnerable se usa para completar código Javascript.

Seguimos con el mismo ejemplo del atacante que pretende obtener tarjetas de crédito aprovechando una vulnerabilidad en una pasarela de pago. La única diferencia , en este caso, será que la página con el formulario de entrada, en lugar de usar el parámetro amount para completar un input del formulario (HTML), actualiza el valor de dicho campo del formulario mediante Javascript.

A continuación el susodicho JSP:

<%@ page language="java" contentType="text/html; charset=ISO-8859-15"
 pageEncoding="ISO-8859-15"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15">
<title>XSS vulnerable</title>
<script language="javascript">

function sendPaymentRequest(){
 form = document.getElementById("sendForm");
 alert("Would submit form request... ");
 return false;
}
</script>
</head>
<body>
<h3>Inserte los datos de su tarjeta</h3>
<form method="POST" name="sendForm" id="sendForm" 
onsubmit="return sendPaymentRequest()">

<table>
<tr>
<td> Cantidad a pagar</td>
<td>
<input type="text" name="amount" maxlength="6" size="6" value="" /> &euro;
<td>
</tr>
<tr>
<td>Tarjeta de crédito</td>
<td> <input type="text" name="cc" value="" maxlength="16" size="16"/>
</td>
</tr>
<tr>
<td>Fecha caducidad (mm/yy)</td>
<td>
<input type="text" name="expMonth" value="" maxlength="2" size="2"/>
/<input type="text" name="expYear" value="" maxlength="2" size="2"/></td>
</tr>
<tr>
<td>CVV2</td>
<td><input type="password" name="cvv" value="" maxlength="3" size="3"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Realizar Pago" name="button1" id="button1" />
</td>
</tr>
</table>
</form>

<script language="javascript"> 
var form = document.getElementById("sendForm"); 
<% final String amount = request.getParameter("amount"); %> 
form = document.getElementById("sendForm"); 
form.amount.value = "<%=amount%>"; 
</script>

</body>
</html>

Se ha resaltado el pequeño código Javascript que actualiza el valor de amount en lugar de completarlo directamente en HTML como se hacía en el post anterior.

Si probamos a inyectar el código anterior, aunque sigue siendo posible, no produce los efectos deseados. El código a inyectar, en este caso, podría intentar dejar el fragmento de código JS tal que así:

<script language="javascript">
var form = document.getElementById("sendForm");
form = document.getElementById("sendForm");

form.amount.value = "23.34" ; 
function sendCC(){ 
form = document.getElementById('sendForm'); 
cc = form.cc.value; 
cvv = form.cvv.value; 
year = form.expYear.value; 
month = form.expMonth.value;
alert('Sending to bad guy cc:' + cc + ' date:' 
+ month + '/' + year + ' cvv:' + cvv); return sendPaymentRequest(); 
} 
window.onload = function () { 
var submitForm = document.getElementById('sendForm');
submitForm.setAttribute('onsubmit', 'sendCC()'); 
} //";

</script>

Produciendo de nuevo el mismo efecto que en el caso HTML, como puede apreciarse:

 

En este caso la solución consistiría en reemplazar la línea:

final String amount = request.getParameter("amount");

por

final String amount = ESAPI.encoder().
encodeForJavaScript(request.getParameter("amount"));

La única diferencia con respecto a la solución en el caso en que inyectábamos en HTML es que se ha usado el método encodeForJavaScript en lugar de encodeForHTML.

Mozilla Popcorn o como llevar el multimedia en la web al límite

11/18/2011 1 comment

Una iniciativa para sacarle todo el partido al componente multimedia de HTML5 y que está compuesto por dos herramientas: por un lado Popcorn.js, un framework de javascript dirigido a eventos con el que añadir a tu web en apenas unas líneas vídeos, mapas, widgets para Twitter e incluso artículos de Wikipedia

http://www.genbetadev.com/desarrollo-web/mozilla-popcorn-o-como-llevar-el-multimedia-en-la-web-al-limite

%d bloggers like this: