3S Labs Banner

Thursday, November 6, 2014

Developing an Effective Strategy for Application Security

Web Application security is perhaps the most common and frequently discussed topic among researchers, small businesses as well as large enterprises. The primary reason is that, it has long overtaken network in being the most commonly attacked layer in a given IT infrastructure. Network and Operating System security has matured to a certain extent. Combined with various OS level hardening mechanism, the traditional attacks against network services has largely been mitigated or has become significantly costly. However, when it comes to web applications, for some reason, it appears that similar maturity in terms of risk mitigation is not achieved yet. Despite multiple WaF products and other security solutions for Web App security, the number of incidents related to compromise of organisation and its data by exploiting issues in web application has only increased in recent times.  For this reason, a different strategy or approach is required in order to safe guard web applications and implement a practice that encourage secure web application development.

Let Numbers Speak for Themselves


In order to better visualise the changing (or perhaps changed) Threat Perception in application and its associated infrastructure, let us consider the case of a Web Server and two web application development framework that is very popular among enterprise application developers - SpringSource Spring and Apache Struts. The statistics reveal that the number of vulnerabilities in the web server software itself is on a reducing path. The actual threat perception is significantly low compared to the numbers due to the existence of various OS level mitigation strategies that makes exploitation of memory corruption and other similar issues in web server process extremely costly/difficult. However, for web applications, the vulnerability classes are significantly different from those mitigated at OS level. New techniques and ease of exploitation has greatly increased the threat perception for web applications and web application development frameworks. Apart from common vulnerability classes, business logic vulnerabilities are another important issue that affects a lot of web applications.

Statistics for SpringSource Spring Framework

Statistics for Apache Struts Framework
Vulnerabilities in popular web application development frameworks are particularly critical due to the widespread impact. Since large enterprise applications are not easy to upgrade due to multiple dependency, vulnerabilities in framework software are extremely critical for such application and must be mitigated if not patched immediately.

Evaluating The Application Security Maturity


There is no single strategy that can help all organisations define a suitable approach for application security. There are various models, however, a carefully chosen model has to be customised and adopted based on the current posture, need and roadmap of any given organisation. Therefore, in order to define a suitable policy, it is very important to evaluate and ascertain the current application security maturity level of an organisation. This can be done to a certain extent by asking few questions:

  1. Is application penetration test (or VA as widely called) conducted regularly on all important applications?
  2. Are the same vulnerability classes for e.g. SQL Injection or CSRF detected every time a security test is conducted?
  3. Is there a training and evaluation program for developers?
  4. Is enforcement of secure coding guidelines implemented in IDE (or similar) level?

[1] The above questions helps in ascertaining the current security posture of an organisation as well as, to some extend, provides a direction for improvement in application security maturity. For example, if you have never done a Penetration Test on your applications, there is probably no need to immediately think of high level security policies or strategies, rather the organisation should focus on initiating regular security testing practices. [2] On the other hand, if you have been doing Penetration Testing for some time, however every time the same classes of vulnerabilities are discovered in different applications or newly implemented features, perhaps its time to think about the effectiveness of the strategy and its RoI. [3] & [4] are strategies that need to be adopted in order to avoid recurring vulnerabilities of similar classes.

Towards an Effective Strategy for Application Security Maturity


A good strategy for implementing or improving application security in an organisation should consists of at least the following:

  • Regular security testing of all applications against commonly occurring and newly discovered vulnerabilities.
  • Comprehensive security test covering maximum functionalities and business logic must be done for at least business critical applications if not all.
  • Vulnerability intelligence - Identify which classes of vulnerabilities has been detected the most in applications. Also identify if similar classes of vulnerabilities are introduced in newly developed applications and/or features.
  • Developer training on how to fix, avoid and mitigate security vulnerabilities is a must. This helps in ensuring that similar vulnerabilities are not re-introduced in future development efforts.

In general, the security strategy for most organisation is reactive in nature i.e. we react to discovered vulnerabilities by patching or mitigating the threat via. workarounds. For organisation with greater threat perception, this cannot continue for ever! An organisation must develop a security roadmap that consists of moving forward - Reactive to Proactive and finally towards Predictive.

For almost a decade, implementing security in an organisation usually started with a VA or PT, followed by patching of discovered issues. However, due to the nature of current threats and skill level of adversaries, it is not enough to continue fixing issues discovered during VA/PT. This method just don't scale and becomes almost unmanageable for large organisations with wide range of assets. It is important for an organisation to be more proactive where it mitigates common classes of vulnerabilities and work towards a better security development life-cycle where common security issues are avoided at design and development stage only.

