From 9157b7845a8e35fc10e75b11dac860aa766fe0e5 Mon Sep 17 00:00:00 2001 From: ArielSAdamsNASA Date: Wed, 13 Oct 2021 08:50:30 -0500 Subject: [PATCH] Fix #1175, Use fstat and fchmod for TOCTOU Bug --- ut_assert/src/uttools.c | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/ut_assert/src/uttools.c b/ut_assert/src/uttools.c index 291edda9f..895a8530f 100644 --- a/ut_assert/src/uttools.c +++ b/ut_assert/src/uttools.c @@ -57,14 +57,15 @@ typedef struct bool UtMem2BinFile(const void *Memory, const char *Filename, uint32 Length) { FILE * fp; + int fd; struct stat dststat; if ((fp = fopen(Filename, "w"))) { - if (stat(Filename, &dststat) == 0) + fd = fileno(fp); + if (fstat(fd, &dststat) == 0) { - chmod(Filename, dststat.st_mode & ~(S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH)); - stat(Filename, &dststat); + fchmod(fd, dststat.st_mode & ~(S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH)); } fwrite(Memory, Length, 1, fp); @@ -106,14 +107,15 @@ bool UtMem2HexFile(const void *Memory, const char *Filename, uint32 Length) FILE * fp; uint32 i; uint32 j; + int fd; struct stat dststat; if ((fp = fopen(Filename, "w"))) { - if (stat(Filename, &dststat) == 0) + fd = fileno(fp); + if (fstat(fd, &dststat) == 0) { - chmod(Filename, dststat.st_mode & ~(S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH)); - stat(Filename, &dststat); + fchmod(fd, dststat.st_mode & ~(S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH)); } for (i = 0; i < Length; i += 16)