From f0f82fcb238c6c7428d884fd8da4b1071a4546f4 Mon Sep 17 00:00:00 2001 From: Jonas 'Sortie' Termansen Date: Sat, 10 Oct 2015 01:24:43 +0200 Subject: [PATCH] Fix tmpfile(3) insecure file creation. --- libc/stdio/tmpfile.cpp | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/libc/stdio/tmpfile.cpp b/libc/stdio/tmpfile.cpp index 71505e2a..17c53db0 100644 --- a/libc/stdio/tmpfile.cpp +++ b/libc/stdio/tmpfile.cpp @@ -1,6 +1,6 @@ /******************************************************************************* - Copyright(C) Jonas 'Sortie' Termansen 2013. + Copyright(C) Jonas 'Sortie' Termansen 2013, 2015. This file is part of the Sortix C Library. @@ -25,15 +25,21 @@ #include #include +#include #include extern "C" FILE* tmpfile() { - char name[5 + sizeof(pid_t) * 3]; - snprintf(name, sizeof(name), "/tmp/%ju", (uintmax_t) getpid()); - FILE* ret = fopen(name, "w+"); - if ( !ret ) - return NULL; - unlink(name); - return ret; + // TODO: There is a short interval during which other processes can access + // this file. Implement and use O_TMPFILE. + char path[] = "/tmp/tmp.XXXXXX"; + int fd = mkstemp(path); + if ( fd < 0 ) + return (FILE*) NULL; + if ( unlink(path) < 0 ) + return close(fd), (FILE*) NULL; + FILE* fp = fdopen(fd, "r+"); + if ( !fp ) + return close(fd), (FILE*) NULL; + return fp; }