الاثنين، 17 سبتمبر 2012

Bypassing WAFs with non-alphanumeric XSS.

This post is an attempt to expand what we already discussed on Patricio’s blog, but with a focus on security in web applications. Although this post will not be a shocker, I will try to make it as interesting and entertaining as possible. If you have not read what Patricio and I wrote on his blog you should go there before continuing, otherwise you may not understand properly some of the references I will be making.

Cross site scripting attacks

As some of you may know, the common security method to prevent XSS is by escaping attacker controlled input (which ultimately becomes webserver output, assuming a persistent web form attack for example), so having a template engine doing this automatically is the best practice. Unfortunately not everybody follows this recommendation, and when manually escaping, people are really prone to making mistakes. So, to overcome this, Web Application Firewalls (WAFs) and Intrusion Detection/Prevention Systems (IDS/IPS) do their part mitigating what has been left behind.

So from an attacker’s point of view we have three stages to bypass, user input sanitization (due to manual escaping mistakes), WAF filtering (by rules such as those provided by modsecurity), and browser protections (which are not covered in this article).

Bypassing WAF filters

Basically, the purpose of a network-based application layer firewall is to monitor and block user content which violates pre-defined policies. In our case, these polices are patterns of user input which can potentially end up in an attack.

The main idea of bypassing a WAF is to craft requests semantically equivalent to a XSS attack for example, while avoiding the security policies.

For XSS, you usually make use of JavaScript’s common methods to steal user information, such as: eval(), Function(), document.write(), document.cookie(), alert(), etc. The problem is, the majority of the WAFs will filter the request immediately if one of these methods are found in a request. Also, if you know the target’s browser, with the help of its API you can use non-standarized methods to extend the attack, which can lead to an easier bypass since most of non-standarized methods are not taken into account by most policies.

But applying what we have learnt about encoders like hieroglyhphy (my python port), jsfuck, and others, we can obfuscate our attack and payload properly. The downside would be that the encoding will increase considerably the amount of characters used on the original request (a friend’s research has shown inflation rates of between 600 and 1000 times, with 650-850 being typical when obfuscating an entire script, such as for exploitation), but we don’t really need to fully encode it, we can just encode parts of it, like half of a method’s name or sensitive parts for exploitation.

Here’s a simple example that you can test in your browser’s interactive console:
eval("aler"+(!![]+[])[+[]])("xss")

If you have not had any luck yet don’t get sad, there are still other ways to try to trick the security measures. Since JavaScript has two different syntactic forms to access properties, you can access an Object method like a dictionary: object.method(arguments) === object["method"](arguments)

An example with document.cookie() would be: document["cookie"], where cookie is passed as a string which you can obfuscate like this:
document[({}+[])[!+[]+!![]+!![]+!![]+!![]]+({}+[])...]

I didn’t include the entire obfuscated representation as it is very long (2727 characters to be exact).

There are also alternate ways of accessing them too, in case the document word is also filtered. Since this is a reference to the current window you can use it as a “dictionary” too: this["document"]["cookie"]

Same thing with the rest, like alert():
this["alert"]("xss")
window["alert"]("xss")

Combining them you can get different results, also applying hex encoding is useful, some WAFs get bypassed just with that.

window[(+{}+[])[+!![]]+(![]+[])[!+[]+!![]]+([][+[]]+[])[!+[]+!![]+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]]

this['ale'+(!![]+[])[-~[]]+(!![]+[])[+[]]]()

this['\x64\x6f\x63\x75\x6d'+([][+[]]+[])[!+[]+!![]+!![]]+([][+[]]+[])[+!![]]+(!![]+[])[+[]]][({}+[])[!+[]+!![]+!![]+!![]+!![]]+({}+[])[+!![]]+({}+[])[+!![]]+'kie']

document['\x63\x6f\x6f\x6b\x69\x65']
Here you can find more examples.

Playground

If you already feel like playing a little with this, I made a playground for the anxious people that want to apply what have learnt above. It’s a little script with different kind of vulnerabilities with a basic simulation of a simple WAF ruleset. The goal is to retrieve the cookies from anybody who visits the site, bypassing the security measures with the above. Consider doing it manually.

Click here to go to the playground.

Pyronbee

