From 6c9cb4e14aa59d732f035bd2fdafec7fe7865789 Mon Sep 17 00:00:00 2001 From: Christopher Wellons Date: Fri, 3 Mar 2017 16:47:20 -0500 Subject: [PATCH] Write keys more securely. --- enchive.c | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/enchive.c b/enchive.c index ccf0205..25cdb80 100644 --- a/enchive.c +++ b/enchive.c @@ -1,3 +1,4 @@ +#define _POSIX_SOURCE #include #include #include @@ -47,6 +48,27 @@ fatal(const char *fmt, ...) exit(EXIT_FAILURE); } +#if defined(__unix__) || defined(__APPLE__) +#include + +static FILE * +secure_creat(char *file) +{ + int fd = open(file, O_CREAT | O_WRONLY, 00600); + if (fd == -1) + return 0; + return fdopen(fd, "wb"); +} +#else + +/* fallback to standard open */ +static FILE * +secure_creat(char *file) +{ + return fopen(file, "wb"); +} +#endif + /* Global options. */ static char *global_random_device = "/dev/urandom"; static char *global_pubkey = 0; @@ -227,7 +249,7 @@ write_key(char *file, const u8 *key, int clobber) if (!clobber && fopen(file, "r")) fatal("operation would clobber %s", file); - f = fopen(file, "wb"); + f = secure_creat(file); if (!f) fatal("failed to open key file for writing -- %s", file); cleanup_register(f, file);