Some of the points that should be considered while developing an application security strategy:

  • Regular security testing
  • Vulnerability management & intelligence
  • Security as a part of Development/SDLC
  • Developer training and skill development
  • Operational Security (secure deployment and management of apps)




Wednesday, October 8, 2014

Announcing Free Scan for Web Application Security

Online free service for Web App Security

What is it?


We are super excited to launch our FreeScan for Web Application Service. It is an online hosted service that can perform automatic security scan of websites or web applications. We have implemented tests for most commonly occurring issues in websites or web applications that can have a security impact.

Who is it for?


This service can be used by anybody with web presence, whose business continuity depends on confidentiality, integrity and availability of its website, business data and client data. Online businesses with strong brand presence can also use this service to look for common security issues to prevent loss of brand due to security incidents. Security engineers or administrators can benefit by scanning their web infrastructure using this service. If you are an enterprise with mass scanning requirements, this might not be the right solution for you. However, do get in touch, we might be able to offer something appropriate.

What does it offer?


The FreeScan for Web currently looks for a bunch of commonly occurring issues in web applications including:

  • HTTP headers security
  • HTTP cookie security
  • HTTP insecure methods
  • SSL/TLS crypto strength & security
  • SSL/TLS configuration weakness
  • Heartbleed
  • Shellshock

Why is it Free?


We in 3S Labs have been doing a lot of Web Application Penetration Testing. In fact, web security test is perhaps one of our most frequently delivered service. Due to our prolonged involvement, we have been writing a bunch of miscellaneous scripts and tools for detecting common issues in web applications. Although the quality of any Penetration Test depends significantly on the skill and expertise of the tester involved, identification of many of the commonly occurring issues can be automated to a certain extent to increase productivity. FreeScan is our project to offer online hosted security services for free, using tools and techniques that graduate out of our research lab. We intend to maintain and extend this service based on our R&D output. However, only tests that can be implemented automatically with a certain degree of reliability and can be executed in a fixed time will be added to FreeScan. This means, you can test your applications for common issues, however for serious security requirements (quality & coverage), you still need a good and experienced security consultant.

Due to the scope and architectural pattern used in developing FreeScan service, it can be easily scaled up or down depending on demand. We should be able to support scanning of a large number of websites or web applications using this service. However, due to the open nature of the service, misuse may be eminent. In order to prevent misuse, we have currently considered a manual approval of scan. In future, we might consider automating the ownership verification of a site to limit misuse and legal issues on our part.


Coverage and Quality


A conventional Web Application Penetration Test consists of roughly the following steps:
  1. Application discovery through web page crawling.
  2. Attack surface enumeration based on detected functionality.
  3. Testing various input/output flows for possible vulnerabilities.
  4. Business logic testing.
  5. Framework/technology specific testing.
In this case - [1], [2] & [3] are directly related i.e. based on the quality of [1] & [2], the effectiveness of [3] will be determined which is the most important part of a proper web application security testing. Apart from that, a security consultant must also enumerate various business logic in the application and test them duly for possible violations. In general, a web application test with good coverage requires significant human intervention and cannot be automated fully. Due to the nature of human intervention, the quality of findings depends on the skill and experience level of the person involved in testing.

We are not trying to build a full fledged web application security scanner. The complexity involved in developing and maintaining such a software is beyond the scope of this service. However, for all practical purpose, it has been noticed that roughly 20% of the vulnerabilities (or weakness) appears 80% of the time. Many of these issues are trivial to detect and can be automated as well. We want to implement these tests in our FreeScan service so that our service can be used to quickly identify most commonly occurring issues in a website or web application.

Critical Vulnerability Detection


Due to our in-house R&D capability, we are in a position to respond quickly to critical vulnerabilities that are discovered or found exploited in the wild. We intend to add detection capability in FreeScan for critical vulnerabilities that are discovered in the future. For example, we were able to analyze, reproduce and add test for Shellshock vulnerability disclosed recently. FreeScan for Web Application supports scanning for Shellshock vulnerability in web applications.




 FreeScan for Web Application


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, September 11, 2014

5 Vulnerabilities That Surely Need a Source Code Review

