3S Labs Banner

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