Preventing char pointer overflow in struct

I have a function that accepts a struct * pointer containing sensitive data (in a char array) as an argument (sort of a small library). The two struct models are as follows:

struct struct1 {
    char str[1024]; /* maybe even 4096 or 10KB+ */
    size_t str_length;
}

struct struct2 {
    char *str;
    size_t str_length;
}

The test function is:

/* Read str_length bytes from the char array. */
void foo(struct struct1/struct2 *s) {
    int i;
    for (i = 0; i < s->str_length; i++) {
        printf("%c\n", s->str[i]);
    }
}

My concern is that, since the str_length parameter is an arbitrary value, one could intentionally set it to cause a buffer overflow (actually someone stupid enough to purposely create a security flaw in its own program, but I feel I have to take such cases into account). By using the struct1 model, however, I could simply check for a possible buffer overflow by just using:

if (s->str_length > sizeof(s->str)) {
    /* ERROR */
}

The problem is that the length array is actually unknown at compile-time. So I don't know whether to use a char * pointer (struct2 style, so no overflow check) or define a very big array (struct1), which would limit the max length (something I would like to avoid) and would allocate unnecessary space most of the time (which could be problematic in embedded systems with scarce memory, I suppose). I know I have to make a compromise, I'd personally use the struct2 model, but I'm not sure if it's a good choice security-wise.

Answers


Where does the user of your library get the struct2 instance to pass to the function from? I don't think he creates it by himself and then passes its address to your function, that would be a weird way to pass arguments. It is most likely returned from another function in your library, in which case you can make struct2 an opaque data type that the user cannot alter directly (or only in hacky ways):

/* in the header file */
typedef struct2_s struct2;

/* in the implementation file, where allocation is handled as well 
 * so you know str_length is set to the proper value.
 */
struct struct2_s {
  char *str;
  size_t str_length;
};

Put the big array at the end..

struct struct1 {
    anyType thisVar;
    someType anotherVar
    size_t str_length;
    char str[10240000]; /
}

Let the user malloc it to whatever 'real' size they wish. If they set 'str_length' wrong, well, there's not much you can do about it, no matter what you do:(


Need Your Help

Calling javascript functions from view in Rails 3

javascript ruby-on-rails

I am new to Rails and I have a pretty simple problem with calling javascript functions from within a view. In Rails 2 I would do...

Tomcat doesn't interpret jsp syntax

java spring maven jsp tomcat8

In eclipse I created a new dynamic web project. After converting to maven I added a tomcat v8 server for deploying. But from the beginning it's just possible to display plain html-code. It seems li...