Skip to content

Commit fbeacd8

Browse files
simathihCopilot
andauthored
Set default config file permissions after renaming (#2184)
* Set default config file permissions after renaming Add permission change for the updated config file * Use os.open with restricted permissions from file creation Replace open()+chmod approach with os.open() using O_CREAT|O_TRUNC and mode 0o400 to ensure the temp config file is never temporarily world-readable. Wraps fd with os.fdopen for safe writing. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Guard fd close if os.fdopen fails os.fdopen takes ownership of the fd, so the with-statement handles closing on normal/write-error paths. Add explicit os.close for the rare case where os.fdopen itself raises before taking ownership. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 09727a9 commit fbeacd8

1 file changed

Lines changed: 8 additions & 2 deletions

File tree

AzureMonitorAgent/agent.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -967,14 +967,20 @@ def enable():
967967
if os.path.isfile(config_file):
968968
new_config = "\n".join(["export {0}={1}".format(key, value) for key, value in default_configs.items()]) + "\n"
969969

970-
with open(temp_config_file, "w") as f:
970+
tmp_fd = os.open(temp_config_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o400)
971+
try:
972+
f = os.fdopen(tmp_fd, "w")
973+
except:
974+
os.close(tmp_fd)
975+
raise
976+
with f:
971977
f.write(new_config)
972978

973979
if not os.path.isfile(temp_config_file):
974980
log_and_exit("Enable", GenericErrorCode, "Error while updating environment variables in {0}".format(config_file))
975981

976982
os.remove(config_file)
977-
os.rename(temp_config_file, config_file)
983+
os.rename(temp_config_file, config_file)
978984
else:
979985
log_and_exit("Enable", GenericErrorCode, "Could not find the file {0}".format(config_file))
980986
except Exception as e:

0 commit comments

Comments
 (0)