I'm working on a C project, the goal is to reach a web server, read the data inside a file (example.com/shellcode.bin for example) and store it inside an array.
Currently, I managed to make the necessary GET requests, i can find my shellcode, insert it into an array (mycode) but when I return it, it sends me the wrong size.
For example, if sizeof(mycode) return 270, sizeof(PE) return 8.
Is it possible to find the total size of the PE variable ?
size_t size = sizeof(mycode);
char* PE = (char*)malloc(size);
for (int i = 0; i < sizeof(mycode); i ) {
PE[i] = mycode[i];
}
printf("Shellcode size before return : %ld\n", sizeof(PE));
return PE;
I tried different format string outputs (%s with strlen, %d, %ld, %zu ....) all of them returned 8.
CodePudding user response:
One solution is to return a struct containing both a pointer to the buffer and the length.
// outside the function
typedef struct {
char* data;
size_t size;
} Buffer;
// in the function
Buffer buffer;
buffer.data = PE;
buffer.size = size;
return buffer;
And also change the return type to Buffer
.
CodePudding user response:
A pointer points to a single object of the pointed-to type; given a pointer value, there's no way to know whether you're looking at the first object of a sequence or not. There's no metadata in the pointer saying "there are N
more elements following the thing I point to."
sizeof PE
gives you the size of the pointer variable, not the number of things in the buffer; sizeof PE == sizeof (char *)
. sizeof *PE
gives you the size of a single char
object, which is 1 by definition; sizeof *PE == sizeof (char)
.
You have to manually keep track of how much memory you allocated - you somehow have to persist that size
variable anywhere you intend to use PE
.
As others have pointed out, you can bundle that into a struct
type:
struct buffer {
size_t size;
char *PE;
};
struct buffer newBuf( const char *mycode, size_t size )
{
struct buffer b;
b.PE = calloc( size, sizeof *b.PE );
if ( b.PE )
{
memcpy( b.PE, mycode, size );
b.size = size;
}
return b;
}
int main( void )
{
char shellcode[] = { /* some char data here */ };
struct buffer b = newBuf( shellcode, sizeof shellcode );
...
}