“We should accept WAFs for what they really are: a method of increasing the cost of attacks, but not necessarily one that might repel every attacker.”
Sometimes you find yourself doing a pentest and the security (WAF, IDS, IPS) starts to block certain requests you perform, for example the ones for an SQL injection. Knowing that a WAF does not see the same as a web server, tweaking our request a little can cause the security mechanisms to ignore it, but the webserver may understand it as a successful request.

One thing that you always must keep in mind is impedance mismatch: “you’re interpreting the stream of data in one way, but there’s a danger that whatever you are protecting is interpreting the same data differently”. Web servers tend to fix malformed requests, and there are modules to correct some urls to specific documents and paths, such as mod_spelling. So you can try to send “broken” requests hoping that the WAF will consider it harmless and the web server interpret it correctly.

So to accelerate the process, I’ve made pyronbee, a tool based on a project titled waf-research (IronBee) on github by Ivan Ristic, creator of ModSecurity, in which you can automate and make custom requests to a certain host to check which formatted requests get filtered and which ones get past the WAF.
(I’m currently making a script to port the test files made for IronBee to JSON syntax in order to use it with mine.)
“In fact, bypassing network-centric security tools is bound to be easier because in general, they perform less HTTP processing (parsing) than web application firewalls.”
In this case, we would use pyronbee to see which .test files are not filtered by security rulesets, using encoded requests for pyronbee with tools like hieroglyphy.
Despite we are trying to bypass a WAF, we are not really doing it in a low-level protocol, since the idea of doing so is to replicate the bypass on foreign browsers as a CSRF/XSS attack. If you want to go any further with this, you can format pyronbee requests to fulfill your needs at that level, but that would be another whole story.

As for the playground, pyronbee won’t be of any help because it’s a php script simulating a WAF with just a str_replace. However yon can host it on your site and play a little with it. Here’s the playground source code, and maybe you might want to use the test/playground/ folder .test files for that.

On pyronbee’s main folder you will find another folder named ‘extra’ where you have a script which can craft standarized HTTP/1.1 GET requests from a list of your own, choosing a desired prefix, in pyronbee’s .test file format.

Side notes and aknowledgments

Just to clarify, hieroglyphy was just an example, there are multiple ways of doing encodings, with more or less characters, but you always have the trade-of between encoding size and charset length. And remember to use url encoding when needed on pyronbee .test files, because for example for the + , the webserver interprets it as a space, and you will generating false positives.

I’d like to thank kernelsmith, an user I met on IRC that was porting hieroglhyphy to ruby with the idea to include it on metasploit as an obfuscator. In the meanwhile we realized that older versions of IE (< 9) and JS in IE9 on ‘quirksmode’ do not support some stuff, like accessing a string as an array, unless the site is using a standarized DOCTYPE. Take this as a side note in case you want to develop obfuscated exploits to bypass AVs. Besides from that, he was really supportive and enthusiastic all the time.

Finally, I will also like to thank snf, a friend, who was very supportive to my ideas during the development of pyronbee.

The quotes I’ve made are from the following paper: Protocol-Level Evasion of Web Application Firewalls.

الأربعاء، 18 يوليو 2012

National program of critical infraestructures and cybersecurity in Argentina



The presidency of our nation through the cabinet of ministers has honoured us inviting Infobyte Security Research to participate in GESI, a "Group of Experts on Security and Computer Law ". The objective of this group is to provide advice to the program that protects the national public sector strategic and critical infrastructures.




The national program of critical infraestructures and cybersecurity, ICIC (spanish acronym), was created by the cabinet of ministers, dependent on the Presidency of the nation, in July of 2011.

The primary mission of the ICIC is to identify and protect critical infrastructures of national public sector, as thus of interjurisdictional agencies, civil society organizations and private sector requiring it. The ICIC has attached so far the following entities: Banco Nación, Argentine army, the National Lottery and the National Institute of Industrial property or PAMI (INSSJP) among others. Infobyte Security Research is one of the first private companies in it, along with others such as Microsoft Argentina or Eset Argentina.

Some of the objectives defined for the ICIC by the resolution 580/2011, governing its creation are: Manage reports of security incidents in the national public sector, monitor the services provided over the internet, establish priorities and strategic plans to lead cybersecurity approach.

Recently, with the aim of advising the ICIC to fulfill its mission, the cabinet of ministers formed GESI. Renowned specialists in the area of law, in the sector of computer crimes of federal police, and from the national office of information technology (ONTI) have been invited to GESI.

Within the private sector, Infobyte Security Research, through its CEO, Francisco Amato, was one of the first companies invited to participate in this advisory group. GESI is also responsible for the creation, generation and editing of content that help an awareness of information security, from different sectors of society

