Declare function with memory address - c++

I'm trying to call a function through its memory address.
I've done something like:
int GetNewValue(int args)
{
return args * 2;
}
int main()
{
/*
Function address: 0x22feac
*/
int(*GetVal)(int) = 0x22feac; // instead of '&GetNewValue'
}
But at compile time, i get the following error:
[Error] invalid conversion from int to int (*)(int) [-fpermissive]
How can I call a method from its address?
(Note the above example uses a constant for simplicity, but in my real code I am hooking a function from a DLL injection.)

The address 0x22feac looks like any address in normal code address space. But this depends on your environment. It is generally a bad idea to use an address specified by a number literal in your source code.
But there might be an address that you got from outside, such as from the Windows function GetProcAddress. If you are sure you really know what you are doing, then you can assign such a value to a function pointer:
intptr_t functionAddress = 0x22feac;
auto GetVal = reinterpret_cast<int(*)(int)>(functionAddress);
The auto allows you to follow the "Don't repeat yourself" pattern.

Related

what does (void(*)() sc) () mean?

unsigned char sc[] =
(some long binary string)
int main()
{
((void(*)())sc)();
return 0;
}
what does what does (void(*)() sc) () mean in here?
I saw " *void(*)() means a void function that takes no argument" in StackoverFlow.
`
I have three question
First,
As this comment above, I think above code has to "*" ahead of void(*).
However, without pointer "*" , it is working well.
Second, "void(*)() sc is wrapped by ()(), such like (void(*)() sc)().
there is twice use of "()"
Third, why is it working?? Common,When we call a function, we usually write only name of function, such as funtion1(a , b);
"(void(*)() sc )()" is just initialize!!
So i think sc is not used yet. However it is working well.
This is a trick to execute any shellcode inside your main.
Let's analyze it together shall we ? (The function declaration, not your shellcode):
(void(*)() sc ) ();
First lets talk about sc. sc is a byte array being assigned a shellcode, meaning that anything can happen (hence why it was rightfully edited).
Then it is converted into a function, a function ptr to be exact:
void(*)() sc
With void(*)() you simply cast your shellcode as a function pointer, meaning that if we call this function ptr, taking no argument as you noticed, it will point to the first byte of your unsigned char array. The compiler will interpret your char array as raw bytes to be converted into machine code.
NB: an unsigned char is a byte.
Finally the trailing (); ask the function, wrapped by parenthesis, to be executed, as soon as you start your program.
In short it is a convenient way to tell eip, the register that hold the address of program's next execution, to point at your byte array and easily test different shellcodes.
Note that, as mentioned by dxiv, this will not work in environment that prevent code execution from data area as your function ptr points to a data segment.
If you want to make it work you will need to compile with the following flags in order to enable exacstack -z execstack, and potentially -fno-stack-protector as well as -m32 if it is a shellcode for 32 bits:
gcc -m32 -fno-stack-protector -z execstack shellcode.c && ./a.out
Example to read /etc/passwd (linux):
unsigned char sc[] =
"\x31\xc9"
"\xf7"
"\xe1\xb0"
"\x05"
"\x51\x68"
"\x73\x73\x77"
"\x64"
"\x68"
"\x63"
"\x2f\x70\x61"
"\x68" "\x2f"
"\x2f\x65\x74"
"\x89" "\xe3"
"\xcd\x80\x93"
"\x91"
"\xb0"
"\x03\x31\xd2"
"\x66" "\xba"
"\xff\x0f\x42"
"\xcd""\x80"
"\x92" "\x31"
"\xc0\xb0\x04"
"\xb3" "\x01"
"\xcd" "\x80"
"\x93\xcd\x80";
int main()
{
((void(*)())sc)();
return 0;
}
Another example to open a shell:
#include <unistd.h>
unsigned char sc[] =
"\x31\xc0\x50\x68\x2f\x2f"
"\x73\x68\x68\x2f\x62\x69"
"\x6e\x89\xe3\x50\x53\x89"
"\xe1\xb0\x0b\xcd\x80";
int main()
{
((void(*)())sc)();
return 0;
}

Strcpy behavior with stack array c++

Here is my program :
#include <cstring>
const int SIZE =10;
int main()
{
char aName [SIZE]; // creates an array on the stack
std::strcpy(aName, "Mary");
return 0;
}
This program is obviously useless, I am just trying to understand the behavior of the strcpy function.
Here is it's signature :
char * strcpy ( char * destination, const char * source )
so when I do :
std::strcpy(aName, "Mary");
I am passing by value the variable aName. I know that the aName (in the main) contains the address of the array.
So is this assertion correct : strcpy creates a local variable called destination that has as value the address of the array aName that I have created on the stack in the main function?
I am asking this because it is very confusing to me. Whenever I have encountered addresses it usually was to point to a memory allocated on the heap...
Thanks!
Whenever you encounter addresses it doesn't mean it will always point to memory allocated to heap.
You can assign the address of a variable to a pointer like this
int a=5;
int *myPtr= &a;
Now, myPtr is a pointer of type integer which points to the memory of variable which is created on stack which is a have value 5.
So, whenever you create a pointer and assign the (address of) memory using new keyword, it will allocate the memory on heap. So, if I assign the value like this it will be on stack
int *myPtr= new int[5];
So is this assertion correct : strcpy creates a local variable called destination that has as value the address of the array aName that I have created on the stack in the main function?
Yes.
Whenever I have encountered addresses it usually was to point to a memory allocated on the heap...
Yep, usually. But not always.
Pointers to non-dynamically-allocated things are fairly rare in C++, though in C it's more common as that's the only way to have "out arguments" (C does not have references).
strcpy is a function from C's standard library.
Maybe it would help to look at an example implementation of strcpy():
char* strcpy(char* d, const char* s)
{
char* tmp = d;
while (*tmp++ = *s++)
;
return d;
}
That's really all there is to it. Copy characters from the source to the destination until the source character is null (including the null). Return the pointer to the beginning of the destination. Done.
Pointers point to memory. It doesn't matter if that memory is "stack", "heap" or "static".
Function parameters are its local variables.
In this call
std::strcpy(aName, "Mary");
the two arrays (one that is created in main with the automatic storage duration and other is the string literal that has the static storage duration) are implicitly converted to pointers to their first elements.
So you may imagine this call and the function definition the following way
std::strcpy(aName, "Mary");
// …
char * strcpy ( /* char * destination, const char * source */ )
{
char *destination = aName;
const char *source = "Mary";
// …
return destination;
}
Or even like
char *p_to_aName = &aName[0];
const char *p_to_literal = &"Mary"[0];
std::strcpy( p_to_aName, p_to_literal );
// …
char * strcpy ( /* char * destination, const char * source */ )
{
char *destination = p_to_aName;
const char *source = p_to_literal;
// …
return destination;
}
That is within the function its parameters are local variable of pointer types with the automatic storage duration that are initialized by pointers to first characters of the passed character arrays
So is this assertion correct : strcpy creates a local variable called destination that has as value the address of the array aName that I have created on the stack in the main function?
Yes. That is correct. Though I probably wouldn't call it a local variable. It is a parameter. Local variable usually means something like this:
int localVariable;
The word'parameter" is often associated with things like this:
int myFunction(int parameter) {
// use parameter some where...
}
The point is roughly the same though: it creates a variable that will go out of scope once the function exits.
I am asking this because it is very confusing to me. Whenever I have encountered addresses it usually was to point to a memory allocated on the heap...
Yes, this is the most common use case for them. But it isn't their only use. Pointers are addresses, and every variable has an address in memory regardless of whether it is allocated on the "heap" or "stack."
The use here probably because pointers to a char are commonly used to store strings, particularly on older compilers. That combined with the fact that arrays "decay" into pointers, it is probably easier to work with pointers. It is also certainly more backwards compatible to do it this way.
The function could have just as easily used an array, like this:
char * strcpy ( char destination[], const char source[ )
But I'm going to assume it is easier to work with pointers here instead (Note: I don't think you can return an array in C++, so I'm still using char *. However, even if you could, I would imagine it is still easier to work with pointers anyway, so I don't think it makes a lot of difference here.).
Another common use of pointers is using them as a way to sort of "pass by reference":
void foo(int * myX) {
*myX = 4;
}
int main() {
int x = 0;
foo(&x);
std::cout << x; // prints "4"
return 0;
}
However, in modern C++, actually passing by reference is preferred to this:
void foo(int & myX) {
myX = 4;
}
int main() {
int x = 0;
foo(x);
std::cout << x; // prints "4"
return 0;
}
But I bring it up as another example to help drive the point home: memory allocated on the heap isn't the only use of pointers, merely the most common one (though actually dynamically allocated memory has been mostly replaced in modern C++ by things like std::vector, but that is beside the point here).
I know that the aName (in the main) contains the address of the array.
You knew wrong. aName is an array. It contains the elements, not an address.
But when you use the name of the array as a value such as when passing it to strcpy, it is implicitly converted to a pointer to first element of the array (the value of a pointer is the memory address of the pointed object). Such implicit conversion is called decaying.
So is this assertion correct : strcpy creates a local variable called destination that has as value the address of the array aName that I have created on the stack in the main function?
This is correct enough. To clarify: It is a function argument rather than a local variable. But the distinction is not important here. Technically, it is the caller who is responsible for pushing the arguments onto the stack or storing them into registers, so it could be considered that main "creates" the variable.
Whenever I have encountered addresses it usually was to point to a memory allocated on the heap
Pointers are not uniquely associated with "heap". Pretty much any object can be pointed at, whether it has dynamic, static or automatic storage or even if it is a subobject.

Correct casting to function pointer that points to a function that returns a function

i was reversing a source code and i've found a function it wich looks like:
consider this:
int examplefn(int x) { return x * 4; }
int (*rtx())(int)
{
return examplefn;
}
well, Then i needed make a pointer function to rtx() to do a hook, then
i've done something like this:
int (*fncptr())(int) = (int(*())(int))0xC0FFEE;
/* 0xC0FFEE it's a sample of the memory address of the function...*/
But my compiler did not compile it, then i've tried do:
typedef int(*fnc_t())(int);
// Clearer example pointing to rtx
fnc_t* TRY_2 = (fnc_t*)&rtx;
// then has successfully compiled, ex test...
int main()
{
std::cout << TRY_2()(4) << std::endl; // output: 16 ok.
}
well, i'm going to the point, ¿How i can do the correct casting without use a typedef?
I searched all over the internet and I have not found anything...
Why do you want to avoid using a typedef? It makes code so much easier to understand:
using F = int(*)(int); // pointer to function taking int and returning int
using G = F(*)(); // pointer to function taking nothing and returning
// a pointer to function taking int and returning int
This took me no time to write and everybody else no time to read and understand. I'd call that a win.
(int(*())(int)) is a function type (the same type as the function rtx has). Your code attempts to declare a function, and cast an integer to function. However you actually want to deal with a pointer to such a function.
After: typedef int(*fnc_t())(int);, the equivalent of fnc_t *x; can be found by replacing fnc_t with (*x) in the typedef: int (*(*x)())(int). So your code could be:
int (*(*fncptr)())(int) = (int(*(*)())(int))0xC0FFEE;
Using a series of typedefs (or equivalent usings) is certainly preferable in real code.

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)
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.

What does DetourAttach(&(PVOID &)BindKeyT, BindKeyD); mean? Attaching a detour to a memory address

This is just a simple question. I've been reading the source of something which attaches to a memory address of a subroutine using DetourAttach(&(PVOID &)BindKeyT, BindKeyD); where BindKeyT is the address to a subroutine in memory. I'm curious, what exactly does (&(PVOID &) mean in english? I understand that PVOID is a void pointer, but how does this get translated into a function which can be used to attach a detour to?
Terry Mahaffey is right, what you are passing is a pointer to a pointer to the function. This is commonly used whenever the function you are passing the pointer to (in this case, DetourAttach) wants to return more than one value, and one of those returned values is a pointer. Since functions in C/C++ can only return a single value, the only way to obtain multiple values from them is via pointers.
A simple example would be when one wishes to return a pointer to a block of allocated memory. Then one can write a function like:
int allocstr(int len, char **retptr)
{
char *p = malloc(len + 1); /* +1 for \0 */
if(p == NULL)
return 0;
*retptr = p;
return 1;
}
To answer your other question, of how to setup a memory address to be used as a function, one can do it like so:
void* (void * BindKeyT)(const char* key) = actual_BindKeyT;
// actual_BindKeyT is a pointer to a function that will be defined elsewhere,
// and whose declaration you will include in your project through a header file
// or a dll import
void * BindKeyD(const char* key)
{
// Code for your hook function
}
DetourAttach(&(PVOID&)BindKeyT, BindKeyD);
(taken from http://zenersblog.blogspot.com/2008/04/api-hooking-with-detours-part-1.html)
Bear in mind that the declarations for BindKeyT and BindKeyD should match.
The C++ parser in my head (which is not bug free) says that it is a C style cast of BindKeyT to a reference to a pointer to void - the (PVOID&) part - and then taking the address of that - the & in front. So the result of the expression is a pointer to a pointer to the function.
There is an introduction to Detours here: api-hooking-with-detours-part-1