We have been performing Source Code Review (SCR) of multiple Java/JavaEE based Web Applications during the recent past. The results have convinced us and the customers that SCR is a valuable exercise that must be performed for business critical applications in addition to Penetration Testing. In terms of vulnerabilities, SCR has the potential to find some of the vulnerability classes that an Application Penetration Test will usually miss out. In this article we will provide a brief overview of some of the vulnerability classes which we frequently discover during an SCR that are missed out or very difficult to identify during Penetration Testing.

Additionally we hope we will be able to provide answers for the following commonly asked questions:
  1. I have already performed an Application Penetration Test. Do I still need to conduct a Source Code Review for the same application?
  2. What are the vulnerabilities found during Source Code Review that are often missed by Application Penetration Test?
Read More: Web Application Penetration Testing Service

Approach for Source Code Review


The approach for SCR is fundamentally different from an Application Penetration Test. While an Application Penetration Test is driven by apparently visible use-cases and functionalities, the maximum possible view of the application in terms of its source code and configuration is usually available during an SCR. Apart from auditing important use-cases following standard practices, our approach consists of two broad steps:

Finding Security Weaknesses (Insecure/Risky Code Blocks) (Sinks)

A security weakness is an insecure practice or a dangerous API call or an insecure design. Some examples of weaknesses are:
  • Dynamic SQL Query: string query = "SELECT * FROM items WHERE owner = '" + userName + "' AND itemname = '" + ItemName.Text + "'";
  • Dangerous or risky API call such as RunTime.exec, Statement.execute
  • Insecure Design such as using only MD5 hashing of passwords without any salt.

Correlation between Security Weakness and Dynamic Input

Dynamic construction of an SQL Query without the necessary validation or sanitization is definitely a security weakness, however it may not lead to security vulnerability if the SQL query does not involve any untrusted data. Hence it is required to identify code paths that start with an user input and reaches a possibly weak or risky code block. The absence of this phase will leave huge number of false positive in the results.

This step generally involves enumerating sources and finding a path between source to sink. A source in this case is any user controlled and untrusted input e.g. HTTP request parameters, cookies, uploaded file contents etc.

Five Vulnerabilities Source Code Review should Find


1. Insecure or Weak Cryptographic Implementation


SCR is a valuable exercise to discover weak or below standard cryptography techniques used in applications such as:
  • Use of MD5 or SHA1 without salt for password hashing.
  • Use of Java Random instead of SecureRandom.
  • Use of weak DES encryption.
  • Use of weak mode of otherwise strong encryption such as AES with ECB.
  • Susceptibility to Padding Oracle Attack.

2. Known Vulnerable Components


For a small-medium scale JavaEE based application, 80% of the code that is executed at runtime comes from libraries. The actual percentage for a given application can be identified by referencing Maven POM file, IVY dependency file or looking into the lib directory. It is a very common possibility for dependent libraries and framework components to have known vulnerabilities especially if the application is developed over considerable time frame. As an example, during 2011, following two vulnerable components were downloaded 22 million times:


During an SCR, known vulnerable components are easier to detect due to source code access and knowledge of exact version number of various libraries and framework components used, something that is lacking during an Application Penetration Testing.

3. Sensitive Information Disclosure


An SCR should discover if an application in binary (jar/war) or source code form may disclose sensitive information that may compromise the security of the production environment. Some of the commonly seen cases are:
  • Logs: Application logs sensitive information such as credentials or access keys in log files.
  • Configuration Files: Application discloses sensitive information such as shared secret or passwords in plain text configuration files.
  • Hardcoded Passwords and Keys: Many applications depend on encryption keys that are hardcoded within the source code. If an attacker manages to obtain even a binary copy of the application, it is possible to extract the key and hence compromise the security of the sensitive data.
  • Email address of Developers in Comments: A minor issue, but hardcoded email addresses and names of developers can provide valuable information to attackers to launch social engineering or spear phishing attacks.

4. Insecure Functionalities


An enterprise application usually goes through various transformations and releases. The application might have legacy functionality with security implications. An SCR should be able to find such legacy functionality and identify its security implications. Some of the examples of legacy functionalities with known security issues are given below:

  • RMI calls over insecure channel.
  • Kerberos implementation that are vulnerable to replay attack.
  • Legacy authentication & authorization technique with known weaknesses. 
  • J2EE bad practices such as direct management of database/resource connection that may lead to a Denial of Service.
  • Race condition bugs.

5. Security Misconfiguration


