Code segment encryption
Implementation of "Rootkit Arsenal" cryptor.
2 March 2014 19:43 3 messages
License : Copyright Emeric Nasi, some rights reserved
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
I. Introduction.
In the Bill Blundens’ "The Rootkit ARSENAL" Edition 1 book, Mr Blunden describes how malware can evade detection and slow down reverse engineering by using code armoring. I implemented Bills’ cryptor and completed it to add patching of target program.
This article presents the modifications I made to the original code and the different tests I did on segment encryption.
It is not necessary to have the "Rootkit Arsenal" book to understand this article but the functions I did not modify are not in this article and if you need the full source code you can ask me by email or may also want to buy this excellent book:-).
II. Theory
II.1 Memory segmentation
An executable file, and its virtual memory image are made up of several sections. Some of this sections are represented by memory segments. Some segments are used to store data and others to store executable machine code. In this article we present how a program can encrypt one of the segment of another application and how this application can self decrypt its encrypted segment at runtime.
Here is the classical segmentation of a Windows portable executable binary file.
Other segment can appear in your files but these are the most important ones. PE headers is complex and I recommend you find some information about it. In this article we use the PE optional header which contains information about the application segments.
The .textbss segment is empty on the binary file. It is used to reserve room in virtual memory for non initialized global variables
The .text segment contains the executable code of the program
The .rdata segment contains read-only data. It is used to global constants (which includes strings). For example in printf("hello");
"hello" goes in .rdata.
The .data segment contains initialized global variables which are not constants. for example this global variable char var[] = "var";
is not a constant string, it is an array and goes in .data.
The .rsrc segment is present if you include resources to your file (*.rc files). Resources file can be used to provide information such as company name and application version.
When the executable is loaded in memory, the stack and heap segment are initialized to store local variables and dynamic allocated value. A part from this the segment layout will not change that much as you can see
II.2 Mechanism
What we want to do is modify an application (the target) in such a way that another application (the cryptor) can encrypt one of its segment. We also want the target application to decrypt itself at runtime.
Following the "Rootkit arsenal" book, we are going to create new segments in the target.
- a .code segment that will be encrypted.
- a .stub segment that is used to decrypt .code segment
In his book Bill Blunden merged the .text and .data segment into .code before encrypting it. There are a lot of other ways to do it. You can merge everything into one segment. You may want to have .text and .code separated so you don’t encrypt all your executable code. you can also create your own data segment and merge it to .code so that you don’t have to encrypt all the application initialiazed global variables and just hide the data you want.
In this article we are going to create a .code segment that will contain the executable code we want to cipher. To make it simple we are not going to merge another segment to it.
Here is the segment layout we will have in this example
II.3 Tools
Here are the tools you need:
- a C source code editor
- a C compiler/linker
- a debugger
- dumpbin.exe tool
- a hex editor
Personally I used Microsoft Visual Studio express 2010 which is free and provides the source code editor, the compiler, the linker, the debugger (with a very practical code machine view), and dumpbin.exe is provided by the Visual Studio shell.
I recommend next to Visual Studio you open the Visual studio CMD shell (can be found in startup/program menus). You can easily get PE file segments information and verify your values are ok using:
c:\test>dumpbin /HEADERS file.exe
Example of output:
For the hex editor I used the free edition of Cygnus Hex Editor.
III. Adapt target software
III.1 Create .code segment
It is very simple to create a new segment using #pragma section
.
You can then specify in which segment your information goes. There are 4 types of information in segments: executable code (pushed with #pragma code_seg
), initialized data (pushed with #pragma data_seg
), uninitialized data (pushed with #pragma bss_seg
) and constant variables (pushed with #pragma const_seg
).
Remember that a code segment will not store global variables or strings.
In out example, we want to put executable code of a C file in .code segment.
/* Your system includes */ #include <windows.h> /* Declare .code as a read/write/execute segment */ #pragma section(".code",execute, read, write) #pragma comment(linker,"/SECTION:.code,ERW") /* .code segment begin (all generated executable code below will go in .code segment ) */ #pragma code_seg(".code")
III.2 Create decryption stub
Why do we need a .stub segment since we do not encrypt all the code? Well we need the cryptor to be able to patch the target self-decryption routines and the code we want to patch will be easier to locate in the .stub section. Also variants of this article can be used to merge all segments into one (.code). So having .stub section is more generic.
// .stub SECTION #pragma section(".stub", execute, read, write) #pragma code_seg(".stub") #define CODE_BASE_ADDRESS 0x15151515 // dumpbin file pointer to raw data (do not change, this will be patched by cryptor) #define CODE_SIZE 0x14141414 // dumpbin size of Virtual memory (do not change, this will be patched by cryptor) /* Decrypt .code block encrypted by cryptor */ /* In this function do not declare array to avoid security cookies checks (see http://msdn.microsoft.com/en-us/library/8dbf701c.aspx) */ /* Or disable security check (GS- option) on prog compilation */ void decryptCodeSection() { unsigned char *ptr; long int i; long int nbytes; int cpt = 0; BYTE key[] = { '1','2','3','4','5','6','7','8','\0'};/* Note: Avoid strings if you plan to encryt .rdata segment */ int keyLength = 8; ptr = (unsigned char *)CODE_BASE_ADDRESS;/* This will be patched by cryptor*/ nbytes = CODE_SIZE;/* This will be patched by cryptor*/ // decrypt code segment for( i = 0 ; i < nbytes ; i++ ) { ptr[i]=ptr[i]^key[cpt]; cpt = cpt + 1; if(cpt == keyLength) cpt = 0; } return; } /* Program first entry function */ int main() { decryptCodeSection(); realmain(); /* Call decrypted program entry point */ return 0; }
III.4 Compilation and link options
Because the target will self-modify itself, we must avoid security cookies (used for stack verification). For that we need to remove security check. The next compilation options are thus mandatory:
/GS- -> Disable functions stack verification relying on secure cookies
Another option is almost mandatory, statically include the Runtime Library. If the Microsoft Runtime Library is not included in the target, this code will work but you will face portability issues.
Use one of the next two Runtime Library options.
/MTD -> for debug
/MT -> for release
To avoid complications we want to have fix address and remove data execution prevention. For that we have to use the next options for linker.
/DYNAMICBASE:NO
/FIXED
/NXCOMPAT:NO
You may also be interested into removing debugging informations but it is not mandatory for this code to work (and very useful to debug when it doesn’t work!).
III.5 Other possibilities
Other segments layouts are possible, and will be described in future articles.
For example, you can encrypt data and constant in your code by creating a custom data segment.
// create a data segment #pragma section(".codedata", read, write) // create the code section (to be decrypted) #pragma section(".code",execute, read, write) // Merge .codedata into .code (which will be encrypted by cryptor) #pragma comment(linker,"/MERGE:.codedata=.code")
Another possibility is to merge .text, .data, .rdata segments into .code which results in the next memory layout:
Note that in this case, the runtime library is encrypted. That means you need to declare a new entry point for the target, example:
// .stub SECTION #pragma section(".stub", execute, read, write) #pragma comment(linker,"/entry:\"ProgEntry\"") // new entry point #pragma code_seg(".stub") // decryption routine /* Entry point function*/ int ProgEntry() { decryptCodeSection(); mainCRTStartup(); /* Call runtime library entry point, which will then call main */ return 0; }
There is however a drawback to this method. Because of the strange PE header and the encryption of most of the file, some AntiVirus may consider the result of this method to be a malware.
IV. Build Cryptor
IV.1 Retrieve wanted information
The role of the cryptor is to encrypt the target programs’ .code segment as well as patching the.stub segment so that the target is able to self-decrypt when launched.
For that, the cryptor will browse through the binary file generated in the previous section and will find the address and size of .code and .stub segment. We need both file offset (to modify the binary target) and virtual memory address (to indicate to target program where is the segment he should decrypt at run-time).
First you need to map the file in memory using CreateFileMapping and MapViewOfFile. I did not do any functional modifications on this code. It can be found in the book or on the Internet.
Once this is done we parse the mapped file to fetch section headers informations.
/** * Get information of .code and .stub segments */ void getSegmentsInfo(LPVOID baseAddress, SEGMENT_INFO_PTR codeSegmentInfo,SEGMENT_INFO_PTR stubSegmentInfo) { PIMAGE_DOS_HEADER dosHeader; PIMAGE_NT_HEADERS peHeader; IMAGE_OPTIONAL_HEADER32 optionalHeader; dosHeader = (PIMAGE_DOS_HEADER)baseAddress; if(((*dosHeader).e_magic)!=IMAGE_DOS_SIGNATURE) { return; } peHeader = (PIMAGE_NT_HEADERS)((DWORD)baseAddress+(*dosHeader).e_lfanew); if(((*peHeader).Signature)!=IMAGE_NT_SIGNATURE) { return; } optionalHeader = (*peHeader).OptionalHeader; if((optionalHeader.Magic)!=0x10B) { return; } (*codeSegmentInfo).moduleBase = optionalHeader.ImageBase; (*stubSegmentInfo).moduleBase = optionalHeader.ImageBase; /* Fill code information with content of code segment */ TraverseSectionHeaders(IMAGE_FIRST_SECTION(peHeader),(*peHeader).FileHeader.NumberOfSections,codeSegmentInfo,".code"); TraverseSectionHeaders(IMAGE_FIRST_SECTION(peHeader),(*peHeader).FileHeader.NumberOfSections,stubSegmentInfo,".stub"); return; }
The next function is used get the next information for any section:
- The segment offset in raw file
- The file segment size
- The virtual memory offset of the segment
/** * Look for sectionName segment in mapped file * addrInfo will be filled with the segment information */ void TraverseSectionHeaders ( PIMAGE_SECTION_HEADER section, DWORD nSections, SEGMENT_INFO_PTR addrInfo, char * sectionName ) { DWORD i ; /* Copy pointer to initial section (so this function can be called several times) */ PIMAGE_SECTION_HEADER localSection = section; for(i=0;i<nSections;i++) { { (*addrInfo).fileSegmentOffset = (*section).PointerToRawData; /* Location of segment in binary file*/ (*addrInfo).fileSegmentSize = (*section).SizeOfRawData; /* Size of segment */ (*addrInfo).memorySegmentOffset = (*section).VirtualAddress; /* Offset of segment in memory at runtime */ } section = section+ 1; } return; }
IV.2 Encrypt target segment
Now that we have the size and location of .code segment in binary file, we can open the file and encrypt the wanted bytes.
This code is almost the same as provided by Blunden except the adaptation for the multiple bytes XOR encryption (witch is not much!). The code is not really optimized but very practical for debugging purpose. In this function we:
- Open the binary target file
- Seek .code segment
- Load .code segment in buffer
- Encrypt buffer
- Write encrypted buffer in place of clear-text .code segment
- Close file and leave
/** * Encrypt .code segment bytes in the given file */ void cipherBytes(char* fileName, SEGMENT_INFO_PTR addrInfo) { DWORD fileOffset; DWORD nbytes; FILE* fptr; BYTE *buffer; DWORD nItems; DWORD i; BYTE key[] = "ab345izz"; int keyLength = 8; int cpt = 0; fileOffset = addrInfo->fileSegmentOffset; nbytes = addrInfo->fileSegmentSize; /* Allocate memory in buffer that will store content of segment */ if(buffer == NULL) { return; } /* Open binary file */ if(fptr == NULL) { return; } /* Seek .code section using calculated offset and copy content into buffer*/ { return; } if(nItems <nbytes) { return; } /* Encrypt buffer */ for( i = 0 ; i < nbytes ; i++ ) { buffer[i]=buffer[i]^key[cpt]; cpt = cpt + 1; if(cpt == keyLength) cpt = 0; } /* Replace current .code section in file by encrypted one */ { return; } if(nItems <nbytes) { return; } return; }
IV.3 Patch target .stub section
After having encrypted the .code section, we need to patch the .stub section so that the target can decrypt itself. In this function we:
- Open the binary target file
- Seek .stub segment
- Load .stub segment in buffer
- locate CODE_BASE_ADDRESS and CODE_SIZE
- Replace values by virtual memory offset and size of .code section
- Write patched buffer in place of .stub segment
- Close file and leave
/** * Patch the filepath file (the .stub segment) * Here we replace CODE_BASE_ADDRESS and CODE_SIZE by newBaseAddr and newSegSize * newBaseAddr is the Virtual memory base address of .code segment in target file * newSegSize contains the size of the target file .code segment */ void patchStub(char * filepath, SEGMENT_INFO_PTR addrInfo, DWORD newBaseAddr, DWORD newSegSize ) { DWORD fileOffset; DWORD nbytes; DWORD nItems; /* Signature to locate where segment memory base address should be written */ BYTE baseAddrSignature[] = { 0x15, 0x15, 0x15, 0x15, 0x00 }; /* Signature to locate where segment size should be written*/ BYTE segSizeSignature[] = { 0x14, 0x14, 0x14, 0x14, 0x00 }; BYTE * baseAddrAddress = NULL; BYTE * segSizeAddress = NULL; BYTE *buffer; FILE* fptr; fileOffset = addrInfo->fileSegmentOffset; nbytes = addrInfo->fileSegmentSize; /* Allocate memory in buffer that will store content of segment */ if(buffer == NULL) { return; } /* Open binary file */ if(fptr == NULL) { return; } /* Seek .stub section using calculated offset*/ { return; } /* Copy content of stub segment into buffer */ if(nItems <nbytes) { return; } /* Search the baseAddress in buffer section */ baseAddrAddress = binStrstr(buffer,baseAddrSignature); /* Change base Address by calculated value */ /* Search the baseAddress in buffer section */ segSizeAddress = binStrstr(buffer,segSizeSignature); /* Change base Address by calculated value */ /* Replace current .stub section in file by patched one */ { return; } if(nItems <nbytes) { return; } return ; }
IV.4 Main function
/** * Cryptor entry point */ void main(int argc, char *argv[]) { char *fileName; HANDLE hFile; HANDLE hFileMapping; LPVOID fileBaseAddress; BOOL retVal; /* To store information of .code and .stub segments */ SEGMENT_INFO codeSegmentInfo; SEGMENT_INFO stubSegmentInfo; if(argc <2) { return; } fileName = argv[1]; /* Map target file */ retVal = getHMODULE(fileName, &hFile, &hFileMapping, &fileBaseAddress); if(retVal==FALSE) { return; } /* Init structures */ codeSegmentInfo.moduleBase = (DWORD)NULL; codeSegmentInfo.memorySegmentOffset = (DWORD)NULL; codeSegmentInfo.fileSegmentOffset = (DWORD)NULL; codeSegmentInfo.fileSegmentSize = (DWORD)NULL; stubSegmentInfo.moduleBase = (DWORD)NULL; stubSegmentInfo.memorySegmentOffset = (DWORD)NULL; stubSegmentInfo.fileSegmentOffset = (DWORD)NULL; stubSegmentInfo.fileSegmentSize = (DWORD)NULL; /* Fill segments information */ getSegmentsInfo(fileBaseAddress,&codeSegmentInfo,&stubSegmentInfo); closeHandles(hFile, hFileMapping,fileBaseAddress); cipherBytes(fileName,&codeSegmentInfo); patchStub(fileName,&stubSegmentInfo,codeSegmentInfo.moduleBase+codeSegmentInfo.memorySegmentOffset,codeSegmentInfo.fileSegmentSize); return; }
Also in this section
2 February 2022 – MSDT DLL Hijack UAC bypass
15 July 2021 – Hide HTA window for RedTeam
24 February 2019 – Bypass Windows Defender Attack Surface Reduction
23 January 2019 – Yet another sdclt UAC bypass
23 June 2018 – Advanced USB key phishing
3 Forum posts
Can we get all the code in pastebin ? or just create a "Download" button as the other write-ups that you wrote please.
what is SEGMENT_INFO_PTR definition?
In the code segment for stub at line 38, the realmain() function call is given. If we are generating the executable without code and have targets generated by metasploit etc how to we call the entry function ??
In this case I presume we are assuming that the code of payload is available with us. Please clarify!!