Skip to content

Commit

Permalink
Fix #1175, Use fstat and fchmod for TOCTOU Bug
Browse files Browse the repository at this point in the history
  • Loading branch information
arielswalker committed Oct 19, 2021
1 parent 64a6b31 commit b1b6c9c
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions ut_assert/src/uttools.c
Original file line number Diff line number Diff line change
Expand Up @@ -106,14 +106,26 @@ bool UtMem2HexFile(const void *Memory, const char *Filename, uint32 Length)
FILE * fp;
uint32 i;
uint32 j;
int fd;
struct stat dststat;


/* Open file to avoid filename race potential */
fd = open(Filename, 0, 0);
if (fd < 0)
{
fd = open(Filename, 1, 0);
if (fd < 0)
{
printf("UtMem2HexFile: Error Opening File: %s, %s\n", Filename, strerror(errno));
return(false);
}
}

if ((fp = fopen(Filename, "w")))
{
if (stat(Filename, &dststat) == 0)
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)
Expand All @@ -135,6 +147,7 @@ bool UtMem2HexFile(const void *Memory, const char *Filename, uint32 Length)
fprintf(fp, "\n");
}
fclose(fp);
close(fd);
return (true);
}
else
Expand Down

0 comments on commit b1b6c9c

Please sign in to comment.