SCR should be able to find common security misconfiguration in application and its deployed environment related to database configuration, frameworks, application containers etc. Some of the commonly discovered issues include:

  • Application containers and database servers are running with highest (unnecessary) privilege.
  • Default accounts with password enabled and unchanged.
  • Insecure local file storage.

Additional Notes


An in-depth Source Code Review exercise is a valuable activity that has significant additional benefits apart from those mentioned above.

It is possible to conduct an in-depth review of implementation of security controls such as Cross-site Request Forgery (CSRF) prevention, Cross-site Scripting (XSS) prevention, SQL Injection prevention etc. It is not uncommon to find codes that lack or misuse such controls in a vulnerable manner resulting in bypass of protection.

There are multiple APIs that are considered to be risky or insecure as per various secure coding guidelines. It is possible to discover usage of such API in a given application easily and quickly during an SCR process.

SCR has the added benefit of being non-disruptive i.e. this activity does not require access to production environment and will not cause any service disruption.

Source Code Review (SCR) is a valuable technique to discover vulnerabilities in your Enterprise Application. It discovers certain class of vulnerabilities, which are difficult to find by conventional Application Penetration Testing.  However, it must be noted that Application Penetration Testing and Source Code Review are complementary in many ways and both independently contribute in enhancing overall security of application and infrastructure.



Thursday, August 28, 2014

Attack Patterns of 2013 and Lessons for the Future

Verizon DBIR 2014 is one of the most comprehensive and well researched report on various attacks and data breaches as seen by companies involved in attack & incident analysis and threat intelligence during 2013.

2013 Attack Patterns


As per the Data Breach Investigation Report (DBIR), year 2013 has seen top attacks and incidents in the following areas:
  • Point-of-Sale Systems
  • Web Applications
  • Cyber Espionage
  • Attack on Financial Services

Top attack patterns


Point of Sale (POS) Systems


It was found that majority of the attacks on POS systems were external in nature i.e. from outside the operating network. The intruders used simplistic scanning tools for identifying POS systems over the Internet. Once identified, guessed (educated) passwords and public exploits were the main tools of compromise to gain access in the systems. RAM scrapers were the primary tool of choice for these threat actors to collect decrypted payment related information including credit card details.

Web Applications


Web applications are surely the target of choice for most attackers. The amount of bug bounty earned by researchers across the world from companies like Google, Facebook, Paypal etc. for web application vulnerabilities speak for it.


However it must be considered that Bug Bounty programs should not be treated as a replacement for conventional Penetration Testing. The two approaches are complementary to each other. Any professional services engagement is usually time boxed and ideally should focus on core aspects of the security of target applications including its possible attack surfaces and issues that directly affect the business operations of the application. Given a large application, it may not be possible to identify all possible vulnerabilities within the defined time frame. This is where the Bug Bounty model comes in. The crowd sourced nature and pay per vulnerability model is effective in identifying and eliminating maximum low hanging fruits in the most cost effective manner. This is a typical case of - Given enough eyeballs, all bugs are shallow. It should also be noted that really complex and interesting vulnerabilities in popular services such as Facebook, Google, Github etc. has also been disclosed as a part of Bug Bounty initiatives. However due to the sheer volume of web applications, it is generally a better approach to consider both professional Penetration Testing and Bug Bounty programs for an effective security testing strategy.

Insider Abuse


It is relatively well known that an Information Technology infrastructure faces threat not only from outside its corporate network but also from inside. There has been multiple cases where Threat Actors were found to be insiders or assisted by insiders.

However it should be considered, due to lack of security awareness and operational security practices, insiders may end up being the pawns or pivot for launching attacks from inside the local network. The exploits of Syrian Electronic Army has highlighted the need for appropriate operational security practices. Even the strongest and most secure IT infrastructure may end up compromised due to lack of security awareness of those operating the systems. Hence it is very important to consider security in all three aspects viz. People, Process & Technology.

Shifting Motivation for Threat Actors


The DBIR also highlight an interesting pattern - The shifting motivation of Threat Actors. This is something inevitable given the rise of Bug Bounty programs and determination of important software vendors to consider defence-in-depth through exploit mitigation techniques to seriously increase the cost of practical attacks.

Threat actor motivation over time

Unlike popular perception, it turns out that random hacking incidents are relatively rare and most of the incidents so far are clearly motivated by economic gains. However over time, the data shows that the threat actors are shifting from Financial fraud to espionage related activities. This is probably an indicator of the growing importance of cyber medium for security agencies of various governments. This might also be an indicator of the growing cost of conducting practical attacks using sophisticated tools and 0day exploits.

