Be more strict about file permission masks
authorJeremy Stanley <fungi@yuggoth.org>
Mon, 23 Mar 2015 07:05:55 +0000 (07:05 +0000)
committerJeremy Stanley <fungi@yuggoth.org>
Mon, 23 Mar 2015 07:05:55 +0000 (07:05 +0000)
Set a reasonably strict umask  of 0022 when creating most files and
directories. Also set the umask to 0077 for private files to avoid a
brief race where someone could open them for reading after creation
but prior to the prophylactic chmod to 0600.

lib/mudpy/data.py

index f254dc6..062bd87 100644 (file)
@@ -100,6 +100,9 @@ class DataFile:
 
     def save(self):
         """Write the data, if necessary."""
+        normal_umask = 0o0022
+        private_umask = 0o0077
+        private_file_mode = 0o0600
 
         # when modified, writeable and has content or the file exists
         if self.modified and self.is_writeable() and (
@@ -108,7 +111,9 @@ class DataFile:
 
             # make parent directories if necessary
             if not os.path.exists(os.path.dirname(self.filename)):
+                old_umask = os.umask(normal_umask)
                 os.makedirs(os.path.dirname(self.filename))
+                os.umask(old_umask)
 
             # backup the file
             if "__control__" in self.data and "backup_count" in self.data[
@@ -144,13 +149,17 @@ class DataFile:
                     os.rename(self.filename, self.filename + ".0")
 
             # our data file
-            file_descriptor = open(self.filename, "w")
-
-            # if it's marked private, chmod it appropriately
-            if self.filename in self.universe.private_files and oct(
-               stat.S_IMODE(os.stat(self.filename)[stat.ST_MODE])
-               ) != 0o0600:
-                os.chmod(self.filename, 0o0600)
+            if self.filename in self.universe.private_files:
+                old_umask = os.umask(private_umask)
+                file_descriptor = open(self.filename, "w")
+                if oct(stat.S_IMODE(os.stat(
+                        self.filename)[stat.ST_MODE])) != private_file_mode:
+                    # if it's marked private, chmod it appropriately
+                    os.chmod(self.filename, private_file_mode)
+            else:
+                old_umask = os.umask(normal_umask)
+                file_descriptor = open(self.filename, "w")
+            os.umask(old_umask)
 
             # write and close the file
             yaml.dump(self.data, allow_unicode=True, default_flow_style=False,