Search code examples
csegmentation-faultmemcpy

Handling memcpy segfaults when passed with invalid inputs in an attack scenario


I am testing a small issue with a daemon here (written in linux). I want to know whether what is done is right or not.

The daemon loads a shared object file (.so) using dlopen call. The the shared object receives some buffers from clients over the network. It uses the following call to read the buffer:

read_buffer(something, length of buffer read, buffer contents);

The read_buffer function copies the buffer of length specified in the second parameter, to another location using memcpy

On the client side, the following is done:

write_buffer(something, length of buffer, buffer contents);

The problem is that if we send an invalid length parameter (not matching the real length of what is copied in the third parameter), from the client side, there is a segfault in the server side in the memcpy location

I am not sure how to input-validate the parameters that are passed to memcpy function

Request you to please help me out understand what is possible solution


Solution

  • You can append the length of the buffer at the start of the buffer.
    -------------------------------------------------------------
    | FIXED LENGTH OF BUFFER - n bytes | BUFFER
    -------------------------------------------------------------

    Now each time you read it on the server side, first read "n" bytes(reserved for storing the length) which contain the length. When the data arrives, you can compare length of buffer and first n bytes for validation. Hope this helps.