Skip to content

Instantly share code, notes, and snippets.

@RobinDavid
Created February 18, 2017 23:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save RobinDavid/52d81f147d29e1fd22d54cd22df2e7b9 to your computer and use it in GitHub Desktop.
Save RobinDavid/52d81f147d29e1fd22d54cd22df2e7b9 to your computer and use it in GitHub Desktop.
PoC to checksum a given portion of the code
#define _GNU_SOURCE
#include <unistd.h>
#include <dlfcn.h>
#include <sys/mman.h>
#include <link.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
void *begin;
void *end;
int callback(struct dl_phdr_info *info, size_t size, void *data) {
if (info->dlpi_name && info->dlpi_name[0] != '\0')
return 0;
size_t page = sysconf(_SC_PAGESIZE);
int i;
for (i = 0; i < (size_t)info->dlpi_phnum; i++)
if ((info->dlpi_phdr[i].p_flags & PF_X)) {
size_t ptr = (size_t)info->dlpi_phdr[i].p_vaddr;
size_t len = (size_t)info->dlpi_phdr[i].p_memsz;
if (ptr % page) {
len += ptr % page;
ptr -= ptr % page;
}
if (len % page)
len += page - (len % page);
if (mprotect((void *)ptr, len, PROT_READ | PROT_WRITE | PROT_EXEC))
if (errno != ENOMEM)
return errno;
}
return 0;
}
int makeTextWritable() {
return dl_iterate_phdr(callback, NULL);
}
int test(int x, int nb, int dummy) {
if(dummy) {
begin = &&begin;
end = &&end;
return 0;
}
int r=1;
int i;
begin:
for (i=0;i<nb;i++)
r = r * x;
end:
return r;
}
int show_code() {
char* p=begin;
printf("Code:");
while (p<(char*) end) {
printf("%02hhx ",(char)*p);
p++;
}
printf("\n");
}
int hash_fun() {
const int HASH = 3801;
int sum = 0;
char* p=begin;
while (p<(char*) end) {
sum += (unsigned char)*p++;
}
printf("Sum:%d\n", sum);
return sum == HASH;
}
void cipher(char key) {
char* p=begin;
while (p<(char*) end) {
*p++ ^= key;
}
}
void main() {
//Demo Tamperproofing
test(0,0,1);
if(hash_fun())
printf("Hash OK !\n");
else
printf("Fail hash\n");
//-------------------
//Demo self-modification
makeTextWritable();
show_code();
cipher(99);
show_code();
if(hash_fun())
printf("Hash OK !\n");
else
printf("Fail hash\n");
test(0,0,0);
//----------------------
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment