summaryrefslogtreecommitdiff
path: root/extract_decoded_executable/extractor.c
blob: 3a53536ea60f3baaaf8f6f47ef88f0ff6d0513c2 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

void extract_contained_binary(){
	double bin_hex_div = (double)strlen((const char*)BIN_HEX) / 2;
	if ( bin_hex_div == 0.5 ){
		fputs( "Error: binary hex is uneven number of characters\n", stderr );
		return;
	}
	size_t hex_byte_count = (size_t)bin_hex_div;
	unsigned char *decoded_bytes = (unsigned char*)calloc( hex_byte_count + 1, sizeof(unsigned char) );
	if ( decoded_bytes == NULL ){
		fprintf( stderr, "Error: failed to allocate memory for decoding: %s\n", strerror(errno) );
		return;
	}
	const char *bin_hex = (const char*)BIN_HEX;
	size_t byte_pos = 0;
	size_t dec_byte_pos = 0;
	char c_byte[2];
	memset( (void*)&c_byte, 0, sizeof(c_byte) );
	unsigned char decoded_byte = '\0';
	for ( ; dec_byte_pos < hex_byte_count; byte_pos += 2, dec_byte_pos++ ){
		memmove( (void*)&c_byte, (const void*)&bin_hex[byte_pos], 2 );
		decoded_byte = (unsigned char)strtoul( (const char*)&c_byte, NULL, 16 );
		if ( errno != 0 ){
			fprintf( stderr, "Error: failed to decode byte: %s\n", strerror(errno) );
			free( decoded_bytes );
			return;
		}
		decoded_bytes[dec_byte_pos] = decoded_byte;
	}
	int out_fd = open( "/tmp/test_output_binary", O_RDWR | O_CREAT, 0755 );
	if ( out_fd == -1 ){
		fprintf( stderr, "Error: failed to open /tmp/test_output_binary for writing: %s\n", strerror(errno) );
		free( decoded_bytes );
		return;
	}
	if ( write(out_fd, (const void*)decoded_bytes, hex_byte_count + 1) == -1 ){
		fprintf( stderr, "Error: failed to write /tmp/test_output_binary: %s\n", strerror(errno) );
		free( decoded_bytes );
		close( out_fd );
		return;
	}
	close( out_fd );
	free( decoded_bytes );
	fputs( "Binary extracted, check /tmp for test_output_binary\n", stdout );
	return;
}

int main( int argc, char *const *args ){
	extract_contained_binary();
	return 0;
}