More information:

http://www.icic.gob.ar/paginas.dhtml?pagina=243
http://www.icic.gob.ar/paginas.dhtml?pagina=97

Programa Nacional de Infraestructuras Críticas y Ciberseguridad en Argentina



La Presidencia de la Nación, a través de la Jefatura de Gabinete de Ministros, nos ha honrado invitando a Infobyte Security Research  a participar del GESI, “Grupo de Expertos en Seguridad y Legislación Informática”.  El objetivo de este grupo es brindar asesoramiento al programa que protege las infraestructuras críticas y estratégicas del Sector Publico Nacional.




El Programa Nacional de Infraestructuras Críticas de Información y Ciberseguridad, ICIC, fue creado por la Jefatura de Gabinete de Ministros, dependiente de Presidencia de la Nación,  en Julio de 2011.

La misión principal del ICIC es identificar y proteger las infraestructuras críticas del Sector Público Nacional, como así también  de organismos interjuridisccionales, y de Organizaciones Civiles y Sector privado que lo requieran. Al ICIC se encuentran adheridos entre otros hasta el momento el Banco Nación, el Ejército Argentino, la Lotería Nacional, el Instituto Nacional de la Propiedad Industrial o el PAMI (INSSJP).   Infobyte Security Research es una de las primeras empresas del sector privado adheridas, junto a otras como Microsoft Argentina o  Eset Argentina.

Algunos de los objetivos definidos para el ICIC en la Resolución 580/2011, que regula su creación son: Administrar los reportes de de incidentes de Seguridad en el Sector Público Nacional, monitorear los servicios que el Sector Público Nacional brinda a través de Internet,  establecer prioridades y planes estratégicos para liderar el abordaje de la ciberseguridad.

Recientemente, con el objetivo de brindar asesoramiento al ICIC para cumplir su misión, la Jefatura de Ministros conformó el GESI, “Grupo de Expertos en Seguridad y Legislación Informática”.  Al GESI han sido invitados reconocidos especialistas como del Área de Derecho, del sector de Delitos Informáticos de Policía Federal, y del ONTI, Oficina Nacional de Tecnología de Información.

Dentro del sector privado, Infobyte Security Research, a través de su CEO, Francisco Amato, fue una de las primeras empresas invitadas a participar de este grupo de asesoramiento.

El GESI además será responsable de la creación , generación y edición de contenidos que ayuden a una concientización acerca de la Seguridad Informática, por parte de los diferentes sectores de la sociedad.

Para más información:

http://www.icic.gob.ar/paginas.dhtml?pagina=243
http://www.icic.gob.ar/paginas.dhtml?pagina=97

الخميس، 26 يناير 2012

Datos para robar casas a través de Internet

Entre el 3 y 10 de enero, Página/12 detectó 8623 tweets de porteños que decían estar fuera y un cruce con la guía Telexplorer arrojó gran cantidad de coincidencias con casas vacías. El uso de Google Maps y el mapa de la ciudad de Buenos Aires.


La ecuación es simple. Si uno está de vacaciones, hay altas probabilidades de que no haya nadie en casa. Hasta hace no mucho tiempo, la única forma que tenían los amigos de lo ajeno para conseguir información sobre una casa vacía era la inteligencia barrial, los “sapos” marcan la vivienda y el resto ya se conoce. Pero en esta fascinación por la presencia en Internet, las redes sociales podrían cumplir un rol inesperado: la cantidad de gente que ofrece datos sobre su paradero en verano es alucinante. Además, si esa búsqueda se sistematiza, los números son aterradores. En un período de una semana, del 3 al 10 de enero de 2012, Página/12 detectó 8623 tweets con información de personas que dijeron estar de vacaciones. De esa cantidad, quedaron 6089 usuarios de Twitter. Entre las primeras diez búsquedas, como expresiones exactas, aparecieron en Twitter 557 personas que escribieron “me voy a la costa”, 512 “me voy a Brasil”, 363 “estoy en Pinamar”, 333 “estoy en Brasil”, 283 “me voy a Gesell”, 232 “estoy en Gesell” y 164 “estoy en Mar del Plata”, entre otras. Del total de usuarios, se detectaron coincidencias con 870 direcciones de la guía telefónica, en la ciudad de Buenos Aires, unas 300 con direcciones únicas. Había 322 “oportunidades” en Palermo, 241 en Caballito, 225 en Recoleta, 193 en Belgrano, 172 en Flores, 168 en Almagro, en 133 Balvanera, en 124 San Nicolas y 111 Villa Urquiza. ¿Todas estas son casas “robables”? No. Pero con llamar por teléfono y evidenciar que no contesta nadie se asume que la información empieza a concordar.
El objetivo de esta investigación realizada en conjunto entre Página/12 y Francisco Amato, responsable de Infobyte y uno de los organizadores de la Ekoparty, el encuentro de hackers más grande de América latina, es alertar sobre la sobreexposición de las redes sociales y las facilidades para manipular los datos ciudadanos. Los expertos en seguridad siguen dando indicaciones sobre cómo cuidar “la casa” cuando uno se va de vacaciones, pero pocos se han percatado sobre las consecuencias de compartir información en las redes sociales.