Lessons or Inferences from the Investigation Report


  • POS System compromise could have been prevented by minimum security investments - Penetration Testing and basic Operational Security like strong passwords, use of Anti Virus etc. could have prevented a majority of the incidents.
  • Web Application vulnerabilities are still prevalent. The industry in general is very much aware of the issues and the rise of bug bounty programs might help curb misused vulnerabilities to a certain extend as long as companies do not replace conventional Penetration Testing with Bug Bounty programs - they complement each other.
  • Espionage "industry" is on the rise. The amount of leakage from relevant agencies involved in Cyber Espionage and exposure from their contractor companies provide enough evidence of its rise and prevalence. Growing investment will encourage researchers to continue innovative security research. Highly sophisticated tools and exploits will continue, but cost of entry will be very high.

General Takeaway

  • Minimum security investment is a must for any IT based business.
  • For organisations with serious security concerns - It is very important to realise that security cannot be achieved by a one-time investment. It is a practice that involves regular activities and development of individuals responsible for its operations.
  • Human Factor is an important aspect of the overall organisational IT infrastructure. Security development/maturity of the human factor must be equally considered along with the Technological aspect.
  • Vulnerabilities will exist. Most leaders in this business accept this fact and is working towards Defense-in-Depth. However you must reach a certain security maturity level in terms of your internal practices and externally exposed risks before you can start considering such strategies effectively.



Tuesday, August 19, 2014

The ActiveAdmin and Inherited Resource Mess

ActiveAdmin is a very popular library for Ruby on Rails to effortlessly implement administrative functionalities in your Rails application. You end up having Forms and Actions for CRUD operation on your models without just about any effort.

However, we recently noticed a scary scenario for a Rails application using ActiveAdmin due to a 3rd party gem (library) that is being used by ActiveAdmin - inherited_resources.

Scenario:
  • A set of resources for e.g. ResourceA, ResourceB e.t.c are internal to the application and need not be created based on user input. However information for those resources are available to the user without authentication i.e. the "read" operation is available and the corresponding "show" method is implemented in each of the respective controllers.
  • The developers implemented only the "show" method in each of the controllers assuming that the other operations such as "create", "write", "delete" e.t.c will not be possible due to the absence of the relevant methods in the controllers.

Resource creation
Exception without inherited_resource

It turns out that ActiveAdmin by default generates a Rails controller with InheritedResource::Base as the base class instead of the default ApplicationController if the corresponding controller is not already generated. This technically implies that any CRUD operation on the generated controller will be handled by InheritedResource::Base which performs the default action as requested.

This scenario resulted in unexpected authorisation issue in the application. Technically this is not a vulnerability in ActiveAdmin or InheritedResource but due to the difference in behaviour compared to Rails default, an application might end up having unexpected default actions in its controllers.

To summarise:
  • ActiveAdmin is a great utility for any Rails application.
  • If you are using ActiveAdmin, ensure you know what InheritedResource::Base is doing.
  • It is always a good idea to authorise all actions in your controller instead of depending on exception handling.


Tuesday, July 8, 2014

Word Exploit Delivery using MIME HTML Web Archive

The creativity and research seen in Anti-virus evasion is interesting, not to consider the "maturing" nature of AV industry :)

We have, multiple times in the past, came across Microsoft Office related exploits packaged and delivered as MIME HTML documents with a .doc extension. Surely Microsoft Word is known to handle and process such documents. Recently we came across a well known exploit for MS12-0158, which is detected by almost all major Anti-virus software in its raw form, however we noticed 100% evasion against the common AV products, when delivered as a MIME HTML package.

MIME HTML Package of MS12-0158 Exploit

Anybody analysing a malicious Word document will be surprised at the first look of the content of the file. During further investigation, it was found that Microsoft Word support what is called a MIME HTML Web Archive. It was identified that the HTML code in turn invokes a known to be vulnerable control with data that triggers a Stack based Buffer Overflow in MSCOMCTL.OCX.


The parameter to the ListView control that exploits the vulnerability is also embedded as a part of the document:

The part is referenced by ActiveX control initialisation earlier in the document.

Even though the sample evaded all AVs we tested at the time of writing, the above document part in its raw form (Base64 decoded) seem to be quite well known among AV products.


