All pastes #2110549 Raw Edit

Unnamed

public text v1 · immutable
#2110549 ·published 2012-02-07 02:32 UTC
rendered paste body
void *malloc_exec(size_t sz) {
    long pagesize = sysconf(_SC_PAGE_SIZE);
    void *p;
    if (posix_memalign(&p, pagesize, sz) != 0) {
      printf ("oops: memalign failed!\n");
      exit (-1);
    }
    if (mprotect(p, sz, PROT_READ | PROT_WRITE | PROT_EXEC) != 0) {
    printf ("oops: mprotect failed!\n");
    exit (-1);
    }
    return p;
}
  
we_proc gen(char *s, int n) {
	
	int i = 0;
	int len = strlen(s);
	
	unsigned long address = (unsigned long) s;
	
	char *b;
	char *start;	// Holds the stabrting position of b
	
	b = malloc_exec(sizeof(16 + 24 * n));
	start = b;
	
	/* PROLOGUE */
	*b = 0x55; b++; 			// push %ebp
	*b = 0x89; b++; *b = 0xe5; b++;		// mov	%esp,%ebp
	*b = 0x53; b++;				// push %ebx
	
	/* BODY */
	for(i = 0; i < n; i++) {
		
		*b = 0xb8; b++; 				// -----------------
		*b = address & 0xff; b++;			// This block of
		address = address >> 8;				// code moves the 
		*b = address & 0xff; b++;			// address of the
		address = address >> 8;				// string to %eax
		*b = address & 0xff; b++;			//
		address = address >> 8;				// mov address,%eax
		*b = address & 0xff; b++;			// -----------------
		
		*b = 0x89; b++; *b = 0xc1; b++;		// mov %eax,%ecx
		
		*b = 0xba; b++;					// -----------------
		*b = len & 0xff; b++;				// This block of
		len = len >> 8;					// code puts the
		*b = len & 0xff; b++;				// length of the
		len = len >> 8;					// string into %edx
		*b = len & 0xff; b++;				//
		len = len >> 8;					// mov len,%edx
		*b = len & 0xff; b++;				// -----------------
		
		*b = 0xbb; b++; *b = 0x01; b++;		// --------------
		*b = 0x00; b++; *b = 0x00; b++;		// mov $0x1,%ebx
		*b = 0x00; b++;				// --------------
		
		*b = 0xb8; b++; *b = 0x04; b++;		// --------------
		*b = 0x00; b++; *b = 0x00; b++;		// mov $0x4,%eax
		*b = 0x00; b++;				// --------------
		
		*b = 0xcd; b++; *b = 0x80; b++;		// int $0x80
	}
	
	/* EPILOGUE */
	*b = 0xbb; b++; *b = 0x00; b++;		// --------------
	*b = 0x00; b++; *b = 0x00; b++;		// mov $0x0,%ebx
	*b = 0x00; b++;				// --------------
		
	*b = 0xb8; b++; *b = 0x01; b++;		// -------------- 
	*b = 0x00; b++; *b = 0x00; b++; 	// mov $0x1,%eax
	*b = 0x00; b++; 			// --------------
	
	*b = 0xcd; b++; *b = 0x80; b++;		// int $0x80
	
	//*b = 0x5b; b++;						// pop %ebx
	//*b = 0x5d; b++;						// pop %ebp
	//*b = 0xc3; b++;						// ret
	//*b = 0x90; b++;						// nop
	
	return (we_proc)start;
}

int main (int argc, char **argv) {
	
	we_proc a;
	a = gen("hello\n", 3);
	a();
	write(1, "oops\n", 5);
	return 0;  
}