Skip to content

Commit

Permalink
Fix nasa#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 13, 2021
1 parent 64a6b31 commit db0f49a
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions ut_assert/src/uttools.c
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,15 @@ bool UtMem2BinFile(const void *Memory, const char *Filename, uint32 Length)

if ((fp = fopen(Filename, "w")))
{
if (stat(Filename, &dststat) == 0)
if (fstat(Filename, &dststat) < 0)
{
chmod(Filename, dststat.st_mode & ~(S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH));
stat(Filename, &dststat);
OS_DEBUG("fstat(%s): %s (%d)\n", local_path, strerror(errno), errno);
status = OS_ERROR;
}
else
{
fchmod(Filename, dststat.st_mode & ~(S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH));
fstat(Filename, &dststat);
}

fwrite(Memory, Length, 1, fp);
Expand Down Expand Up @@ -110,10 +115,15 @@ bool UtMem2HexFile(const void *Memory, const char *Filename, uint32 Length)

if ((fp = fopen(Filename, "w")))
{
if (stat(Filename, &dststat) == 0)
if (fstat(Filename, &dststat) < 0)
{
OS_DEBUG("fstat(%s): %s (%d)\n", local_path, strerror(errno), errno);
status = OS_ERROR;
}
else
{
chmod(Filename, dststat.st_mode & ~(S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH));
stat(Filename, &dststat);
fchmod(Filename, dststat.st_mode & ~(S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH));
fstat(Filename, &dststat);
}

for (i = 0; i < Length; i += 16)
Expand Down

0 comments on commit db0f49a

Please sign in to comment.