Temporary file security risks
What you'll learn: Why using predictable filenames for temporary storage can allow hackers to hijack your program's data.
The "Reserved Parking" Problem
Imagine you are driving to a busy stadium and you call ahead to reserve a specific parking spot, "Spot #42." A thief overhead your call, arrived five minutes early, and placed a giant, locked crate in Spot #42. When you arrive, you don't realize the crate is malicious; you just assume it's part of the spot, so you leave your valuable luggage next to it.
In C programming, this is known as a Race Condition. If your program always creates a temporary file named /tmp/my_data.txt, a malicious user can create a "symbolic link" with that exact name before your program runs. When your program opens the file to write sensitive data, it follows that link and accidentally overwrites a system file or leaks data into a folder the hacker controls.
Predictability is the Enemy
Older C functions like tmpnam() or mktemp() are dangerous because they only suggest a filename. There is a tiny gap in time between when the name is generated and when your program actually creates the file. In that split second, an attacker can "win the race" by creating a file with that name first.
To fix this, we use mkstemp(). This function doesn't just give you a name; it creates the file and opens it for you in one atomic step. It also uses random characters to make the filename impossible to guess.
Secure file creation
Here is how you safely generate a temporary file without falling into the predictability trap:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
// The XXXXXX will be replaced by random characters
char temp_template[] = "/tmp/data_XXXXXX";
// mkstemp opens the file safely and returns a file descriptor
int fd = mkstemp(temp_template);
if (fd == -1) {
perror("Failed to create safe temporary file");
return 1;
}
printf("Secure temp file created at: %s\n", temp_template);
// Close and remove the file when done
close(fd);
unlink(temp_template);
return 0;
}
By using mkstemp(), you ensure that if a file with that random name already exists, the system will try a different random name until it finds a truly unique one, leaving no room for a hacker to intercept your data.
Key takeaway
Never use hardcoded or predictable temporary filenames; use mkstemp() to create files with random names in a single, secure step.