From 1d453d987d5ece338aad08cee315fbacf179e692 Mon Sep 17 00:00:00 2001 From: Krzysztof Grobelny Date: Fri, 26 Jun 2020 10:40:42 +0200 Subject: VolatileFile security fix - Flushing file content before deleting it TESTED: Tested manually, no regression detected. Signed-off-by: Krzysztof Grobelny Change-Id: Id48ebb6edbb2c0f0fbf930c2be9a63dd1034b7cc --- src/utils.hpp | 41 +++++++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/src/utils.hpp b/src/utils.hpp index f4d2c02..961e1e5 100644 --- a/src/utils.hpp +++ b/src/utils.hpp @@ -181,20 +181,7 @@ class VolatileFile ~VolatileFile() { - // Purge file contents - std::array buf; - buf.fill('*'); - std::ofstream file(filePath); - std::size_t bytesWritten = 0, bytesToWrite = 0; - - while (bytesWritten < size) - { - bytesToWrite = std::min(secretLimit, (size - bytesWritten)); - file.write(buf.data(), bytesToWrite); - bytesWritten += bytesToWrite; - } - - // Remove leftover file + purgeFileContents(); fs::remove(filePath); } @@ -206,16 +193,34 @@ class VolatileFile private: static void create(const std::string& filePath, const Buffer& data) { - // Create file std::ofstream file(filePath); + limitPermissionsToOwnerOnly(filePath); + file.write(data->data(), data->size()); + } - // Limit permissions to owner only + static void limitPermissionsToOwnerOnly(const std::string& filePath) + { fs::permissions(filePath, fs::perms::owner_read | fs::perms::owner_write, fs::perm_options::replace); + } - // Write contents - file.write(data->data(), data->size()); + void purgeFileContents() + { + if (std::ofstream file(filePath); file) + { + std::array buf; + buf.fill('*'); + + std::size_t bytesWritten = 0; + while (bytesWritten < size) + { + std::size_t bytesToWrite = + std::min(secretLimit, (size - bytesWritten)); + file.write(buf.data(), bytesToWrite); + bytesWritten += bytesToWrite; + } + } } const std::string filePath; -- cgit v1.2.3