From 29f626fe3bdcf8beb5bbef5f5fc949103039e4ab Mon Sep 17 00:00:00 2001 From: Helmut Grohne Date: Wed, 31 Jan 2024 08:07:18 +0100 Subject: examples/chroottar.py: add explanations for non-trivial aspects --- examples/chroottar.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/chroottar.py b/examples/chroottar.py index 89db0b1..47e5fe1 100755 --- a/examples/chroottar.py +++ b/examples/chroottar.py @@ -59,7 +59,10 @@ class TarFile(tarfile.TarFile): except: zfobj.close() raise - tarobj._extfileobj = False + # Setting the _extfileobj attribute is important to signal a need to + # close this object and thus flush the compressed stream. + # Unfortunately, tarfile.pyi doesn't know about it. + tarobj._extfileobj = False # type: ignore return tarobj def get_comptype(self) -> str: @@ -107,6 +110,8 @@ def main() -> None: pid = os.fork() if pid == 0: parentsock.close() + # Once we drop privileges via setreuid and friends, we may become + # unable to open basetar or to chdir to tdir, so do those early. with TarFile.open(args.basetar, "r:*") as tarf: os.chdir(tdir) linuxnamespaces.unshare( @@ -116,6 +121,8 @@ def main() -> None: childsock.send(tarf.get_comptype().encode("ascii") + b"\0") childsock.recv(1) childsock.close() + # The other process will now have set up our id mapping and + # will have changed ownersip of our working directory. os.setreuid(0, 0) os.setregid(0, 0) os.setgroups([]) @@ -147,6 +154,9 @@ def main() -> None: childsock.close() comptype = parentsock.recv(10).split(b"\0", 1)[0].decode("ascii") linuxnamespaces.newidmaps(pid, [uidmap], [gidmap]) + # We still had to be in the initial namespace to call newidmaps and + # now we transition to a namespace that can access both the container + # and the files of the invoking user. linuxnamespaces.unshare_user_idmap( [uidmap, linuxnamespaces.IDMapping(65536, os.getuid(), 1)], [gidmap, linuxnamespaces.IDMapping(65536, os.getgid(), 1)], -- cgit v1.2.3