Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Implement Linux User Namespaces support #248

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 54 additions & 10 deletions dangerzone/container.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import gzip
import json
import logging
import os
import pipes
Expand Down Expand Up @@ -49,6 +50,19 @@ def get_runtime() -> str:
return runtime


def podman_get_subids():
info = subprocess.run(
["podman", "info", "-f", "json"], check=True, stdout=subprocess.PIPE
)
info_dict = json.loads(info.stdout)
for id_type in ["uid", "gid"]:
mapping = info_dict["host"]["idMappings"][f"{id_type}map"]
count = 0
for m in mapping[1:]:
count += m["size"]
yield count


def install() -> bool:
"""
Make sure the podman container is installed. Linux only.
Expand Down Expand Up @@ -158,7 +172,9 @@ def exec_container(
if get_runtime_name() == "podman":
platform_args = []
security_args = ["--security-opt", "no-new-privileges"]
security_args += ["--userns", "keep-id"]
num_subuids, num_subgids = podman_get_subids()
security_args += ["--uidmap", f"0:1:{num_subuids}"]
security_args += ["--gidmap", f"0:1:{num_subgids}"]
else:
platform_args = ["--platform", "linux/amd64"]
security_args = ["--security-opt=no-new-privileges:true"]
Expand Down Expand Up @@ -189,6 +205,29 @@ def convert(
output_filename: str,
ocr_lang: Optional[str],
stdout_callback: Callable[[str], None],
) -> bool:
dz_tmp = os.path.join(appdirs.user_config_dir("dangerzone"), "tmp")
os.makedirs(dz_tmp, exist_ok=True)
tmpdir = tempfile.TemporaryDirectory(dir=dz_tmp)

try:
return _convert(tmpdir, input_filename, output_filename, ocr_lang,
stdout_callback)
finally:
if get_runtime_name() == "podman":
subprocess.run([
"podman", "unshare", "chown", "-R", "0:0", tmpdir.name
], check=True)
# Clean up
tmpdir.cleanup()


def _convert(
tmpdir: tempfile.TemporaryDirectory,
input_filename: str,
output_filename: str,
ocr_lang: Optional[str],
stdout_callback: Callable[[str], None],
) -> bool:
success = False

Expand All @@ -197,20 +236,23 @@ def convert(
else:
ocr = "0"

dz_tmp = os.path.join(appdirs.user_config_dir("dangerzone"), "tmp")
os.makedirs(dz_tmp, exist_ok=True)

tmpdir = tempfile.TemporaryDirectory(dir=dz_tmp)
tmp_input_file = os.path.join(tmpdir.name, "input_file")
pixel_dir = os.path.join(tmpdir.name, "pixels")
safe_dir = os.path.join(tmpdir.name, "safe")
shutil.copy(input_filename, tmp_input_file)
os.makedirs(pixel_dir, exist_ok=True)
os.makedirs(safe_dir, exist_ok=True)

if get_runtime_name() == "podman":
subprocess.run([
"podman", "unshare", "chown", "-R", "1001:1001", tmpdir.name
], check=True)

# Convert document to pixels
command = ["/usr/bin/python3", "/usr/local/bin/dangerzone.py", "document-to-pixels"]
Comment on lines 244 to 252
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about grouping together the "unshares" with a context manager? The core code would look a bit more organized:

    [...]
    with namespaced_tmpdir(tmpdir):
        # Convert document to pixels
        command = ["/usr/bin/python3", "/usr/local/bin/dangerzone.py", "document-to-pixels"]
        ...

The context manager I'm using looks like:

from contextlib import contextmanager

@contextmanager
def namespaced_tmpdir(tmpdir: tempfile.TemporaryDirectory):
    """Some more detailed explanation"""
    try:
        if get_runtime_name() == "podman":
            unshare_cmd = ["podman", "unshare", "chown", "-R", "1001:1001", tmpdir.name]
            log.debug("> " + " ".join(unshare_cmd))
            subprocess.run(unshare_cmd, check=True)
        yield
    finally:
        if get_runtime_name() == "podman":
            unshare_cmd = ["podman", "unshare", "chown", "-R", "0:0", tmpdir.name]
            log.debug("> " + " ".join(unshare_cmd))
            subprocess.run(unshare_cmd, check=True)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have implemented an example of this here 3de0633.

extra_args = [
"-v",
f"{input_filename}:/tmp/input_file",
f"{tmp_input_file}:/tmp/input_file",
"-v",
f"{pixel_dir}:/dangerzone",
]
Expand Down Expand Up @@ -243,14 +285,16 @@ def convert(
container_output_filename = os.path.join(
safe_dir, "safe-output-compressed.pdf"
)
shutil.move(container_output_filename, output_filename)

if get_runtime_name() == "podman":
subprocess.run([
"podman", "unshare", "chown", "-R", "0:0", tmpdir.name
], check=True)
shutil.move(container_output_filename, output_filename)

# We did it
success = True

# Clean up
tmpdir.cleanup()

return success


Expand Down