Ver mapa completo
Hace un año, un grupo de hackers montó en Estados Unidos el sitio pleaserobme.com (por favor robame), que demostró lo sencillo que era recolectar información para encontrar “posibilidades de robo” a partir de la información publicada motu proprio. Pleaserobme.com estuvo tres meses en línea, salió en los principales medios estadounidenses y se dio de baja. Poco después, tres hombres fueron detenidos en Estados Unidos por robo, y confesaron que perpetuaban asaltos siguiendo las actualizaciones de Facebook. Mario Rojas, Leonardo Barroso y Víctor Rodríguez robaron 18 casas en Nashua, New Hampshire, chequeando Facebook, encontrando a los dueños que anunciaban haberse ido (ver aparte).
En Argentina, según comScore hay 13 millones de conexiones, 27 millones de personas, el 91 por ciento de los conectados usa redes sociales y un 18 por ciento usa Twitter desde su casa o trabajo: es decir, hay millones de personas que ofrecen información constantemente y 17 millones de usuarios de Facebook que, cada tanto, actualizan sus “Estados”. Por pedido de este diario, Amato sistematizó las búsquedas de “oportunidades” sólo con información pública. Primero, se hicieron pruebas manuales, como buscar en Twitter “me voy a Pinamar”, “me voy para la Costa”, de allí se sacaron una veintena de usuarios, y se cruzaron con Telexplorer.com.ar donde se puede buscar manualmente el nombre de una persona, y la base ofrece la dirección y el teléfono de línea. Después, se revisó la red social de georreferenciamiento Foursquare para ver si había alguna referencia. Sin embargo, los checkins de la “casa” en Foursquare –cuando un usuario dice que está en su hogar– sólo sirven para tener una referencia barrial. Por último, se puede acceder al sitio oficial del Gobierno de la Giudad de Buenos Aires, que tiene un espectacular mapa catastral (mapa.buenosaires.gov.ar). Así, del usuario de Twitter –muchos con nombre y apellidos reales–, se podía saber si la casa era linda en Google Maps.
Los casos testigos funcionaron, así que se decidió sistematizarlo. Amato trabajó en un programa que guardaba los tweets de quienes ponían información sobre el futuro de sus vacaciones. “Se realizaba una búsqueda por palabras claves utilizando la api de Twitter, luego se filtraba el contenido para obtener usuarios, nombre y apellido”, cuenta Amato. La “api” es una puerta que abre Twitter a desarrolladores para trabajar sobre su contenido. Se buscó tweets en la provincia de Buenos Aires. Desde el 3 al 10 de enero de 2012 se encontraron 6098 usuarios “interesantes”. Aunque con el transcurso de los días se descubrió que los tweets de quienes escribían en singular tenían conductas más adultas –sus casas más encontrables rápidamente por su nombre–, pero para asegurarse de que la casa estaba vacía había que ir al plural: seguramente estará deshabitada si la familia sale junta. Algo como “nos vamos a Cariló”. El problema del plural era que se trataba de hijos de familias cuyos nombres no figuran en Telexplorer.com.ar, ni en Páginas Amarillas puesto que las casas están a nombre de los padres. O sea: el nivel de inconsciencia es indirectamente proporcional a la edad de los usuarios de las redes sociales (ver aparte).
Una vez juntados los “usuarios de vacaciones”, se decidió sistematizar la búsqueda de direcciones con Telexplorer.com.ar, una web gratuita, registrada en la Dirección Nacional de Protección de Datos. Telexplorer tiene 7,5 millones de registros telefónicos de todo el país: nombre, dirección y teléfono, y se puede buscar por cualquier campo. De acuerdo a las normas vigentes en Argentina, Telexplorer ofrece mecanismos para que los usuarios puedan eliminar su información personal. Páginas Amarillas ofrece la misma información. “Desarrollé algo que analiza Telexplorer y permite sistematizar las consultas. Cuando se llega a 400 veces, aparece una confirmación manual, como cuando alguien equivoca tres veces su password en Gmail y tiene que escribir letras desfiguradas. Una vez ingresado el código se ofrecen otras 400 búsquedas. Es un proceso semiautomático que junta apellido y nombre con la dirección y el barrio”.
Después de cruzar la base de más de 6 mil usuarios de Twitter, se arrojaron 870 coincidencias, muchas, obviamente, con más de una dirección, lo cual ofrece un margen de error pero no tan alto: la gran mayoría de las direcciones repetidas no pasaban de dos o tres opciones (salvo que el apellido fuese Pérez). Para ser un poco más precisos, se podía filtrar por aquellos que tenían una sola dirección, y finalmente lo más efectivo fue buscar apellidos raros.
Obviamente, hay que tener en cuenta que la información de la guía no está siempre actualizada, o se trata de contratos de alquiler donde no cambian los datos o simplemente son homónimos. En estos casos, basta con observar la actividad de los usuarios de Twitter o Facebook para saber si tiene congruencia con el lugar; si alguien tiene dirección en Claypole y acaba de tweetear “vengo de darme una vuelta por Lomas de Zamora”, el hallazgo tiene sentido. Otro procedimiento fue revisar “entre los usuarios de Twitter contenidos de Foursquare con la palabra ‘casa’”, cuenta el programador. Los resultados fueron más bien escasos, apenas un par en Foursquare y unas cuantas localizaciones en Twitter. La localización en Twitter se muestra si el usuario la activó. Pero muchas veces la persona suele olvidar que la tiene prendida.
Una consideración: si Telexplorer decidiera mejorar la seguridad de las consultas, lamentablemente sólo bastaría con buscar en Google “Padrón electoral elecciones 2011” para conseguir en decenas de sitios la lista completa de personas con nombre, apellido, DNI, dirección y teléfono. En fin, una vez detectado que la persona no se encuentra en el lugar, hay dos maneras gratuitas y disponibles en la web para observar la casa antes de acercarse físicamente. La más obvia es Google Maps: basta con poner la dirección encontrada, hacer click y observar desde el cielo la presunta casa vacía. Y eso que todavía no está disponible el fabuloso servicio de Street View, que permite recorrer los barrios “caminando”. Pero la opción de información oficial que está en el mapa de la ciudad de Buenos Aires es más precisa, aunque su acceso no puede sistematizarse. Esto se obtiene de Página/12 (Solís 1525): “superficie total: 614.00 m2, Frente: 22.00 m, Fondo: 27.91 m, División en propiedad horizontal: no, Pisos sobre rasante: 4, Pisos bajo rasante: 1, Unidades: 0, VUC: 0.08”. O sea, no se olviden que hay sótano.
Por: Mariano Blejman@blejman

