3S Labs Banner

Showing posts with label research. Show all posts
Showing posts with label research. Show all posts

Friday, September 26, 2014

CVE-2014-6271 Bash Vulnerability a.k.a Shellshock

CVE-2014-6271 a.k.a Shellshock is command execution vulnerability in Bash shell via. specially crafted environment variable. As per NIST, the exploitation has been demonstrated against vectors involving ForceCommand feature in OpenSSH sshd, the mod_cgi and mod_cgid modules in the Apache HTTP Server, scripts executed by unspecified DHCP clients, and other situations in which setting the environment occurs across a privilege boundary from Bash execution.

Due to the wide spread deployment and use of Bash shell on almost all Linux, OSX and other *nix based systems, this vulnerability is considered to be extremely critical with possible impact matching the Heartbleed issue, if not more.

Who is Affected?


Any application or system that invokes command through the bash shell can be potentially vulnerable. In order to exploit this issue in a target, an attacker needs to:

  • Set any environment variable with his controlled data.
  • Force the target to invoke any shell command through bash -c <cmd>

The immediate targets that can be exploited remotely are Web Servers with CGI support particularly those CGI scripts that are written in shell scripting. Apart from that, web applications written in various scripting language such as PHP, Perl, Python, Ruby etc. are equally vulnerable if deployed in CGI mode and the application at some point invokes shell command using functions like popen, exec, system etc.

How to Fix?


The bash shell needs to be updated to a patched version. For Debian based systems, it can be done using the following command:
apt-get install --only-upgrade bash

For RedHat or CentOS based system, following command can be used to update bash:
yum update bash

Note: The current fix in Bash is considered to be incomplete. A complete fix is yet to be released at the time of writing. The initial fix bypass is assigned the vulnerability identifier CVE-2014-7169.

Technical Analysis & Test Case


The simplest test case involves executing the following command in an affected bash shell:


If the string Vulnerable is printed, then the shell is affected by this issue.

Remote exploitation of this vulnerability can be demonstrated in a local environment using Apache/CGI based deployment and an affected version of Bash shell.

Sample CGI to demonstrate the vulnerability:


Following ruby script can be used as a test case for exploiting the above CGI for vulnerability detection:


The vulnerability can be confirmed if the HTTP response contains an additional header named X-Shellshock. Our FreeScan For Web Application service is updated with test to detect this vulnerability using a similar test case as described above. However it must be noted that the test is limited that uses common heuristic and should not be considered 100% reliable.

Reference:

  • http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2014-6271
  • https://rhn.redhat.com/errata/RHSA-2014-1306.html
  • https://securityblog.redhat.com/2014/09/24/bash-specially-crafted-environment-variables-code-injection-attack/


Thursday, June 13, 2013

HiDump: Tracing and Extraction of Runtime Injected Code

Malware analysis is Fun!

It is particularly satisfactory if the analyst manages to identify and somehow extract the hidden core logic/component of a given malware which is crypted and protected in order to hinder analysis efforts.

In reality, most malware we have encountered are either packed partially or uses in-memory injection of decoded/unpacked core logic at runtime to evade Anti Viruses. It is usually trivial to unpack such malware using a Debugger or IDA with Debugger plugin. We have rarely, but indeed, experienced malware protected with advanced engines like Themida, VMProtect etc. which are non-trivial to analyse due to extensive code obfuscation or virtualised instructions and multiple anti-debugger techniques.

RunPE


Perhaps the most commonly used crypter technique is RunPE. The original executable is encoded/encrypted and somehow embedded inside a Stub Executable either in a PE section or as EOF data or as a Resource. The Stub Executable in turn decodes/decrypts the original executable in-memory at runtime and uses RunPE engine to load and execute it.

The RunPE technique consists of the following steps:
  • Execute a host process (HP) (say notepad.exe) with CREATE_SUSPENDED flag set.
  • Identify the ImageBaseAddress of the original executable (OE) to be loaded from its PE Header.
  • Attempt to allocate memory for OE in HP's address space at OE's expected based address.
  • If OE's expected base address not available, unmap HP's original mappings and allocate memory.
  • Write OE's PE sections into the address space of HP using WriteProcessMemory(..) API.
  • Change the ImageBase in HP's PEB if required.
  • Resume execution of main thread in HP.
The crux of the technique lies in OS's support for the CREATE_SUSPENDED flag in CreateProcess(..) API. This flag tells the kernel to suspend the main thread of the newly created process immediately after the PE is loaded and the sections are mapped. At this point, another thread must call ResumeThread(..) API on the main thread before control is transferred to NTDLL's LdrInitialize(..) and the process is loaded in the usual manner (Import Resolution, Base Relocation etc.)

