]> git.ipfire.org Git - thirdparty/kea.git/commitdiff
[#3050] Added Umask RAII and use it
authorFrancis Dupont <fdupont@isc.org>
Fri, 31 May 2024 22:47:11 +0000 (00:47 +0200)
committerFrancis Dupont <fdupont@isc.org>
Thu, 27 Jun 2024 12:47:52 +0000 (14:47 +0200)
src/lib/process/daemon.cc
src/lib/util/filesystem.cc
src/lib/util/filesystem.h
src/lib/util/tests/filesystem_unittests.cc

index e201f5e8a5549f41ff6aa9907a7c03eb3aeebed4..39786e28f87cc523f37fb77aad85833b9c59f460 100644 (file)
@@ -231,6 +231,9 @@ Daemon::writeConfigFile(const std::string& config_file,
         isc_throw(Unexpected, "Can't write configuration: conversion to JSON failed");
     }
 
+    // Remove rights for other from the umask.
+    Umask mask(S_IRWXO);
+
     std::ofstream out(config_file, std::ios::trunc);
     if (!out.good()) {
         isc_throw(Unexpected, "Unable to open file " + config_file + " for writing");
index 5571231562f70e36bb39717d3690b2e629d7eadf..cc0cc03d0c1014a2f54d6c87c096e83c34938c40 100644 (file)
@@ -19,7 +19,6 @@
 #include <string>
 
 #include <fcntl.h>
-#include <sys/stat.h>
 
 using namespace isc::util::str;
 using namespace std;
@@ -69,6 +68,14 @@ isFile(string const& path) {
     return ((statbuf.st_mode & S_IFMT) == S_IFREG);
 }
 
+Umask::Umask(mode_t mask) : orig_umask_(umask(S_IWGRP | S_IWOTH)) {
+    umask(orig_umask_ | mask);
+}
+
+Umask::~Umask() {
+    umask(orig_umask_);
+}
+
 Path::Path(string const& full_name) {
     if (!full_name.empty()) {
         bool dir_present = false;
index 1f20003f39810b6762eb216d017f5412075b05f6..0305fa4d1c9dfc25d52f7b18530f88a0e8017f4d 100644 (file)
@@ -7,6 +7,7 @@
 #ifndef KEA_UTIL_FILESYSTEM_H
 #define KEA_UTIL_FILESYSTEM_H
 
+#include <sys/stat.h>
 #include <string>
 
 namespace isc {
@@ -48,6 +49,23 @@ isDir(const std::string& path);
 bool
 isFile(const std::string& path);
 
+/// \brief RAII device to limit access of created files.
+struct Umask {
+    /// \brief Constructor
+    ///
+    /// Set wanted bits in umask.
+    Umask(mode_t mask);
+
+    /// \brief Destructor.
+    ///
+    /// Restore umask.
+    ~Umask();
+
+private:
+    /// \brief Original umask.
+    mode_t orig_umask_;
+};
+
 /// \brief Paths on a filesystem
 struct Path {
     /// \brief Constructor
index 548070a35a7f8ddf43380ff33f30ff9cb303163c..28d9513f1ccd6569fb9cae0a83f8537826dbbb5e 100644 (file)
@@ -69,6 +69,18 @@ TEST_F(FileUtilTest, isFile) {
     EXPECT_FALSE(isFile(TEST_DATA_BUILDDIR));
 }
 
+/// @brief Check Umask.
+TEST_F(FileUtilTest, umask) {
+    // Protect the test itself assuming that Umask does what we expect...
+    Umask m0(0);
+    mode_t orig = umask(0);
+    {
+        Umask m(S_IROTH);
+        EXPECT_EQ(S_IROTH, umask(S_IRWXO));
+    }
+    EXPECT_EQ(0, umask(orig));
+}
+
 /// @brief Check that the components are split correctly.
 TEST(PathTest, components) {
     // Complete name