Rules / C/C++
SHIELD-CPP-016
Insecure temporary file creation
What it detects
mktemp and tmpnam generate predictable names vulnerable to symlink and race attacks.
How to fix
Use mkstemp which atomically creates and opens a unique file.
Vulnerable — Shield flags thisscratch.c
#include <stdlib.h>
#include <fcntl.h>
int open_scratch(void) {
static char path[] = "/tmp/report-XXXXXX";
if (mktemp(path)[0] == '\0') /* predictable name */
return -1;
return creat(path, 0600); /* name can be raced */
}
Fixed — scans cleanscratch.c
#include <stdlib.h>
int open_scratch(void) {
char path[] = "/tmp/report-XXXXXX";
/* mkstemp atomically creates and opens a unique file */
return mkstemp(path);
}
Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-CPP-016, the fixed one does not.