The RunPE technique involves replacing the original program image from the address space of the newly created process with that of the program it intends to execute. In memory execution of a program will involve doing everything which the OS's Program Loader does. In order to avoid doing everything by itself, the RunPE technique lets the OS do everything, just that it replaces the original program content with its own payload in time ie. after the target program is mapped into the address space of the newly created process but before the PE Loading process is initiated.

Extracting executables protected with RunPE like crypters are usual trivial as it involves setting break points in memory allocation and memory write routes and dumping decoded/decrypted content using a debugger. However things get a little tricky with a bit of obfuscation and anti-debug ...


The VMProtect Story


In the past, we had come across a malware (stage1 really) which simply does the following:

  • Fetch an encrypted DLL (stage-2) over the Internet via. HTTP
  • Decrypt the DLL in-memory
  • Inject it into explorer.exe address space.

Essentially the core logic of the malware resided in Stage-2 DLL however due to custom compression & encryption, it was not possible to obtain the DLL for further analysis just from a pcap dump. Usually the next approach would be to use a Debugger to trace the Stage-1 executable, set appropriate breakpoints and obtain a dump of the decrypted DLL before it is being injected into explorer.exe.

However it turned out that the Stage-1 was protected with VMProtect with Debugger detection turned on. It was not possible to use a debugger to trace Stage-1 as it was detecting a debugger presence (we did not try a kernel debugger that time) and halting execution.

At that time, we solved the issue using a Pin Tool. Since PIN does not use Windows Debugging API for injection or management of PIN Tool, it was possible to trace execution of Stage-1 using a PIN Tool. We could hook WriteProcessMemory(..) and extract the decrypted DLL from Stage-1 for further analysis.


HiDump


The idea for HiDump was conceived based on our experience with analysing protected malware with anti-debugging capability. Our objective was to devise a generic technique for extraction of data/code written using WriteProcessMemory(..)  Our implementation will attempt to avoid using Windows Debug API in order to play nice with Anti-Debugger checks.

Implementation:

The system consists of 2 core components:
  • Loader: Execute target executable with 'Monitor' injected into it.
  • Monitor: A DLL that hooks Windows API for monitoring and data extraction.
Loader:
  1. Start Target exe with CREATE_SUSPENDED Flag
  2. Inject Monitor DLL in the address space of Target exe
  3. Resume Main Thread of Target exe (continue execution)
Monitor:
  • Hook OpenProcess, VirtualAllocEx, WriteProcessMemory, CloseHandle, CreateRemoteThread
  • Build State Machine for Data/Code Capture as per Hook Trigger Events
  • On End-State, dump data to disk
The Monitor is implemented using Microsoft Detour library for API Hooking. Essentially the monitor hooks following Windows API:


The Monitor internally maintains a State-Machine that starts with OpenProcess(..) and usually ends with CreateRemoteThread(..). The reason for maintaing a State-Machine is to record all memory write in the same order and offset in which a given block of data is written in the address space of the target process. When an event occurs that is marked as an End-State such as a call to CreateRemoteThread(..) the monitor attempts to dump all data recorded for that corresponding context (consisting of Process Handle, Allocated and Written Memory).

This technique however lacks the capability to identify and extract code injections using SetWindowsHookEx(..) or QueueUserAPC(..) APIs. However we believe the tool can be extended to consider those cases as well.

Proof of Concept Implementation:

A proof of concept implementation is available in Github.

Sample Execution against VMP Protected Executable

Monitor logs captured using syelogd.exe

Sunday, December 23, 2012

A Brief Survey of CWMP Security

Summary

This article attempts to provide a brief overview of the CPE WAN Management Protocol (CWMP). We also share some of our findings during a Penetration Test (with very limited scope) of a CWMP based Home Broadband infrastructure.

Finally we provide some of the possible attack vectors against a CWMP infrastructure and prospective areas of research in this topic.

Introduction

The CPE WAN Management Protocol (CWMP) is a bi-directional SOAP/HTTP based protocol which allows centralised remote management of Customer Premises Equipments such as Broadband Routers, VoIP Phones , Set-Top Boxes etc. by an Auto Configuration Server (ACS).

CWMP infrastructure allows an ACS to provision a CPE during its deployment at the customer end while monitoring and upgrading its software and configuration as and when applicable.

The Broadband Forum's Technical Report 069 (TR069) defines the specification and implementation requirements for CWMP.

Deployment & Technical Details


Fig. 1.0: CWMP Specification - TR069.pdf

