Directory
Error #1 (c or C + +)
Error #2 (c or C + +)
Error #3 (can be any language, sample is C #)
Error #4
Error #5
Error #6 (C #)
Error #7 (C #)
Error #8 (C #)
Error #9 (C #)
Error #10 (Silverlight CLR C #)
We all like to check for security errors by reviewing the code. We can even say that we are very good at it. We are not boasting that we are the best, but we can often find a lot of mistakes quickly. Can you do it?
If you see a security error, can you identify it? Evaluate it by doing this test. Each code example has at least one security vulnerability. Try to find the error and take a look at your score. Following the code is a summary of these vulnerabilities, comments, and, if conditions permit, how the Security Development Lifecycle (SDL) can help find these errors. Thank Peter Torr and Eric Lippert for providing input and code examples.
Error #1 (c or C + +)
void func(char *s1, char *s2) {
char d[32];
strncpy(d,s1,sizeof d - 1);
strncat(d,s2,sizeof d - 1);
...
}
The answer: We think we should first talk about a buffer overflow that is old but very easy to understand. For many people, this code is safe enough because the code uses restricted strncpy and STRNCAT functions. However, these functions are safe only when the buffer size is appropriate, and in this case the buffer size is incorrect. Downright wrong.
Technically, the first call is safe, but the second call is wrong. The last parameter of the strncpy and STRNCAT functions is the amount of space that is reserved in the buffer, and you have just occupied some or all of the space by invoking strncpy. Buffer overflow. Michael published a blog post in 2004 that describes exactly the same type of error.
In Visual C + + 2005 and later versions, the warning C4996 is to tell you that you should replace the wrong function call with a more secure call, and the/analyze option will issue a C6053 warning that strncat may not terminate the string with 0.
To be honest, for a variety of reasons, strncpy and Strncat (and their "n" equivalents) are worse than strcpy and strcat (and their peers). First, the return value is a bit superfluous-it is a pointer to a buffer, and the buffer may or may not be valid. You have no way to know! Second, it's really hard to get the right target buffer size. If you find the error, you can add a point to yourself.