Schuyler
Schuyler

Reputation: 529

C++ insert function pointer into memory

I am trying to overwrite a char and a function pointer on the stack. Based on what I found on this question (How can I store a value at a specific location in the memory?) I was able to figure out how to overwrite the character. My problem now is that I get a compile error saying I am casting it wrong.

void foo(char letter);
void bar(char letter);

void function1()
{
  void (*pointer)(char);
  pointer = foo;
  letter = 'B';
  function2();
  (*pointer)(letter);
}

void function2()
{
  int number; // Used in omitted code

  *(char *)(&number + 75) = 'A';
  *(void (*)(char)) (&number + 42) = &bar; // This is the line with the error
}

The first injection works but the second one gives me a compile error.

I am running Redhat Linux using a g++ compiler. The error I get from the compiler is:
"cannot convert ‘void (*)(char)’ to ‘void(char)’ in assignment"

If I change that line to *(void(char)) then the compiler says:
"invalid cast to function type ‘void(char)’"

What is the proper syntax for this?

(This is modified code from a school security assignment, I'm not writing malware)

Upvotes: 2

Views: 310

Answers (1)

Red Alert
Red Alert

Reputation: 3816

Your goal is to write the address of pass to memory, so why are you casting (&number + 13) to a function pointer? Just do what you did before:

*(long *)(&number + 13) = (long)&pass;

And you won't get a compiler error. As to what will happen when this undefined behavior is invoked, you'll just have to see.

Edit: As @DavidGrayson pointed out, if we deference the right side of the equation, we'd get the contents of the function, not its pointer. So we have to cast it to a POD type, not a pointer.

Upvotes: 1

Related Questions