The above diagram briefly describes the design and deployment of a CWMP based infrastructure involving a set of CPE devices and an ACS. The ACS can request for a session with the CPE which in turn establishes a CWMP session with the pre-configured ACS. The session allows an ACS to perform various administrative tasks on the CPE including software and configuration update. If UPNP is supported by the CPE, it optionally can allow NAT Traversal functionality by an ACS so that it can communicate with devices inside the Local Network and request for connection initiation.

Protocol of Communication


CWMP uses SOAP/HTTP based communication between the ACS and the CPE. The schema definition for CWMP SOAP Methods are available here using which an appropriate WSDL can be generated for use with conventional SOAP Clients or Libraries. Pre-generated WSDL for CWMP-1.0 and CWMP-1.1 can be found here.

The major RPC Methods used in CWMP are as follows:
  • Inform method is used by a CPE to initiate a CWMP Session with its pre-configured ACS.
  • GetParameterValues method is used by the ACS to obtain various configuration information from the CPE using corresponding Parameter Names.
    • Parameters are grouped based on relevance and are separated using '.'
    • E.g. InternetGatewayDevice.ManagementServer.URL is the parameter name for ACS URL configuration in the CPE.
  • SetParameterValues method is used by the ACS to update various configuration information in the CPE using corresponding Parameter Names.
  • Download method is used by the ACS to initiate a file download by the CPE. This request is usually used to upgrade software/firmware in the CPE.
  • Upload method is used by the ACS to request the CPE to upload a local file from the CPE to a specific URL. Current version of CWMP allows uploading of Vendor Configuration and Log Files only.
  • Reboot method is used by the ACS to initiate a CPE reboot.


The CWMP specification also supports a method called GetRPCMethods which can be used to enumerate the supported CWMP RPC Methods in a CWMP capable device (CPE or ACS).


CWMP GetRPCMethods Example using SoapUI

The above screenshot shows a GetRPCMethods call against an ACS. This method is probably ideal for use as a CWMP endpoint discovery mechanism due to the fact that many ACS or CPE will allow a request for this method even without authentication.


During our testing, we could call this method against multiple ACS implementations without authentication. However none of the CPEs (our scope was limited to only 2 models of Home Broadband ADSL Router) responded to this request even with authentication.

Session Initiation & Execution

  • A CWMP Session is initiated by a CPE with its pre-configured ACS URL by sending an Inform Request to the ACS. Device specific information like Vendor, Make, Model etc. are shared as a part of Inform request parameter with the ACS. An Inform request is executed by a CPE on occurrence of various events or periodically every pre-configured duration.
  • The ACS in turn responds with an Inform Response message which contains negotiated session parameters. This HTTP response may contain more than one SOAP envelops each containing a CWMP RPC Method call request from the ACS. 
  • The CPE then responds with response to RPC Method Call requests from the ACS or RPC Method Call request of its own.
  • The session is terminated when there are no further messages to be exchanged by both the ends or in case of an error.

Alternatively, an ACS may also request for a session by sending a GET request to a specific URL in the CPE called the Connection Request Notification (CRE). The specification suggests usage of non-static resource-location by the CPE along with HTTP Digest based authentication for CRE. This GET request act as a trigger event which should cause the CPE to initiate a CWMP session with the ACS in the usual manner described above.

Note: The CWMP specification suggests usage of a single HTTP connection (using the Keep-Alive flag) for the entire CWMP session. However cookies may be used to maintain the HTTP session for implementations that does not support Keep-Alive.

Security Note: CWMP is relatively secure by design due to the fact that CPE devices which may be exposed over the Internet DOES NOT accept CWMP RPC requests over any HTTP connection originating from any location other than the one initiated by the CPE itself. The CPE initiates an HTTP Connection with the pre-configured ACS URL and initiates a CWMP Session. The SOAP/HTTP paradigm is reversed in its implementation such that HTTP Responses from the ACS contains CWMP RPC Requests and HTTP Requests from the CPE contains corresponding CWMP RPC responses.


CWMP Attack Surface

During our research, we were not able to discover any critical issue with the design of CWMP however during a pentest we were able to exploit configuration weaknesses in the CWMP implementation of the target particularly hardcoded credentials and absence of SSL in HTTP connections. Particularly we were able to demonstrate using CWMP for backdooring CPE devices and using our malicious ACS as a Command & Control server for multiple CPE devices which was possible only due to configuration vulnerabilities in the target deployment and is not a flaw with CWMP itself.

Man in the Middle (MiTM) Attacks

