Saturday, 13 May 2017

Malware Analysis

Malware Analysis is the study or process of determining the functionality and potential impact of a given malware sample such as a virus, Trojan horse, rootkit, or backdoor.

How to perform dynamic and static analysis on all major files types, how to carve malicious executable from documents and how to recognize common malware tactics and debug and disassemble malicious binaries.

 Almost every system or network breach involves a Trojan, backdoor, virus, or rootkit. Incident responders (or Malware Analysts) perform appropriate malware analysis in order to fix the current infections and prevent any future ones. According to the Verizon Data Breach Report 2015,      “70-90% of malware samples are unique to an organization”. (bcz of Targeting is happening).

The various types of Malware analysis Involves Dynamic, Static, and Hybrid state/dynamic analysis, which are used to detect malware in a system or a network.

This Malware Analysis covers a wide range of topics such as Windows Malware Analysis / Basic Forensics / Incident Response / Malware Discovery / and Basic Reverse Engineering.

 However, it is advisable to have a general idea about the following topics:

                Networking – TCP/IP
                Operating System Internals
                Programming (C/C++)
                Software Vulnerabilities

What is Malware Analysis and Why is it useful:

                > AV cannot be relied on
                > Breaches involve malware
                > If Breach happens - Now what ?
                       * Typical:
                                  Remove from network.
                                  Reimage the machine.
                       * Advanced: Incident Response                                      
                                  > Analyze Logs, Network traffic, Strange Processes etc
                                  > is it any where else?
                                  > How did it get there?
                       * Mature: Gather Intelligence

                > What is the impact?
                > What is the risk?
                > Finically motivated ? Hacktivism ? Opportunistic?
                           Avanced Persistent Threat(APT)?,  APT group's                                              
  Malware Types/Functionality
        Virus  (file infector Rare)
        Trojan (Common)
        Worm   (Rare)
        Bot     (Very Common)
        Rootkits (UnCommon)
        RAT ---- Remote Access Tool/Trojan (Very Common)
More Specialized:
                 Credential Stealers
                 Loader Downloader
 Can buy malwares from Dark Web... Builders / Exploit Kit / Packer-Crypter / Hair a Hacker                                                            

  Types Of Malware Analysis

  1.  Dynamic Analysis:

     We just Executing the malware in a VM/LAB and check what is happening. (FireEye MAS, Any Virtual machine).

Some online file reputation analysis service providers :



 Simple, Fast, Easy to miss things. (ex. things in code like kill date etc)
                       We can get some n/w confirmation.

                                              > Will get C2C server details.
                                              > Will get IP it is connecting to and many more...
But it is easy to miss the things. Say some breakout date is coded in malware etcSome Kill date in which malware will wipe out the entire computer. (Only way to analyse this kind of issue is that of going for a static analysis).
This form of analysis is often performed in a sandbox environment to prevent the malware from actually infecting production systems.  many such sandboxes are virtual systems that can easily be rolled back to a clean state after the analysis is complete.

The malware may also be debugged while running using a debugger such as GDB or WinDbg to watch the behavior and effects on the host system of the malware step by step while its instructions are being processed.

 Modern malware can exhibit a wide variety of evasive techniques designed to defeat dynamic analysis including testing for virtual environments or active debuggers, delaying execution of malicious payloads, or requiring some form of interactive user input.

CWSandbox: Early malware sandbox solution.

GFISandbox: Sandbox solution c. from GFI Software, became ThreatAnalyzer.

Cuckoo Sandbox: Sandbox solution c. 2012?, open source on GitHub,
    designed for automated malware detection and profiling.

Cuckoo Sandbox is a Malware Analysis System.You can throw any suspicious file
 at it and in a matter of seconds Cuckoo will provide you back some detailed results outlining what such file did when executed inside  an isolated environment.


Joe Sandbox: Sandbox solution c. 2010 from Joe Security.
      First solution introducing Hybrid Analysis. Enables analysis on any device,
  including bare metal laptops, PCs and phones. Supports analysis on Windows,  Android, MAC OS X and iOS.

