Skip to content

Commit

Permalink
Merge pull request #172 from pkalever/perms
Browse files Browse the repository at this point in the history
Ensure we have right perms on saveconfig
  • Loading branch information
maurizio-lombardi committed Jun 4, 2020
2 parents 3266f18 + 9f5764d commit 493b62e
Showing 1 changed file with 28 additions and 6 deletions.
34 changes: 28 additions & 6 deletions targetcli/ui_root.py
Expand Up @@ -95,6 +95,26 @@ def _compare_files(self, backupfile, savefile):
else:
return False

def _create_dir(self, dirname):
'''
create directory with permissions 0o600 set
if directory already exists, set right perms
'''
mode = stat.S_IRUSR | stat.S_IWUSR # 0o600
if not os.path.exists(dirname):
umask = 0o777 ^ mode # Prevents always downgrading umask to 0
umask_original = os.umask(umask)
try:
os.makedirs(dirname, mode)
except OSError as exe:
raise ExecutionError("Cannot create directory [%s] %s."
% (dirname, exe.strerror))
finally:
os.umask(umask_original)
else:
if (os.stat(dirname).st_mode & 0o777) != mode:
os.chmod(dirname, mode)

def _save_backups(self, savefile):
'''
Take backup of config-file if needed.
Expand All @@ -109,12 +129,7 @@ def _save_backups(self, savefile):
backupfile = backup_dir + backup_name
backup_error = None

if not os.path.exists(backup_dir):
try:
os.makedirs(backup_dir)
except OSError as exe:
raise ExecutionError("Cannot create backup directory [%s] %s."
% (backup_dir, exe.strerror))
self._create_dir(backup_dir)

# Only save backups if savefile exits
if not os.path.exists(savefile):
Expand All @@ -125,12 +140,17 @@ def _save_backups(self, savefile):

# Save backup if backup dir is empty, or savefile is differnt from recent backup copy
if not backed_files_list or not self._compare_files(backed_files_list[-1], savefile):
mode = stat.S_IRUSR | stat.S_IWUSR # 0o600
umask = 0o777 ^ mode # Prevents always downgrading umask to 0
umask_original = os.umask(umask)
try:
with open(savefile, 'rb') as f_in, gzip.open(backupfile, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
f_out.flush()
except IOError as ioe:
backup_error = ioe.strerror or "Unknown error"
finally:
os.umask(umask_original)

if backup_error == None:
# remove excess backups
Expand Down Expand Up @@ -167,6 +187,8 @@ def ui_command_saveconfig(self, savefile=default_save_file):

savefile = os.path.expanduser(savefile)

save_dir = os.path.dirname(savefile)
self._create_dir(save_dir)
self._save_backups(savefile)

self.rtsroot.save_to_file(savefile)
Expand Down

0 comments on commit 493b62e

Please sign in to comment.