As described earlier, CWMP enables an ACS to perform various administrative and management operation on a set of CPE devices including firmware upgrade and updating important configuration parameters like Gateway IP, DNS Server etc. The specification strongly encourages usage of HTTPS instead of plain HTTP. The specification also optionally requires the CPE to verify the SSL certificate fingerprint of the ACS before connection establishment. Adhering to these recommendations ensure integrity of the session.

CWMP infrastructure that does not make use of SSL sessions are susceptible to Man-in-the-Middle attacks which endagers CPE devices. In case an attacker manages to become a Man-in-the-Middle between an ACS and a CPE, it is possible to change the ACS URL configuration and hijack the corresponding CPE using his own malicious ACS.

Reflective DDoS against an Auto Configuration Server (ACS)

CWMP provides option for an ACS to request for a session with a CPE. The Connection Request Notification (described earlier) is a GET request sen't to a CPE designated URL with credentials for HTTP Digest Authentication with the CPE. This GET request acts as trigger for the CPE to initiate a new CWMP session with its pre-configured ACS after verification of provided credentials. The specification requires the CPE to randomly generate the path of the URL for Connection Request Notification. However during our testing, we found the entire set of CPE devices within the scope of testing have the following configuration:

CWMP "Connection Request Notification" Configuration in Test ADSL Router

Evidently the CWMP implementation in our tested CPE devices are not very obedient to the specification. Due to the predictable nature of the Connection Request Notification (CRE) configuration for CPE devices, it is trivial to write a script to scan an entire network for open CWMP endpoints and send a CRE HTTP request which will initiate a connection from the CPE to the ACS. If the network is sufficiently large, it can be exploited to cause a DDoS against the ACS.

Even though the specification suggests that the CPE should handle this case and must not initiate more than a given number of connection within a time window, implementations may vary and such was the case during our testing.

Miscellaneous Issues

The ACS is a conventional web application usually implemented using Java based technologies and deployed on top of JBoss or Tomcat. Hence during a Penetration Test of a CWMP deployment the ACS must be subjected to a conventional Web Application & Web Service Penetration Testing. 

We were blessed with a nice verbose SQL Injection vulnerability in one of the target ACS during our test which made life a bit easier.

Although CWMP provides a robust model for remote management of CPE in a local broadband deployment, the security threats associated with the design of CWMP and its common deployments are yet to be evaluated. The readers are requested to share possible Attack Vectors that may be possible against a CWMP infrastructure.




References

http://www.broadband-forum.org/cwmp.php
http://www.broadband-forum.org/technical/download/TR-069.pdf
http://en.wikipedia.org/wiki/TR-069
http://openacs.sourceforge.net/
http://pierky.wordpress.com/2009/05/20/acs-url-configuration-via-dhcp-vendor-specific-information/
https://github.com/dpavlin/perl-cwmp
http://my-svn.assembla.com/svn/cwmp/src/parser/wsdl/

Friday, September 7, 2012

Unpacking ASPack-2.29 using Dynamic Analysis

ASPack is a Win32 executable file compressor which also protects the executable against basic Reverse Engineering. Although there are automated tools like IDA Pro's Universal Malware Unpacker or can probably be unpacked using techniques defined in BitBlaze Renovo, we analyzed ASPack protected executables using Dynamic Analysis particularly as an exercise for our upcoming training on Reverse Engineering and Malware Analysis at Nullcon 2012 Delhi.

Following analysis is based on Free version of ASPack 2.29.

ASPack-2.29 Generated Executable Overview

ASPack compresses each section of the input executable along with adding two of its own section: .aspack and .asdata - the former containing the decoder and loader code however it is currently not clear about the purpose of the later as it seem to be empty (SizeOfRawData = 0).

Section List for Original Executable

Section List for Packed Executable

Comparing the Section Listing of the original and packed executable above, following assumptions can be made:

  • ASPack keeps the original sections intact including the section RVA however it sets the section mapping permission to RWX instead of the original R_X.
  • ASPack adds two news sections - .aspack and .adata among which the purpose of .adata is unknown as it is empty.
  • As understandable, the original entry-point is redirected to point somewhere within .aspack section.

Analysis Approach

The approach was conventional - start with Static Analysis to have a basic idea of the decoder logic and look for possible anti-debug or anti-diassambly technique and acquire enough knowledge to proceed with Dynamic Analysis. We needed to identify important code blocks like decoder loop, section mapping, control transfer to Original Entry Point (OEP) etc before we can proceed with automated unpacking.

Static Analysis


The entry point code in .aspack section in the packed executable uses a bunch of fake long and short jump op-codes (0xe9, 0xeb) to break the disassembler (Note: IDA 6.3 can detect such obfuscation technique and disassemble correctly without manual intervention). After little manual fix-up the code can be analyzed and IDA 5.0 (free) can build the Flow Graph correctly as shown below.



