Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a checksum of the current stack

Tags:

c

stack

checksum

I would like to make a checksum of the current stack in the main, in order to check if it has been altered between two points.

For example:

int main(void) {
    ...
    stack_checksum();

    ... process ...

    if(stack_checksum() != ...)
        altered.
}

How can I grab the base stack address and the current address of the stack's top ?

EDIT: With @Miroslav Bajtoš help, step for approach:

  • Put local variable in a structure
  • Check backtrace return array
like image 781
Maxux Avatar asked Jan 13 '13 17:01

Maxux


2 Answers

It depends on which compiler/implementation of standard library you are using.

For gcc (or any other compiler that uses glibc), you can use backtrace() functions in execinfo.h - see these answers for more details: How to generate a stacktrace when my gcc C++ app crashes and How to get more detailed backtrace

For Microsoft compiler, you can use StackWalk64() function, see this article for more details: Walking-the-callstack. There was also a similar quesion asked here on StackOverflow: StackWalk64 on Windows - Get symbol name

Computing checksum should be easy once you can walk the stack.

like image 73
Miroslav Bajtoš Avatar answered Oct 24 '22 03:10

Miroslav Bajtoš


I think you will have to use inline assembly for this. The following code stores the current values of the base pointer and the current pointer in base and current. It's for gcc on a 64-bit machine:

// make these variables global (if not, the stack registers would change)
void *base, *current;
__asm__("movq %%rbp, %0;"
        "movq %%rsp, %1;"
        : "=r"(base), "=r"(current)
        :
        :
);

If you are on a 32-bit machine you have to use ebp and esp instead of rbp and rsp and movl instead of movq.
I recommend you to check out this inline assembly tutorial for gcc if you have any questions with the syntax.

like image 3
qwertz Avatar answered Oct 24 '22 05:10

qwertz