الأربعاء، 7 ديسمبر 2011

Pwning Java update process 2007-Today

Last week a Trojan appeared on the news, named FinFisher is being sold exclusively to law enforcement and intelligence agencies of different nations for monitoring PCs and mobile devices.

What is so interesting about FinFisher?
It uses as an infection vector, fake updates in the iTunes application exploiting a vulnerability that I reported in 2008 and interestingly Apple three years after on November 14 published patch to solve it.

Two blogs covered this story in depth, I recommend you to visit Seguridad Apple & Krebs on Security who were reporting on the matter.

And the Java update?
On the same day that Apple was alerted about the problem, I did it with SUN with the difference that they published a patch on December 3, 2008. In early 2010 I discovered that it was possible to bypass the restrictions of this patch. Their first update system worked like this:

1) The updater requests in a insecure way the file java.sun.com/update/1.6.0/map-m-1.6.0.xml, this is done using HTTP. This is the content of the file:

<java-update-map>
<mapping>
<version>1.6.0_27</version>
<critical>1</critical> <url>http://javadl-esd.sun.com/update/1.6.0/au-descriptor-1.6.0_29-b110.xml</url>
</mapping>...
<mapping>
<version>1.6.0_28</version>
<critical>1</critical> <url>http://javadl-esd.sun.com/update/1.6.0/au-descriptor-1.6.0_29-b110.xml</url>
</mapping>
</java-update-map>