Three APIs as shown below in the disassembly were found to be resolved early in the loader code. Based on this logic, we made an assumption that those APIs will be used in order to decode and map sections and hence are perfect analysis points during Dynamic Analysis.


Dynamic Analysis

Phase1

We needed to verify that the decoded code is executed from its original location (as mapped by the PE Loader). Since our test executable was a GUI application (calc.exe) which inevitably calls GetMessageW, we set a breakpoint on the API and on breakpoint hit we could verify that the original code was decoded and execute from its original location only.

Phase2

Once it is verified that ASPack decoder decodes and execute original code in-place, we wanted to discover the decoder code block. For this we set a break-on-write (ba w4 addr-range in WinDBG) at the base address of the mapping containing the packed code.

Phase3

During Phase1 we noticed that the memory mapping of the decoded .text section is changed to R_X before execution from its original RWX permission as seen in the packed executable. From this we inferred that VirtualProtect must have been used before control is transferred to OEP.

Using this logic we were able to determine the exact point where ASPack loader transfers control to the OEP in the decoded .text section as shown below:




Little trial and error proved that ASPack loader does not seem to have any random or metamorphic component and hence this particular code above is always at an offset 0x420 from the base of .aspack section. The 0x00 above is patched with the computed OEP address at runtime.

Workflow for Automatic Unpacking

  • Set breakpoint on entry point
  • On breakpoint hit
    • Set breakpoint on OEP Caller address (push)
    • On breakpoint-hit
      • Dump the PE
      • Update entry point in PE Optional Header
      • TODO: Re-construct IAT

The Tool

The tool is written using the wonderful Metasm Framework, without it a LOT of work would have been required. The core logic is as below:


The full code is available here.

Closing Note: ASPack is not really meant for executable protection as such, it is more of a compression system similar to UPX. For serious requirement, appropriate tools like ASProtect, Themida, VMProtect etc. should be considered.

Advertising:

We will be conducting a 2-days workshop on Reverse Engineering and Malware Analysis at Nullcon 2012 Delhi which includes topic as described above along with other interesting topics like Dynamic Binary Instrumentation, Binary Patch Analysis etc. If you are new to Reverse Engineering, we will try our best to equip you with the basics of x86 ASM and Win32 platform components so that you can benefit from open information available on the internet. Do check out if you are interested.



Reference

http://www.aspack.com/
http://metasm.cr0.org/
http://bitblaze.cs.berkeley.edu/

Tuesday, May 22, 2012

Skype Greeting API Crash

It seem like the following code crashes latest version of Skype:


The interfaces look like this:


The crash log looks something like this:


This issue can however only be triggered from a post-authorized state ie. your client must be authorized by the Skype client to use Skype API.

Security Impact of this issue is currently unknown due to uncertainty of exploitation possibility. Even if exploitation is possible (although looks unlikely) the impact will be lower due to local and post-authorized nature of the affected functionality.

Wednesday, May 9, 2012

Skype API ... and Security

For sometime, we have been working on techniques to record Skype voice calls in a reliable and non-intrusive manner. Previously there had been known techniques and public proof-of-concept codes that demonstrate Skype voice call recording via DLL Injection and hooking certain Sound API inside Skype process, however such techniques evidently will be far from being non-intrusive.

It turns out, since quite some time Skype is actually developer friendly. Among various SDKs which are not available freely and only available to partners, Skype provides a OLE COM interface freely through which it is possible to interact with the active Skype process via a valid and documented interface.

The OLE interface thus makes it trivial to setup OLE Event Handlers for notification on Voice Call initiation and termination along with setting up appropriate recording channels.

Using Skype4COM, scripting up a Skype Recorder is actually quite trivial:



All great so far, however such trivial Automation API does come with a risk of malware misuse. In order to avoid malwares misusing Skype OLE Automation Interface, Skype has implemented API Access Authorization by the user which basically pops up or displays a message to the user for authorizing a given application to use Skype API. The authorization process is actually a bit complex than simply asking for user authorization and is more or less discussed here.

As already discussed and proved here, such Access Control or Authorization is definitely not enough as it is not very difficult to simulate mouse events. With some effort we were able to develop a proof of concept code that can automate the API authorization process using FindWindow, mouse_event and SendMessage Win32 APIs. Apart from that, authorizing applications to use API based on executable hash only is probably not a good idea as it _might_ be possible to force a trusted application to perform malicious activities by using it as a shuttle for malicious code.