diff --git a/cloudinit/temp_utils.py b/cloudinit/temp_utils.py index f6b52e35d98..e4fe5e11017 100644 --- a/cloudinit/temp_utils.py +++ b/cloudinit/temp_utils.py @@ -44,7 +44,7 @@ def _tempfile_dir_arg(odir=None, needs_exe: bool = False): tdir = get_tmp_ancestor(odir, needs_exe) if not os.path.isdir(tdir): os.makedirs(tdir) - os.chmod(tdir, 0o1777) + os.chmod(tdir, 0o700) if needs_exe: if util.has_mount_opt(tdir, "noexec"): diff --git a/tests/unittests/test_temp_utils.py b/tests/unittests/test_temp_utils.py index 05c8a50aa60..6ce5f86df23 100644 --- a/tests/unittests/test_temp_utils.py +++ b/tests/unittests/test_temp_utils.py @@ -3,6 +3,7 @@ """Tests for cloudinit.temp_utils""" import os +import stat from tempfile import gettempdir import pytest @@ -120,6 +121,25 @@ def fake_mkstemp(*args, **kwargs): assert "/fake/return/path" == retval assert [{"dir": "/run/cloud-init/tmp"}] == calls + def test_mkdtemp_creates_missing_ancestor_not_world_writable( + self, tmp_path + ): + """mkdtemp creates missing ancestor dirs with mode 0o700 (GH-4189).""" + ancestor = str(tmp_path / "scratch") + retval = mkdtemp(dir=ancestor) + assert os.path.isdir(retval) + assert 0o700 == stat.S_IMODE(os.stat(ancestor).st_mode) + + def test_mkstemp_creates_missing_ancestor_not_world_writable( + self, tmp_path + ): + """mkstemp creates missing ancestor dirs with mode 0o700 (GH-4189).""" + ancestor = str(tmp_path / "scratch") + fd, retval = mkstemp(dir=ancestor) + os.close(fd) + assert os.path.isfile(retval) + assert 0o700 == stat.S_IMODE(os.stat(ancestor).st_mode) + def test_tempdir_error_suppression(self): """test tempdir suppresses errors during directory removal."""