\"The average man does not want to be free. He simply wants to be safe.\" - H. L. Menken
I am attempting to write very secure C. Below I
Don't use gets()
for input, use fgets()
. To use fgets()
, if your buffer is automatically allocated (i.e., "on the stack"), then use this idiom:
char buf[N];
...
if (fgets(buf, sizeof buf, fp) != NULL)
This will keep working if you decide to change the size of buf
. I prefer this form to:
#define N whatever
char buf[N];
if (fgets(buf, N, fp) != NULL)
because the first form uses buf
to determine the second argument, and is clearer.
Check the return value of fclose().
Yannick Moy developed a Hoare/Floyd weakest precondition system for C during his PhD and applied it to the CERT managed strings library. He found a number of bugs (see page 197 of his memoir). The good news is that the library is safer now for his work.
You could also look at Les Hatton's web site here and at his book Safer C which you can get from Amazon.
A good place to start looking at this is David Wheeler's excellent secure coding site.
His free online book "Secure Programming for Linux and Unix HOWTO" is an excellent resource that is regularly updated.
You might also like to look at his excellent static analyser FlawFinder to get some further hints. But remember, no automated tool is a replacement for a good pair of experienced eyes, or as David so colourfully puts it..
Any static analysis tool, such as Flawfinder, is merely a tool. No tool can substitute for human thought! In short, "a fool with a tool is still a fool". It's a mistake to think that analysis tools (like flawfinder) are a substitute for security training and knowledge
I have personally used David's resources for several years now and find them to be excellent.
Insecure Programming by Example
blog with a few of the answers
I think your sscanf example is wrong. It can still overflow when used that way.
Try this, which specifies the maximum number of bytes to read:
void main(int argc, char **argv)
{
char buf[256];
sscanf(argv[0], "%255s", &buf);
}
Take a look at this IBM dev article about protecting against buffer overflows.
In terms of testing, I would write a program that generates random strings of random length and feed them to your program, and make sure they are handled appropriately.