Google
 

Thursday, December 25, 2008

Null function pointer trick

Few days ago Ayush posted the following code to our class' mailing list. What does the following C code do??


unsigned char *virus;
virus = (char *)(((int) virus + PAGESIZE-1) & ~(PAGESIZE-1));
((void (*)())virus)();

Cracked me a while, but here's the explanation:

Line 1 is pointer to unsigned char, straight forward..

Line 2 looks a bit confusing but is a brilliant technique for 'ceiling'ing integers. This converts the address of virus to next multiple of PAGESIZE. The code is working with memory location, so I assume PAGESIZE is some power of 2. Suppose say if PAGESIZE is 1024, then for

*virus = 123 => 1024
*virus = 2000 => 2048
and so on..

Hope u got the point. Just some bit-arithmetic to change the location pointed by virus to next memory page (assuming PAGESIZE = size of one page)

Line 3 involves simple null function pointer. From line 2, variable virus contains location to start of a page (the page might contain virus code, written by some means like buffer overflow exploit ;)). Now (void (*)()) is null pointer to function. so the above code will execute the function at memory location pointed by virus with no arguments.

6 comments:

  1. wont work if ASLR is enabled ;)

    ReplyDelete
  2. hehe yeah, but that's why aslr was devised.. :)

    ReplyDelete
  3. Hey very interesting way to brief us regarding C code...this must be helpful for me in many ways...thanks a lot Jwalanta..keep it up

    research paper

    ReplyDelete
  4. Its so good to read this blog and receive the information for useful purpose. I am thanking a lot to this person. good luck for your future.

    ReplyDelete
  5. I have been trapped in C code issue for such a long time now until I finally managed to find your this sharing....this is really very handy solution!

    ReplyDelete
  6. surprising, but 5 yrs l8r this post solved a problem I was facing in attempting to do what was being quoted in an embedded environment. Thanks

    ReplyDelete