From d2efe23825fe8bb84d6d754226a6134669f76c28 Mon Sep 17 00:00:00 2001 From: bluhm Date: Thu, 15 Oct 2015 19:30:03 +0000 Subject: [PATCH] Avoid a race between fopen(3) and fchmod(2). Use umask(2) and unlink(2) and fopen(3) to prevent an attacker to open an old file with wrong permissions before the secret is written into it. This also guarantees that a new file with correct permissions is created. Without fchmod(2) "fattr" can be removed from pledge. with and OK deraadt@ --- usr.bin/x99token/x99token.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/usr.bin/x99token/x99token.c b/usr.bin/x99token/x99token.c index eb5f68f4fc8..0aaa0919bdc 100644 --- a/usr.bin/x99token/x99token.c +++ b/usr.bin/x99token/x99token.c @@ -1,4 +1,4 @@ -/* $OpenBSD: x99token.c,v 1.11 2015/10/15 17:23:09 bluhm Exp $ */ +/* $OpenBSD: x99token.c,v 1.12 2015/10/15 19:30:03 bluhm Exp $ */ /* * X9.9 calculator @@ -46,7 +46,7 @@ main(int argc, char **argv) unsigned int pin; struct passwd *pwd; - if (pledge("stdio rpath wpath cpath fattr getpw tty", NULL) == -1) + if (pledge("stdio rpath wpath cpath getpw tty", NULL) == -1) err(1, "pledge"); while ((i = getopt(argc, argv, "dk:in:")) != -1) { @@ -139,9 +139,10 @@ main(int argc, char **argv) key[0] ^= (pin >> ((i * 7) % 26)) & 0x7f; if (init) { + umask(S_IRWXG | S_IRWXO); + unlink(keyfile); if ((fp = fopen(keyfile, "w")) == NULL) err(1, "could not open %s for writing", keyfile); - fchmod(fileno(fp), 0600); for (i = 0; i < 8; ++i) { fprintf(fp, "%c", digits[(key[i]>>4)&0xf]); fprintf(fp, "%c", digits[(key[i]>>0)&0xf]); -- 2.20.1