ThreatAnalyzer: Sandbox solution c. 2013–present from ThreatTrack Security,
  designed for automated malware detection and detailed profiling.

VMRay: Sandbox solution c. 2015 from VMRay. Created by the original author of  WSandbox.
 Instead of hooking, the target machine is unmodified and monitoring and control is
done at the hypervisor layer.

Droidbox : DroidBox is developed to offer dynamic analysis of Android applications.


Buster Sandbox Analyzer : Buster Sandbox Analyzer is a tool that has been
designed to analyze the behaviour of processes and the changes made to system
and then valuate if  they are malware suspicious.

The changes made to system can be of several types: file system changes,
 registry changes and port changes.

A file system change happens when a file is created, deleted or modified. Depending of what type of file has been created (executable, library, java script, batch, etc) and
where was created (what folder) we will be able to get valuable information.

Registry changes are those changes made to Windows registry.
In this case we will be able to get valuable information from the modified value keys
and the new created or deleted registry keys.

Port changes are produced when a connection is done outside, to other computers,
or a port is opened locally and this port starts listening for incoming connections.

From all these changes we will obtain the necessary information to evaluate
the "risk" of some of the actions taken by sandboxed applications.

Watching all these operations in an easy and safe manner is possible thanks to
Sandboxie (, an excellent tool created by Ronen Tzur.

Even if Buster Sandbox Analyzer´s main goal is to evaluate if sandboxes processes
have a malware behavior, the tool can be used also to simply obtain a list of changes
made to system, so if you install a software you will know exactly what installs and where.

Additionally apart of system changes we can consider other actions as 
malware suspiciouskeyboard logging, end the Windows session,
load a driverstart a service, connect to Internet, etc.

All the above operations can be considered as not malicious but if they are
performed when it´s not expected, that´s something we must take in consideration.
Therefore it´s not only important to consider what actions are performed.
It´s also important to consider if it´s reasonable certain actions are performed.

SandBox Automation
Note: Some hosted sandboxes, such as Malwr, use one of the above products under the hood (Malwr
uses Cuckoo).
 2. Static Analysis:

   We won't execute the malware. We will slowly step through it. ie, 
One instruction at a time like what is this doing and find out.
This will capable of identifying more about the malware. (Require lot of technical knowledge)
   Reverse Engineering. It is slow. Need deep technical knowledge.

3. Hybrid Static/Dynamic:  most malware analysis is hybrid.

       > Most Analysis is a mixture: You find something in the disassembly then you
                  confirm/investigate while the malware is executing.

       > Memory Forensics: Can be vary useful, but is not the end-all-be-all.

    In-memory analysis(Volatility/Rekall) , execute a malware and then dump 
what ever in the memory and look at it statically.
Helps to analysis what ever in memory at that time. It helps to understand
what are the original things that the hacker tries to protect.
Most of malware analysis is actually hybrid.

Where you are using a VM to execute the malware safely or some kind of Sandbox
and we verify it with some kind of static approach. Like IP/network is work like this etc.

Four stages of malware analysis:-

              Examining Malicious software involves several stages, however the below stages mentioned can be considered as discrete and sequential steps over-simplifies the steps malware analysis process:

                 > Manual Code Reversing
                 > Interactive Behavior Analysis
                 > Static Properties Analysis
                 > Fully-Automated Analysis

Basic Tools useful for malware analysis:

            MAP Pack
            010 :
            PE Viewer : CFF Explorer, PE Explorer, PE View,
            A disassembler: IDA Pro,x64_dbg,Hopper etc
             > Other Preferences:
                  Cygwin - md5sum, gcc, xxd, file, strings, python-2.7.12
PE Studio

Regshot : 

Map (Malware analysis pack) :
It will install several of this shell extensions MD5 hash / sub-strings / Submit to VT / VT check /

Check ASCII and Hexa file and see for File header to see what kind of file it is.(say executable)

Get Samples:


            Contagio Malware Dump: Free, password required

            KernelMode info: free, registration required


   : free, registration required.


            Malware DB:


            Open Malware:

            SecuBox Labs: Free


            > Catch your own: Honey Pot
            > Make your own:
                           > Program based on description
                           > Download a builder:

You can create your own malware using builders or catch your own malware using Honey Pot.
 There are certain malware that are triggered when scanned, extracted from Archive(, or viewed icon (Word, PDF, or System Icon). You’ll also learn about hash collision and why the industry is adopting SHA256 when compared to MD5.

         Two recommended learning tools that will help you expertise in the area:

       > Practical Malware Analysis by Michael Sikorski and Andrew Honig
   > Virus Research and Defense by Peter Szor.

   Module 2: Lab Setup
 We’ll explore a basic lab setup, involving running a local VM on a Windows local machine (referred to as the victim) and funnelling traffic through a Linux VM (called the Router).  This module begins with the installations of VMware workstation, Windows XP, and finally, setup of Kali for networking.

  Run VM in host-only mode is fine while running a malware in it

  Anti-Debugging Techniques:
        Process Name Check
  Vmware LDT Register Detection
  Vmware STR Register Detection
  Vmware special I/O Instruction
  Checks special VT-x or VMM instructions
  Timing checks
  Registry Checks
  Virtual MAC Address
  Virtual hardware names
  Checks Common VM drive ID's

To enhance your skills and expertise in the topic, you can read or refer to the following resources:

Practical Malware Analysis
Anti-Debugging – A Developer’s Viewpoint
Scientific but Not Academical Overview of Malware Anti-Debugging, Anti-Disassembly and Anti-VM Technologies

    Module 3Dynamic Analysis Part 1.1
 What is Dynamic malware analysis : The goal of malware analysis is to generate the Indicators of Compromise (or IOC’s), determine the malware type or attributions.

         > Execute the Malware
First Response / Triage
> Virtual Machine vs. Native Hardware Goals:
       > Generate Indicators of Compromise (IoC's) :

       > Determine Malware Type/Family : Is it a backdoor / trojan / Bot
      > Assess Risk and Impact of this to your organization :
      > Attribution :

 It is easy and fast.

       Dynamic Analysis Part 1.2
 Demo: Using Dyre Malware family.

 > theZoo aka Malware DB :
 >  Dyre:

This session opens with a quick demo to explain malware analysis using certain tools. Next, we’ll download a malware code from the Github site.

 The required malware analysis tools are also downloaded on the virtual machine.

We will then discuss how to identify indicators (or IOC’s) for a Dyre malware. The tools that will be explored for IOC’s are CaptureBAT, RegShot, and Autoruns.

You’ll also learn how these tools help in identifying malware activity and how do they differ from each other.

 > Download Malware from :

        > Snapshot :
           > CaptureBAT
        > RegShot
        > Autoruns

  > More advanced:
          > SysAnalyzer
      > ProcMon
     > OllyDbg --- bebugger for reverse engineering

 1. Go to  --- Here you will
get source code for many malware families built over the years. from here you can download

 2. Download "Sysinternals Suite"
    ( )

3. Install CaptureBAT / Malcode Analyst Pack / 010 Editor / Notepad++ / 7zip
     then extract RegShot / Sysinternals
    Setup CaptureBAT with needed arguments.
"C:\Program Files\Capture\CaptureBAT.exe" -c -n -l "C:\Users\W7\Desktop\batlog.txt"
4. Take a Snapshot of the VM Machine before you are execute malware in it.

5. Extract malware ( Passwd: infected ) passwd is industry standard
      Before executing the malware run CaptureBAT and also make sure your 
machine is not connected to internet or with local system.

6. Execute malware ( here PDF document with .scr extension )
     After some time close the CaptureBAT and open the log file (will create when execute captureBat. alread mentioned while creating target in desktop)

Open the log file in notepad++ and Check for "Process" / "file" write or delete / "registry"   setvaluekey.

check for IOC's and if any file adding get it's md5 hash value

 ( here we are having googleupdaterr.exe / and a registry entry for GoogleUpdate / get MD5 for .scr file / get MD5 for googleupdaterr.exe just check both the md5 values are matching or not. )

  So now we are having some IOC's with us. So check it against the old spanshot we took.

 7. Now launch the old snapshot. Here we execute RegShot. it will do two things, will take the spanshot of the registry and also another snapshot after executing the malware once again.

    > Take 1st shot
 > Execute Malware
 > Take 2nd shot
 > Compare

In this file we can able to find RNG (Random number generator)/Seed those values we can ignore..
  those will very each time and it's the natural way the windows is executing.

Also we can able to Scan directories using RegShot and can see what files are changed in those.

You can delete the all new files created / delete the registry keys created / and other files or folder and reboot. Then again check and see whether the presence of malware is showing again or not.

8. Other than the above steps we are using another tool called sysinternals "autorunsc.exe"(cmd line) / autoruns.exe (gui)

      Dynamic Analysis Part 1.3

> Some Malware will detect:
     > Executing / Installing Analysis tools
     > Virtual machine containment
 > Sandbox Containment
 > Security products

  Certain malware programs may not run if the username is ‘analysis machine’ or just ‘user’, or if it detects a sandbox environment, security products or on a VM. Further we’ll discuss other reasons why some malware don’t work on some virtual machine. You’ll also learn certain malware execution tips.

> Other reasons why it might not run correctly:

     > Incorrect environment:
         > Software Versions
 > Installed OS Languages
 > Multiple components
 > Disabled networking

 > Bugs in the malware
 > Dependencies not met
 > Kill dates
 > Specific Target

Tip: Malware repo should be non-execute:

  > Windows Host:
                     icacts C:\malware /deny "Everyone: (OI)(IO)(X)"
                                               (user string)

      > Linux Host:
                    chmod 600 /malware <file name>

      > user interaction

Else it may chance to infect your machine even before you remove the network cable from machine.

Note: read Practical Malware Analysis by Michael Sikorski and Andrew Honig to learn more about dynamic analysis.

    Module 4Dynamic Analysis Part 2

During any kind of malware analysis Indicators Of Compromise(IoC's) are important to identify,

In System Level:

 > File Hashes
 > Strings
 > Registry Keys
 > File Names
 > File Paths
 > Process Names

In Network level:

 > IP Addresses
 > Domains
 > URLs
 > Network Traffic


OpenIOC is an extensible XML schema that enables you to describe the technical characteristics that identify a known threat. It categorize tones of indicators, like below.

> Driver Attached to driver name
> Driver Device Name
> EventLog ID
> EventLog GenTime
> EventLog Log
> EventLog Messages
> EventLog User
> File Name
> File Full Path
> File MD5
> File Import Function
> File Compile Time
> File Size
> Network DNS
> Process Handle name
> Registry Path
> Registry Text
> Service Name
> File Attribute
> File Extension
> File Path
> File Modified Time
> File Base Address
> File delected Anomalies
> File Entrypoint sig name
> File Entrypoint sig Type
> File Certificate Subject
> File Digital Signature Exists
> File Digital Signature Verified
> File export Function
> File Export Count
> File Import Name
> File PE checksum API
> File PEInfo ResourceInfo Type
> File Detected Signature
> File Created Time
> File Section Name
> File PE Section SizeInBytes
> File PE Subsystem
> File PE Type
> File PEInfo Language
> File PEInfo ProductName
> File PeakCodeEntropy
> File PeakEntropy
> File ADS MD5Sum
> File ADS Name
> File ADS SizeInBytes
> File Strings
> File Owner
> Hook Function
> Hook Hooked Module
> Hook Hooking Module
> Network String General
> Network String URI
> Port localPort
> Port Process
> Port Remote IP
> Port RemotePort
> Process Type
> Process RemoteIP
> Process RemotePort
> Process Section Name
> Process Section Import Module
> Process String List
> Process UserName
> Process Arguments
> Process Name
> Process parentPID
> Process Path
> Registry Key ModDate
> Registry Type
> Registry Value

 Yara : YARA is a tool designed to help malware researchers identify and classify malware samples. It's been called the pattern-matching Swiss Army knife for security researchers (and everyone else).


  Dynamic Analysis Part 2.2

 Demo Malware: Illision Bot

 > Downloaded sample:
           get file

 > Network Traffic
               > WireShark

   > Strings ---> YARA Sigs

Passwd for malware: infected

 1. Execute CaptureBAT
 2. Run WireShark and capture the traffic
 3. make sure VM network is restricted only for that machine
 4. Execute the malware and check the traffic on wireshark
 5. inetsim .... Execute this command in linux machine through 
     which VM traffic is passing It will emulates different services which 
will listen on different standard ports and kill it after some time.

 6. add route in windows machine to go all traffic to the linux machie. edit the inetsim config machine and add route IP in that to resolve DNS to that IP

 7. can use netcat to check listening port. and see what malware doing.

          Follow steps above

   Module 5: Basic Static Analysis
  What is static Analysis:
                      > Reading the assembly code from the executable
                      > Use tools such as

> Characteristics
     > Slow
 > Detail oriented
 > Technical knowledge required

> Goals
   > Confirm Dynamic analysis
 > Understand Behavior
 > Find more IOC
            > Encrypted strings/payloads
> DGA's
> Network traffic encryption algorithms
 > Determine Defenses
            > anti-debugging
 > Determine Capabilities for Assess risk and impact
                                                 > attributions

 [  You’ll also be learning about debuggers, compilers, and disassemblers. The key characteristics of static analysis are that it is a slow, very detail-oriented process, requiring huge technical know-how. Static analysis is utilised to confirm your findings in dynamic analysis and understand the behaviour of malware.
It also helps you to identify additional Indicators of Compromise (IOCs) such as encrypted strings or payloads, domain generation algorithms (DGA’s), and network traffic encryption algorithms.

Further, you’ll learn that assembly code is a human readable code for a particular chip. You’ll also learn about various chip architectures like x86, x64. We’ll also discuss about the various chip manufacturers such as Intel, AMD, ARM, MIPS and where these are used.

Next, we’ll understand the x64 and x86 assembly. X86 is the most common architecture and we’ll discuss this in some detail as most malware is written in it. X86 is known as a complex syntax instruction set and has many functions. As an aspiring assembly coder or someone trying to read/understand assembly, you’ll need programming knowledge like functions, local variables, and application programming interface (API’s) and some math know-how like binary, and decimal (and how to convert them). We then move on to demonstrating compilers like GCC C, Cygwin; debuggers like IDA Pro, OllyDbg 2.0, and finally Visual Studio. ]

what is Assebmly : Human readable machine code for a particular chip.

Examples of some architectures:
           AMD x64 - Common in PC also known as 'x64' or '64-bit'
   ARM - Common in phones and tablets
   MIPS - Common in Printers

Most common architecture found in the world is x86. Most malwares written in x86 assembly. (For malware execution compactability also matters).

 x86 Assembly
Risk and sys instruction set

> 14 instructions make up 90% of code.  you can see these instruction set while reading the cde.

  1. MoV
4. CMP
5. ADD
6. POP
7. LEA
9. JE
10. XOR
11. JMP
12. JNE
13. RET
14. INC

When you reading the assembly 2 different ways you can read the x86. One with Intel syntax and other with AT&T syntax.

> Syntax
       > Intel
   > AT&T

  check how to read the intel and AT&T registers.

    A windows executable walkthrough
A windows executable has the following details,

simple.exe  - Header   > DOS header
   > PE header
   > optional header
   > data directories
   > section table

            - sections > code
           > imports
   > data

 PE file (Portable Executables)format
------ ------- -------- ----- --------- ------
Most modern windows executables use the below 'PE' format. 
We can move a .exe file to any of the below format and able to execute it as a .exe file do.

 > .exe
 > .dll
 > .src   screen saver files
 > .cpl
 > .ocx
 > .sys
 > .drv
 > .efi
 > .fon

 [ Compilers create raw executable files that are included in a container called the PE (Portable Executable) files. Windows uses PE files to know which instruction to begin executing, what libraries, or other metadata it would need. ]

 [ various PE file parsers like PE Explorer, COFF explorer, PEiD, PE Studio, 010 Hexaeditor with the PE binary templates. To make your own PE files, refer to the Malware Analysis Cookbook. Next, we’ll discuss the kind of files that use PE.
Some malwares may use any of the PE file formats like .exe, .dll, .src, .cpl, .ocx, .sys, .drv, .efi, .fon. ]

Why static analysis is important : This is inorder to
            > Understand the Malware
   > Discover IOC's
   > Confirm Dynamic Analysis
   > Discover Anti-Debugging Code

Some of the Tricks used by the malware :
> Stack Corruption
> Import Hiding using DFR
            > Dynamic Function Resolving
> String Obfuscation

You’ll learn both the easy as well as the hard way for string obfuscation. The hard way includes fully reverse engineering the code, re-implementing it, and then applying the same process to the strings. While the easy way uses the native code and executes it.

We’ll demonstrate a hybrid method, combining both static as well as dynamic analysis for de-obfuscation of strings.

    Enumerating malware capabilities

 Find command processing subroutine
 Configuration processing subroutine
 Document everything
 Test afterwards via dynamic analysis

  Module 6 : Packers
   > Self decrypting executables
   > Originally made for compressing code size
   > Use tools such as
        > Debuggers
> Memory Dumpers

   > Characteristics If malware if it is packer the below characters will be there

   > Packer strings/advertisements : we can check for this to verify whether 
the malware is packed or not.

Few strings
Few imports :
High entropy data
Large virtual section with small raw disk size

    > Goals:
        > Hide strings
        > Change the hash
        > mask binary signatures

 Legitimate users use Packers for the following:

   > Code Compression
> Intellectual Property Protection
> Anti-Reverse Engineering
> Anti-Cheat
> Digital Rights Management (DRM)
      > Product Licensing : If you reverse engineering this product you can come to
know how the license keys work. But it is illegal

 Common Packers:

    > UPX
 > Armadillo
 > ASPack
 > VMProtect
 > Themida
            > Packers ---> Bundlers ---> Virtualisers ---> compressors

--------------> check how to pack a malware or virus.

After Packing following changes may come :

    > Before packing:
                            > illusion bot strings
  > illusion bot AV detections
  > illusion bot PE sections

> After Packing:
               > No strings
            > Fewer AV Detections : Check in virustotal or something after packing the malware
  > Different PE sections
> PEiD:
                 PEiD detects most common packers, cryptors and compilers for PE files.

  Try packer on top of a packer.

  use to analyse a file/executable.

 use UPX to pack an executable.

   compare the following:
Strings between a packed and non-packed code.
Anti Virus (AV) detections in the code.
Different PE sections in the code.

You’ll also learn about the, which is a meta-anti virus scanning portal.
 We’ll also explain how to view PEiDs in a code.

  > UPX packed Regshot
          > strings
        > PEiD

  > Pack Regshot (run)
        > strings after

>PEiD --> deep.Data base from SANS

  > Unpack Regshot "upx -d packageName"
        > OllyDbg 1.10 (OllyDBG 2 will auto unpack)
        > Find OEP

  > Dump
        > OllyDump or
        > OllyDbg PE Dumper 3.03 or
        > LordPE

  > Reconstruct IAT
         > ImpREC 1.7e

> Malware Analyst's cookbook

> Practical Malware Analysis

  Module 7Malware Defense

> Anti-Debugging
   > API
  > Process and thread
  > Hardware and Register Based
  > Exception Based
  > Modified Code Based
  > Timing Based

> Anti-Virtual Machine
   > API
  > Memory Constants
  > File/Process Names

> Anti-Disassembly
   > Tricky Assembly
  > Dynamic Code generation/Calling

> Anti-Analysis Tools

Malware Goals:
   > Stop automated analysis

No comments:

Post a Comment