A challenge for all the C experts out there: On a linux machine, you have an already compiled C program, and y开发者_如何学运维ou are given its source code:
...
char buffer[20];
int code;
gets(buffer);
if(code==1234) ...
...
...
if(0) func();
You don't posses root privileges and the program is read-only. Find a way to execute func. I am certain this is possible, so please don't post any "It isn't possible" answers. Good luck!
The answer lies in the unchecked buffer overflow that is waiting to happen with gets(buffer);
and an understanding of what the stack looks like.
You could try setting the return address to the func()
call by overflowing buffer
.
http://en.wikipedia.org/wiki/Stack_buffer_overflow#Exploiting_stack_buffer_overflows
It may or may not be possible. If there are no other references to func(), the compiler may well have decided not to generate code for it in the first place -- dead code can be optimized away entirely.
This question is pretty underspecified, anyway. What do you mean by "the program is read-only"? The source code, or the executable? Are we attacking it from inside the process at runtime, inside the process by changing the source code, outside the process by trying to invoke it in funny ways, ...?
If the compiler generated code for the function (i.e. it didn't get chopped by the dead code optimizer) and you have a debugger and debug symbols, just attach a debugger and tell it to find and invoke func().
If you want to exploit the code at runtime, you can cause a buffer overflow in gets(), and take control of the process from inside, but you still have to find func() so you can jump to it -- having the source code won't help you here, and nothing will help you here if the compiler didn't generate code for it.
Since we have the source code, I would make the following edit and recompile:
-if(0) func();
+func();
Serious answer, there are thousands of ways of doing it (hacked environments, buffer overflows, etc), but the common pitfall is that a good compiler should optimize if (0) {}
away. If that is the case there would be no way of executing func()
. If not, then I would just start up my trusty debugger and jumping to the right spot.
Obviously, execute the famous set 0=1
command before running your executable.
But seriously, this is way off-topic...
精彩评论