I am trying to write on the code section of a running process. The code is below:
Code:
#include <sys/mman.h>
#include <limits.h>
#ifndef PAGESIZE
#define PAGESIZE 4096
#endif
unsigned char buffer[1024];
int blank();
int main()
{
unsigned long *p;
unsigned char c;
unsigned long *d;
int i;
p = ␣
d = (unsigned long *)(((int) p + PAGESIZE-1) & ~(PAGESIZE-1));
if (mprotect(d,4096,PROT_WRITE))
{
perror("Could not mprotect");
exit(errno);
}
printf("\naddress contained in p %x add cotained in d %x address of blank %x", p, d, blank);
printf("\n address of d[0] %x, address of d[1] %x",d, (d+1));
printf("\n address of d[0] %x, address of d [-1] %x d[-2] %x",d, d-1, (d-2));
p[1] = 0x89;
return 0;
}
int blank()
{
int index=0;
int i;
unsigned char *p;
p = &main;
printf("here");
for (i=0;i<=203;i++)
buffer[index++] = p[i];
buffer[index]='\0';
return 0;
}
The program prints
p = 8048536, d = 8049000, blank = 8048536, d[0] =8049000, d[1] = 8049004
So what is happening is that 'd' (the write enabled page) is getting aligned to 1 page after 'p'. So when I try to do a write on p[1], it segment faults. Can someone help me on how to align d such that 'p' becomes write enabled?
any help is appreciated
Thanks