2) The updater compares it's version with the tag <version>, if it's a newer release, it downloads the file defined in <url> then the user gets a notification regarding a new update available.

3) The file contains the following content:

<java-update>
<information version="1.0" xml:lang="en">
<caption>Java Update - Update Available</caption>
<title>Java Update Available</title>
<description>Java 6 Update 29 is ready to install. Click the Install button to update Java now. If you wish to update Java later, click the Later butto
<moreinfo>http://java.com/infourl</moreinfo>
<AlertTitle>Java Update Available</AlertTitle>
<AlertText>A new version of Java is ready to be installed.</AlertText>
<moreinfotxt>More information...</moreinfotxt>
<url>http://javadl.sun.com/webapps/download/GetFile/1.6.0_29-b110/windows-i586/jre-6u29-windows-i586-iftw-rv.exe</url>
<version>1.6.0_29-b110</version>
<post-status>https://nometrics.java.com</post-status>
<cntry-lookup>http://rps-svcs.sun.com/services/countrylookup</cntry-lookup>
<predownload></predownload>
<options>/installmethod=jau SP1OFF=1 SP2OFF=1 SP3OFF=1 SP4OFF=1 SP5OFF=1 SP6OFF=1 SP7OFF=1 SP8OFF=1 SP9OFF=1 SP10OFF=1 SP11OFF=1 MSDIR=ms5 SPWEB=http://
<urlinfo>0a8ddda613f0196beac748407767efebcaea83ca</urlinfo>
</information>
</java-update>

4) If the user confirms the update, the binary set in the <url> tag will get downloaded, if it's signed by CA it will be executed, if not the user will have to confirm the execution.

After the 2008 patch, SUN kept the same update implementation using HTTP with the exception of one more validation step.

5) Before executing the file it compares that the binary is signed by SUN...

Java update bypass:

To bypass this restriction we send the Java Web Start (javaws.exe) binary as payload and since we can control the arguments with the tag <options> we put an address with a JNLP under our control & Bingo!

This technique was presented at Black Hat & Defcon 2010 with the last version of Java 1.6.0_22 and still today the last version Java <=1.6.0.28 remains vulnerable.

The following video demonstrates the vulnerability:



Important Dates:
  • 2007 It was first presented at ekoparty (Itunes/Java vulnerable).
  • 2008 We presented Evilgrade at Troopers, Shakacon & H2HC.
  • By the end of 2008, We got in touch with the vendors. SUN publishes the patch. We release Evilgrade 1.0 to the public.
  • 2010 We presented Evilgrade 2.0 at Defcon/BlackHat, and we release it to the public.
  • 2011 Apple fixes the iTunes flaw, SUN still has no clue about their bug.
While there was not an a initial contact with the company, shouldn't they do their homework and learn where researchers publish our work?
Or should we wait for FinFisher 2.0 release so they are forced to patch it?

Think about it...
Cheers!

Pwning Java update process 2007-Today (ES)

La semana pasada se hizo publico un troyano llamado FinFisher que estaba siendo comercializado exclusivamente a fuerzas de seguridad y agencias de inteligencia de distintas naciones para vigilar PCs y dispositivos mobiles.

¿Que tiene de interesante FinFisher?
Utiliza como vector de infección updates falsos de la aplicación iTunes, explotando una vulnerabilidad que reporté en 2008 y curiosamente Apple luego de 3 años, el 14 de Noviembre publico el parche para solucionarla.

Dos blogs cubrieron esta noticia en profundidad, les recomiendo que visiten Seguridad Apple y Krebs on Security quienes estuvieron informando del asunto.

¿Y el update de Java?
En la misma fecha que avisé del problema en Apple lo hice en Sun con la diferencia que ellos sacaron un parche el 3 de Diciembre del 2008. A principios del 2010 descubrí que era posible saltar las restricciones de este parche. Su primer sistema de actualización realizaba las siguientes acciones:

1) El updater obtiene por http de manera insegura el archivo java.sun.com/update/1.6.0/map-m-1.6.0.xml, que contiene lo siguiente:

<java-update-map>
<mapping>
<version>1.6.0_27</version>
<critical>1</critical> <url>http://javadl-esd.sun.com/update/1.6.0/au-descriptor-1.6.0_29-b110.xml</url>
</mapping>...
<mapping>
<version>1.6.0_28</version>
<critical>1</critical> <url>http://javadl-esd.sun.com/update/1.6.0/au-descriptor-1.6.0_29-b110.xml</url>
</mapping>
</java-update-map>

2) El updater compara su versión actual con el tag <version>, si es mas reciente procede a obtener el archivo en el tag <url> y preguntarle al usuario si desea instalar la nueva actualización.

3) El archivo contiene la siguiente información:

<java-update>
<information version="1.0" xml:lang="en">
<caption>Java Update - Update Available</caption>
<title>Java Update Available</title>
<description>Java 6 Update 29 is ready to install. Click the Install button to update Java now. If you wish to update Java later, click the Later butto
<moreinfo>http://java.com/infourl</moreinfo>
<AlertTitle>Java Update Available</AlertTitle>
<AlertText>A new version of Java is ready to be installed.</AlertText>
<moreinfotxt>More information...</moreinfotxt>
<url>http://javadl.sun.com/webapps/download/GetFile/1.6.0_29-b110/windows-i586/jre-6u29-windows-i586-iftw-rv.exe</url>
<version>1.6.0_29-b110</version>
<post-status>https://nometrics.java.com</post-status>
<cntry-lookup>http://rps-svcs.sun.com/services/countrylookup</cntry-lookup>
<predownload></predownload>
<options>/installmethod=jau SP1OFF=1 SP2OFF=1 SP3OFF=1 SP4OFF=1 SP5OFF=1 SP6OFF=1 SP7OFF=1 SP8OFF=1 SP9OFF=1 SP10OFF=1 SP11OFF=1 MSDIR=ms5 SPWEB=http://
<urlinfo>0a8ddda613f0196beac748407767efebcaea83ca</urlinfo>
</information>
</java-update>

4) Si el usuario confirma la actualización se descargara el binario que se encuentra en el tag <url>, en el caso que el archivo esté firmado por una entidad certificada ejecuta el binario, de lo contrario preguntaba al usuario si desea ejecutar el binario.

Luego del parche del 2008, SUN continuo utilizando la misma mecánica de update, todo vía HTTP con la excepción de una comprobación adicional.

5) Antes de ejecutar el archivo comprueba que el binario este firmado por una entidad certificante y sea un certificado de SUN.


Java update bypass:
Para saltar esta restriccion enviamos como binario el Java Web Start (javaws.exe) y como podemos controlar los argumentos con el tag <options> le pasamos una direccion que controlamos con un JNLP y bingo!

Esta técnica fue presentada en Blackhat y Defcon 2010 con la ultima version Java 1.6.0_22 y hasta hoy sigue siendo vulnerable en la ultima version de Java <=1.6.0.28.

El siguiente video demuestra la vulnerabilidad:



Fechas:
  • 2007 Fue presentando por primera vez Evilgrade en ekoparty (Itunes/Java vulnerable).
  • 2008 Presentamos Evilgrade en Troopers, Shakacon y H2HC.
  • Fines del 2008, Nos pusimos en contacto con los vendors. Sun publico el parche. Lanzamos Evilgrade version 1.0
  • 2010 Presentamos Evilgrade version 2.0 en Defcon/Blackhat y publicamos version 2.0
  • 2011 Apple corrige vulnerabilidad en iTunes y Sun aun no se dio cuenta de su vulnerabilidad.
Si bien no hubo un contacto inicial con la empresa, no deberian hacer su tarea y enterarse en los medios donde los investigadores publicamos nuestros trabajos?
O hay que esperar a la version 2.0 de FinFisher para que lo resuelvan?

Para pensar...
Saludos!

Pwning Java update process 2007-Today (BR)

Na semana passada um Trojan apareceu na mídia, com o nome de FinFisher, este está sendo associado exclusivamente para leis e para agências de inteligência de diferentes nações para monitoramento de computadores e de dispositivos móveis.

O que é tão interessante sobre FinFisher?
Ele usa como vetor de ataque, atualizações falsas do iTunes, explorando uma vulnerabilidade que relatei em 2008, e curiosamente a Apple só agora, três anos depois, em 14 de Novembro publicou o patch para resolver.

Dois blogs analisaram com maior profundidade esta história, eu recomendo que você visite Seguridad Apple & Krebs on Security que trataram sobre o assunto.

