Why is strcpy () unsafe?

5

I'm reading about secure programming, and I read that the strcpy() function of the C language is an example of insecure function.

I also read that there is a safe version of this function, which would be strcpy_s() .

What is the functional difference between them? Does it have anything to do with accessing undue memory locations? I would like an example to understand the "insecurity" of strcpy() .

    
asked by anonymous 30.04.2016 / 21:57

1 answer

5

First, it is important to say that you can safely use this function. Her problem is that the programmer may forget or not know how to do this.

The first problem with the function is that it does not consider the size of what it is copying, so it is possible to overwrite an area of memory that was not intended. Usually the memory is allocated where the string copy is placed and then the operation is performed. If what is passed to this function is larger than the placeholder, it will place data beyond the placeholder. And this is one way to inject malicious code into an application you want to compromise.

Another problem is that it does not guarantee that the destination will be terminated by a% null value, which is what determines the end of a string , so another part of the code can read this memory waiting for this character to know when to stop reading and you will not find it. This problem also exists in strncpy() .

The function strcpy_s() (only available in C11) requires you to pass the size of what will be copied and the function will respect this. Of course if the programmer does not put an appropriate value (probably equal to what was allocated) it will also be insecure. It guarantees that it will have a null ending string appropriately.

If you do not have a C11 compiler, you can use strlcpy() , if available, or strncpy() , which still has problems, but is already a little better. Anyway, the programmer can always check before using the function if the source size is suitable for the target and can ensure that the null is placed at the end. Every decent C programmer has a function of his own to do this for him if the compiler he uses does not provide a standard function.

char * txt = malloc(10);
strcpy(txt, "teste maior do que devia"); //aqui já era! Vai ocupar uma memória indevida
strcpy_s(txt, 10, "teste maior do que devia"); //aqui só vai usar "teste mai"
    
30.04.2016 / 22:14