Insecure temporary file creation

Insecure temporary file creation

Description

Generating a temporary name and opening it later leaves time for the name to refer to another file or a symbolic link.

Potential impact

The process may overwrite an unintended file or expose temporary data. A privileged process can also affect protected files.

Remediation

Use mkstemp or a platform API that creates and opens the file in one operation. Close and remove the file when finished.

Examples

Before

c
char name[] = "/tmp/app.XXXXXX";
mktemp(name);
FILE *f = fopen(name, "w");

After

c
char name[] = "/tmp/app.XXXXXX";
int fd = mkstemp(name);

If mkstemp(name) returns -1, handle the creation failure. On success, use the returned fd without reopening the name.

References