CryptedHelloWorld: App with encrypted mach-o sections

Posted: July 23rd, 2016 | Author: | Filed under: crypto, macOS, Programming | Tags: , , , , , , , | No Comments »

 
In a previous post ( constructor and destructor attributes ), I described the constructor attribute and mentioned software protection as a possible use case:

A constructor attribute could be used to implement a software protection. You could encrypt your executable with a custom encryption and use a constructor function to decrypt the binary just before it is loaded.

In this post I describe such a protection with an example.

 
 
Mach-O file format

Let’s start with a brief summary of the Mach-O file format. For more information you should definitively read the OS X ABI Mach-O File Format Reference.

A Mach-O file contains 3 regions:

  • header structure: describes the Mach-O file
  • load commands: describes the segments and their sections
  • actual segment data

 
Here is the figure from the OS X ABI Mach-O File Format Reference:


Mach-O file format basic structure

The goal is to encrypt the data of the __text section from the __TEXT segment. This is the section containing the code of the executable. The other sections and segments will be left untouched.

 
 
The target application: CryptedHelloWorld

The target application is called ‘CryptedHelloWorld’. Its (__TEXT, __text) section is encrypted, meaning that the main() function needs to be decrypted before running. When launched, a constructor function will decrypt the encrypted section and the decrypted main() will be called.

The application itself is a simple command line ‘Hello World’ written in C. Here is the source code of the main function:


int main(int argc, const char * argv[])
{
	printf("\n\n");
	printf("------------------\n");
	printf("Hello, World!\n");
	printf("------------------\n");
	printf("\n\n");
	
    return 0;
}

 
 
CryptoTool

When building the project with Xcode, the target dependency ‘CryptoTool’ is built. At the end of the compilation of the CryptedHelloWorld app, a Run Script phase is executed which runs ‘CryptoTool’ on the just compiled CryptedHelloWorld binary. ‘CryptoTool’:

  • reads the binary of the CryptedHelloWorld application from the disk
  • locates the (__TEXT, __text) section in the file
  • encrypts it using AES 128
  • replaces the bytes with the encrypted bytes in the binary on the disk.

 
The Run Script phase is straightforward:


Run Script phase

 
 
Location of the constructor function

When you launch the application, the constructor function will be triggered and will need to decrypt the (__TEXT, __text) section. Obviously this constructor function can’t be located in the (__TEXT, __text) section. I store it in a custom (__TEXT,__timac) section using the attribute __attribute__((section(“__TEXT,__timac”))):

void __attribute__((constructor)) __attribute__((section("__TEXT,__timac"))) decryptTextSection()

 
 
Self contained constructor function

We need to make sure that the constructor function doesn’t call any functions that are located in the (__TEXT, __text) section. To ensure that I made all the required functions inlined. For example:

static inline void __attribute__((always_inline)) EncryptDecryptMachoFile(struct mach_header_64 *machHeader, CCOperation operation)

The attribute __attribute__((always_inline)) ensures that the function is inlined even for debug builds when optimizations are turned off.

 
 
Locating the (__TEXT, __text) section

The constructor function uses the _dyld_get_image_header() dyld function to get the Mach-O header. It then loops though all the commands and all the sections of the LC_SEGMENT_64 segments to find the (__TEXT, __text) section:

static inline void __attribute__((always_inline)) EncryptDecryptMachoFile(struct mach_header_64 *machHeader, CCOperation operation)
{
	size_t segmentOffset = sizeof(struct mach_header_64);
	
	// For each load command of the mach-o file
	for (uint32_t i = 0; i < machHeader->ncmds; i++)
	{
		struct load_command *loadCommand = (struct load_command *)((uint8_t *) machHeader + segmentOffset);
		if(loadCommand->cmd == LC_SEGMENT_64)
		{
			// We found a 64-bit segment
			struct segment_command_64 *segCommand = (struct segment_command_64 *) loadCommand;
			
			// For each section in the 64-bit segment
			void *sectionPtr = (void *)(segCommand + 1);
			for (uint32_t nsect = 0; nsect < segCommand->nsects; ++nsect)
			{
				struct section_64 *section = (struct section_64 *)sectionPtr;
				fprintf(stderr, "Found the section (%s, %s)\n", section->segname, section->sectname);
				
				// Check if this is the __TEXT segment
				if (strncmp(segCommand->segname, SEG_TEXT, 16) == 0)
				{
					// Check if this is the __text section
					if (strncmp(section->sectname, SECT_TEXT, 16) == 0)
					{
						// This is the (__TEXT, __text) section.
						// We should encrypt/decrypt it in place.
						fprintf(stderr, "%s the (%s, %s) section\n", (operation == kCCEncrypt) ? "Encrypting" : "Decrypting", section->segname, section->sectname);
						EncryptDecryptBuffer((uint8_t *) machHeader + section->offset, (uint8_t *) machHeader + section->offset, section->size, operation);
						
					}
				}
				
				sectionPtr += sizeof(struct section_64);
			}
		}
		
		segmentOffset += loadCommand->cmdsize;
	}
}

 
 
Encryption

The section is encrypted using AES 128 by chunks of PAGE_SIZE bytes (4096 bytes). If there are less than PAGE_SIZE bytes to encrypt, chunks of 16 bytes are used. I use the CommonCrypto implementation of AES 128:

static inline void __attribute__((always_inline)) EncryptDecryptBytes(const void *srcBuffer, void *dstBuffer, uint64_t len, CCOperation operation)
{
	// Encrypt/decrypt the data from the source buffer using the AES key
	size_t outLength = 0;
	CCCryptorStatus result = CCCrypt(operation,
                   kCCAlgorithmAES128,
                   kCCOptionPKCS7Padding,
                   sAesKey,
                   kCCKeySizeAES128,
                   NULL,
                   srcBuffer,
                   len,
                   sEncryptionBuffer,
                   len + kCCBlockSizeAES128,
                   &outLength);
	
	if (result == kCCSuccess)
	{
		// Copy the encrypted/decrypted data into the destination buffer
		memcpy(dstBuffer, sEncryptionBuffer, len);
	}
	else
	{
		fprintf(stderr, "Error %d: Could not %s the data\n", result, (operation == kCCEncrypt) ? "encrypt" : "decrypt");
		exit(1);
	}
}

 
 
Virtual memory protections

The __TEXT segment is not writable by default. In order to decrypt the memory in place, the virtual memory protections need to be changed to allow writes. This is done using vm_protect:


static inline void __attribute__((always_inline)) ChangeVirtualMemoryProtections(vm_address_t addr, vm_size_t size)
{
	kern_return_t returnValue = vm_protect(mach_task_self(), addr, size, false, VM_PROT_ALL);
	if ( returnValue != KERN_SUCCESS )
	{
		fprintf(stderr, "Error %d: Fail to change virtual memory protections\n", returnValue);
		exit(1);
	}
}

 
 
Testing the compiled application

Here is the log output when launching the binary using the Terminal:

*** Constructor called to decrypt sections
Found the section (__TEXT, __text)
Decrypting the (__TEXT, __text) section
Found the section (__TEXT, __stubs)
Found the section (__TEXT, __stub_helper)
Found the section (__TEXT, __timac)
Found the section (__TEXT, __cstring)
Found the section (__TEXT, __unwind_info)
Found the section (__DATA, __nl_symbol_ptr)
Found the section (__DATA, __got)
Found the section (__DATA, __la_symbol_ptr)
Found the section (__DATA, __mod_init_func)
Found the section (__DATA, __data)
Found the section (__DATA, __bss)
*** The sections should now be decrypted. main() will be called soon.

——————
Hello, World!
——————

 
 
Examining the compiled application

 
Using MachOView, we see that the (__TEXT, __text) section is encrypted:


Section __text

 
This is confirmed with Hopper. The main() function doesn’t make any sense:


Hopper

 
Back to MachOView, we see that the (__TEXT, __timac) section contains unencrypted code:


Section __timac

 
 
Limitations of this proof of concept

As mentioned this example is a proof of concept and has several limitations:

  • it only supports 64-bit Mach-O files. Adding 32-bit and fat Mach-O support is fairly simple and left to the reader.
  • only the (__TEXT, __text) section is encrypted. It is possible to encrypt other sections or maybe even the whole __TEXT segment.
  • the target application is a really simple command line application written in C.
  • As mentioned earlier all the functions required in the constructor function have been made inlined. This makes it difficult to debug. If you want to debug this code I recommend to debug the CryptoTool app. It supports the parameters -decrypt and -encrypt. You should also remove the always_inline attribute otherwise breakpoints won’t fire as you would expect.

 
 
Should you use such code to protect your application?

I wouldn’t. Although this might prevent a user to look at the code, this won’t defeat an experienced attacker. Also note that this is a proof of concept.

 
 
Downloads

You can download the precompiled CryptedHelloWorld command line tool here.

The whole source code is available here.


constructor and destructor attributes

Posted: July 16th, 2016 | Author: | Filed under: code injection, Debugging, macOS, Programming | Tags: , , , , , , | 3 Comments »

GCC (and Clang) supports constructor and destructor attributes:

__attribute__((constructor))
__attribute__((destructor))

 
 
Description

A function marked with the __attribute__((constructor)) attribute will be called automatically before your main() function is called. Similarly a function marked with the __attribute__((destructor)) attribute will be called automatically after your main() function returns.

You can find the GCC documentation here:

constructor
destructor
The constructor attribute causes the function to be called automatically before execution enters main (). Similarly, the destructor attribute causes the function to be called automatically after main () has completed or exit () has been called. Functions with these attributes are useful for initializing data that will be used implicitly during the execution of the program.
These attributes are not currently implemented for Objective C.

Note: The GCC documentation tells that these attributes are not implemented for Objective-C. However this seems to work as expected with my tests using Clang ‘clang-703.0.31’ from Xcode 7.3.1.

 
 
Example

Here is an example of C code to demonstrate these attributes:


//
// To compile:
// clang -o constructor constructor.c
//

#include <stdio.h>
 
void constructor() __attribute__((constructor));
void destructor() __attribute__((destructor));

int main()
{
	printf ("main called\n");
	return 0;
}

void constructor()
{
	printf ("constructor called\n");
}

void destructor()
{
	printf ("destructor called\n");
}

When running this application, you will see the following output logs as you would expect:

constructor called
main called
destructor called

 
 
How does it work under the hood?

When you mark functions with these attributes, the compiler will create in your binary the sections called __mod_init_func for the constructors and __mod_term_func for the destructors. These sections contain the list of function pointers. You can use the excellent MachOView to see these sections:


ACTION

When your application is launched, dyld will call the constructors before your main() function is called. This is handled by the following dyld function:

void ImageLoaderMachO::doModInitFunctions(const LinkContext& context)

The destructors are handled by the dyld function:

void ImageLoaderMachO::doTermination(const LinkContext& context)

Since dyld is open source you can look at the implementation in the file ImageLoaderMachO.cpp of dyld. The source code for macOS 10.11.4 is available here.

 
 
Example of use

  • The first obvious usage is to be able to initialize some global variables with a constructor and do some cleanup with a destructor. It could be used to initialize some libraries too.
  •  

  • Another usage is code injection. In a previous post ‘Simple code injection using DYLD_INSERT_LIBRARIES’ I wrote code to replace some methods with an Objective-C +(void)load class method. Using a constructor would allow to inject code earlier in the process.
  •  

  • A constructor attribute could be used to implement a software protection. You could encrypt your executable with a custom encryption and use a constructor function to decrypt the binary just before it is loaded.