The next step was to look into the exploit itself and the shellcode responsible for delivering the payload. A quick look on the decoded bytes gave an idea about the possible nature of the exploit and the start of the shellcode. Multiple NOP (0x90) bytes were identified prepended to a jmp short (0xeb) instruction.

Hexdump of param data passed to ListView control

Here 0x27583c30 is a platform independent address of JMP ESP instruction in MSCOMCTL.OCX used as a RETURN ADDRESS for exploitation of the vulnerability. The JMP ESP return is used for transition to shellcode that follows the return address.



The RETURN ADDRESS in the above dump is immediately followed by the shellcode that starts with a bunch of NOP instruction. Upon closer inspection, the shellcode was found to be XOR encoded. The decoder decodes the actual payload by performing XOR operation on each byte with 0xBF as the key.

XOR decoding of shellcode

The 2nd stage shellcode in turn performs the following:
  • Extracts an embedded executable from the document.
  • Decodes the executable.
  • Drops and runs the executable from the Temporary Directory.
  • The dropped executable in turn runs a VBE payload which is persisted by creating a shortcut in the current user startup directory.

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

Friday, January 25, 2013

Scanning Process Memory for Injected Code

This post presents a simple yet effective approach to quickly scan running processes for runtime code injections, something we always felt is required during analysis of a possibly infected system.

Code Injection Techniques


There are a bunch of techniques available for generic injection of custom code into the address space of a remote process in Windows platform, some of which are documented here and here. In most cases, a call to CreateRemoteThread(..) is made to start execution of injected code under the context of the remote process.

A rough workflow for injecting and running code within the address space of a remote process can be summarised as below:


DLL Injection done using SetWindowsHookEx API does not involve a call to CreateRemoteThread(..). However detecting injection of malicious DLL using SetWindowsHookEx is usually trivial - One just needs to list all the loaded modules in the target process and look for possibly non-standard path.

Scope of our Approach


We aim to devise a more or less generic approach for detecting injected code in the address space of a given process in a non-intrusive manner.

Our approach is tested against some of commonly used tools and trojans that employ process injection techniques such as Metasploit's Meterpreter and common process injecting trojans like PoisonIvy, Cyber Gate etc.

Limitation of our Approach


Our approach involves False Negative if a DLL is injected into the address space of remote process using SetWindowsHookEx API.

False Positives were encountered while testing applications that generate valid code at runtime such as Java JIT Compiled code. False Positives may also be encountered for packed executables that perform in-memory unpacking.

Methodology


We employ a simple yet effective methodology for scanning multiple processes at runtime for injected code. Our approach is simple and easy to implemented without too much of performance hit.

The crux of our approach lies in the fact: In almost all cases of code injection in remote process memory, the foreign code that is being introduced in the address space of the target process for execution does not belong to any of the executable sections of the PE files(s) (exe, dll etc.) loaded within the context of the target process.

Our methodology involves scanning each thread context and its corresponding stack frames in the target process for possible Instruction Pointer address that does not belong to an executable section of any of the PE modules loaded in the target process.

Implementation


The full implementation of the above methodology is available Here. The implementation involves the following core steps:

  • Enumerate each Thread in the target process.
  • For each Thread, obtain the stack trace of the Thread using StackWalk64 API.
  • For each Stack Frame, check if Instruction Pointer (AddrPC) points to any address outside executable sections of the loaded PE modules (exe, dll etc.)

Implementation Note: Stack Walking is a non-trivial process due to that fact that stack may look very different for different executables due to difference in compiler settings and optimization. Stack Walking process may be different for different platforms as well. StackWalk64 is a documented and portable method for enumerating stack frames of a given Thread however appropriate care must be taken else obtained results may be incoherent.

Field Testing

  • Meterpreter (Reflective) DLL Injection
  • Poison Ivy (Browser Process Injection)
  • Cyber Gate (Browser Process Injection)

Meterpreter migrated to Notepad.exe Address Space

PoisonIvy running inside default browser


This is a proof of concept pre-alpha release only. Feedback and bug reports will be greatly helpful.

References


http://support.microsoft.com/kb/2458544
https://github.com/abhisek/RandomCode/tree/master/Malware/Process
http://metasm.cr0.org/
http://en.wikipedia.org/wiki/DLL_injection
http://www.codeproject.com/Articles/42450/Remote-Code-Process-Injection-and-Relocation
http://msdn.microsoft.com/en-us/magazine/cc301805.aspx
http://www.codeproject.com/Articles/11777/InjLib-A-Library-that-implements-remote-code-injec


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/