E a atualização do Java?
No mesmo dia em que a Apple foi alertada sobre o problema, eu fiz isso com a SUN, à diferença é que eles publicaram um patch no dia 03 de Dezembro de 2008. No início de 2010 eu descobri que era possível “bypassar” as restrições deste patch. O primeiro update deles funcioanava desta maneira:

1) O atualizador faz a requisição do arquivo java.sun.com/update/1.6.0/map-m-1.6.0.xml, de forma insegura, pois isto é feito usando HTTP. Este é o conteúdo do arquivo:

<java-update-map>
<mapping>
<version>1.6.0_27</version>
<critical>1</critical> <url>http://javadl-esd.sun.com/update/1.6.0/au-descriptor-1.6.0_29-b110.xml</url>
</mapping>...
<mapping>
<version>1.6.0_28</version>
<critical>1</critical> <url>http://javadl-esd.sun.com/update/1.6.0/au-descriptor-1.6.0_29-b110.xml</url>
</mapping>
</java-update-map>

2) O atualizador compara sua versão atual com a tag <version>, e se for mais novo, procede a fim de obter o arquivo através da tag <url> então, pergunta ao usuário se ele deseja instalar a nova atualização.

3) O arquivo contêm as seguintes informações:

<java-update>
<information version="1.0" xml:lang="en">
<caption>Java Update - Update Available</caption>
<title>Java Update Available</title>
<description>Java 6 Update 29 is ready to install. Click the Install button to update Java now. If you wish to update Java later, click the Later butto
<moreinfo>http://java.com/infourl</moreinfo>
<AlertTitle>Java Update Available</AlertTitle>
<AlertText>A new version of Java is ready to be installed.</AlertText>
<moreinfotxt>More information...</moreinfotxt>
<url>http://javadl.sun.com/webapps/download/GetFile/1.6.0_29-b110/windows-i586/jre-6u29-windows-i586-iftw-rv.exe</url>
<version>1.6.0_29-b110</version>
<post-status>https://nometrics.java.com</post-status>
<cntry-lookup>http://rps-svcs.sun.com/services/countrylookup</cntry-lookup>
<predownload></predownload>
<options>/installmethod=jau SP1OFF=1 SP2OFF=1 SP3OFF=1 SP4OFF=1 SP5OFF=1 SP6OFF=1 SP7OFF=1 SP8OFF=1 SP9OFF=1 SP10OFF=1 SP11OFF=1 MSDIR=ms5 SPWEB=http://
<urlinfo>0a8ddda613f0196beac748407767efebcaea83ca</urlinfo>
</information>
</java-update>

4) Se o usuário confirmar, a atualização irá baixar o binário que está na tag <url> , já se o arquivo for assinado por uma entidade certificada, o binário é diretamente executado, caso contrário, irá solicitar ao usuário que execute o binário.

Após o patch de 2008, a SUN continua usando a mesma forma de atualização, ou seja, tudo via HTTP com exceção de uma verificação adicional.

5) Antes de executar o arquivo, é verificado se o binário é assinado por uma entidade certificadora e é um certificado da SUN...

Java update bypass:

Para “bypassar” esta verificação, enviamos como binário o (javaws.exe) e como nós podemos controlar os argumentos com a tag <options> passamos uma direção que nós controlamos com um JNLP e Bingo!

Esta técnica foi apresentada na Blackhat e na Defcon em 2010, com a última versão Java 1.6.0_22, e até hoje continua vulnerável na última versão do Java <=1.6.0.28.

O vídeo a seguir demonstra a vulnerabilidade:



Datas:
  • 2007 Foi apresentado pela primeira vez o Evilgrade na Ekoparty (Itunes e Java vulneráveis).
  • 2008 Apresentamos o Evilgrade na Troopers, na Shakacon e na H2HC.
  • No final de 2008, nós entramos em contato com os vendors. SUN publicou o patch. Lançamos a versão 1.0 do Evilgrade.
  • 2010 Apresentamos o Evilgrade versão 2.0 na Defcon/Blackhat e publicamos a versão 2.0.
  • 2011 Apple corrige vulnerabilidade no iTunes e a Sun não se deu conta de sua vulnerabilidade.
Não houve um contato inicial com a empresa, porém não deveriam estas fazer sua lição de casa e buscar na mídia onde os pesquisadores publicam os seus trabalhos?
Ou devem esperar a versão 2.0 do FinFisher para resolverem?

Para pensar...
Saudações!

(*) Traduzido por Jordan M. Bonagura (tw)