Fix static analysis(TOCTOU) issue 23/242223/4
authorJunghyun Yeon <jungh.yeon@samsung.com>
Tue, 25 Aug 2020 05:17:55 +0000 (14:17 +0900)
committerJunghyun Yeon <jungh.yeon@samsung.com>
Tue, 1 Sep 2020 06:39:47 +0000 (06:39 +0000)
Change-Id: I18dfdee7f6ca2dc0e7676b95b84aece3b3208fb9
Signed-off-by: Junghyun Yeon <jungh.yeon@samsung.com>
src/wgt/step/encryption/step_encrypt_resources.cc

index c5bbb9b..40b6781 100644 (file)
@@ -13,7 +13,9 @@
 #include <common/utils/byte_size_literals.h>
 
 #include <manifest_parser/utils/logging.h>
+
 #include <sys/stat.h>
+#include <unistd.h>
 
 #include <algorithm>
 #include <cstdio>
@@ -160,22 +162,28 @@ bool StepEncryptResources::Encrypt(const bf::path &src) {
 bool StepEncryptResources::EncryptFile(const bf::path &src) {
   struct stat info;
   memset(&info, 0, sizeof(info));
-  if (stat(src.c_str(), &info) != 0) {
+  int fd;
+
+  FILE *input = OpenFile(src, "rb");
+  if (!input) {
+    LOG(ERROR) << "Cannot open file for encryption: " << src;
+    return false;
+  }
+
+  fd = fileno(input);
+  if (fstat(fd, &info) != 0) {
     LOG(ERROR) << "Could not access file " << src;
+    fclose(input);
     return false;
   }
+
   const std::size_t fileSize = info.st_size;
   if (0 == fileSize) {
     LOG(ERROR) << src << " size is 0, so encryption will be skipped";
+    fclose(input);
     return true;
   }
 
-  FILE *input = OpenFile(src, "rb");
-  if (!input) {
-    LOG(ERROR) << "Cannot open file for encryption: " << src;
-    return false;
-  }
-
   bf::path encFile(src.string() + ".enc");
   FILE *output = OpenFile(encFile, "wb");
   if (!output) {
@@ -263,11 +271,13 @@ bool StepEncryptResources::EncryptFile(const bf::path &src) {
   } while (!std::feof(input));
 
   fclose(output);
-  fclose(input);
 
   LOG(DEBUG) << "File encrypted successfully";
-  if (0 != unlink(src.c_str()))
+  if (0 != unlink(src.c_str())) {
+    fclose(input);
     return false;
+  }
+  fclose(input);
 
   LOG(DEBUG) << "Rename encrypted file";
   if (0 != std::rename(encFile.c_str(), src.c_str()))