Skip to content
Open
Show file tree
Hide file tree
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
24 changes: 24 additions & 0 deletions python/unblob/processing.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import atexit
import multiprocessing
import os
import shutil
import tempfile
from collections.abc import Iterable, Sequence
from operator import attrgetter
from pathlib import Path
Expand Down Expand Up @@ -100,6 +103,21 @@ class ExtractionConfig:
dir_handlers: DirectoryHandlers = BUILTIN_DIR_HANDLERS
verbose: int = 1
progress_reporter: type[ProgressReporter] = NullProgressReporter
tmp_dir: Path = attrs.field(
factory=lambda: Path(tempfile.mkdtemp(prefix="unblob-tmp-"))
)

def __attrs_post_init__(self):
atexit.register(self._cleanup_tmp_dir)
Copy link
Contributor

Choose a reason for hiding this comment

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

This is problematic for programs using unblob as library, as these variables remain set in the hosting process's environment. We should set and reset them in a tighter scope.

For example, Processor.process_task looks like a fine candidate, as it by default will spawn child processes, not poisoning the caller's environment at all (given they use process_num > 1).

Another possibility is doing this at process_file level, but it still affects the hosting process unfortunately, but at least we can restore the variables upon returning from the function.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done. Also implemented tests in test_necessary_resources_can_be_created_in_sandbox

Copy link
Contributor

Choose a reason for hiding this comment

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

I do not see the original comment being resolved in the code - below I can find the env variables being set, but not restored, and here atexit.register still being used.

Have you pushed your changes?

I am also not sure how it would landlock to a /tmp/call-specific-tempdir if used as a library on the second call with another ExtractionConfig.

One solution I can think of is process_file forking in case of landlock, setting the environment variables in the fork, and cleaning up the temporary directory when the fork exits. Since the environment variables would be set in the child, they need no restoring.

(actually multiprocessing should be used somehow, as https://docs.python.org/3/library/os.html#os.fork has many problems and known not to work on macos)


def _cleanup_tmp_dir(self):
if isinstance(self.tmp_dir, Path) and self.tmp_dir.exists():
try:
shutil.rmtree(self.tmp_dir)
except Exception as e:
logger.warning(
"Failed to clean up tmp_dir", tmp_dir=self.tmp_dir, exc_info=e
)

def _get_output_path(self, path: Path) -> Path:
"""Return path under extract root."""
Expand Down Expand Up @@ -244,11 +262,17 @@ def __init__(self, config: ExtractionConfig):
def process_task(self, task: Task) -> TaskResult:
result = TaskResult(task)
try:
self._set_tmp_dir()
self._process_task(result, task)
except Exception as exc:
self._process_error(result, exc)
return result

def _set_tmp_dir(self):
"""Set environment variables so all subprocesses and handlers use our temp dir."""
for var in ("TMP", "TMPDIR", "TEMP", "TEMPDIR"):
os.environ[var] = self._config.tmp_dir.as_posix()

def _process_error(self, result: TaskResult, exc: Exception):
error_report = UnknownError(exception=exc)
result.add_report(error_report)
Expand Down
4 changes: 4 additions & 0 deletions python/unblob/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ def __init__(
AccessFS.remove_file(config.extract_root),
AccessFS.make_dir(config.extract_root.parent),
AccessFS.read_write(log_path),
# Allow access to the managed temp directory for handlers
AccessFS.read_write(config.tmp_dir),
AccessFS.remove_dir(config.tmp_dir),
AccessFS.remove_file(config.tmp_dir),
*extra_passthrough,
]

Expand Down
1 change: 1 addition & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,7 @@ def test_archive_success(
verbose=expected_verbosity,
progress_reporter=expected_progress_reporter,
)
config.tmp_dir = mock.ANY
process_file_mock.assert_called_once_with(config, in_path, None)
logger_config_mock.assert_called_once_with(expected_verbosity, tmp_path, log_path)

Expand Down
8 changes: 8 additions & 0 deletions tests/test_sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ def test_necessary_resources_can_be_created_in_sandbox(
):
directory_in_extract_root = extraction_config.extract_root / "path" / "to" / "dir"
file_in_extract_root = directory_in_extract_root / "file"
file_in_tmp_dir = extraction_config.tmp_dir / "tmp_file"
directory_in_tmp_dir = extraction_config.tmp_dir / "tmp_dir"

sandbox.run(extraction_config.extract_root.mkdir, parents=True)
sandbox.run(directory_in_extract_root.mkdir, parents=True)
Expand All @@ -45,6 +47,12 @@ def test_necessary_resources_can_be_created_in_sandbox(
log_path.touch()
sandbox.run(log_path.write_text, "log line")

sandbox.run(directory_in_tmp_dir.mkdir, parents=True)
sandbox.run(file_in_tmp_dir.touch)
sandbox.run(file_in_tmp_dir.write_text, "tmp file content")
sandbox.run(file_in_tmp_dir.unlink)
sandbox.run(directory_in_tmp_dir.rmdir)


def test_access_outside_sandbox_is_not_possible(sandbox: Sandbox, tmp_path: Path):
unrelated_dir = tmp_path / "unrelated" / "path"
Expand Down
Loading