Skip to content

Commit 58f5de7

Browse files
vlaciqkaiser
andcommitted
feat: introduce landlock based sandboxing
Co-authored-by: Quentin Kaiser <quentin.kaiser@onekey.com>
1 parent dc131b1 commit 58f5de7

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

unblob/processing.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import multiprocessing
22
import shutil
3+
import sys
34
from operator import attrgetter
45
from pathlib import Path
56
from typing import Iterable, List, Optional, Sequence, Set, Tuple, Type, Union
@@ -9,6 +10,11 @@
910
import plotext as plt
1011
from structlog import get_logger
1112
from unblob_native import math_tools as mt
13+
from unblob_native.sandbox import ( # type: ignore
14+
AccessFS,
15+
SandboxError,
16+
restrict_access,
17+
)
1218

1319
from unblob.handlers import BUILTIN_DIR_HANDLERS, BUILTIN_HANDLERS, Handlers
1420

@@ -112,6 +118,30 @@ def get_extract_dir_for(self, path: Path) -> Path:
112118
return extract_dir.expanduser().resolve()
113119

114120

121+
def sandbox(extract_dir: Path, report_file: Optional[Path]):
122+
restrictions = [
123+
AccessFS.read("/"),
124+
AccessFS.read_write("/dev/shm"), # noqa: S108
125+
AccessFS.read_write(extract_dir.as_posix()),
126+
AccessFS.make_dir(extract_dir.parent.as_posix()),
127+
]
128+
129+
if report_file:
130+
restrictions += [
131+
AccessFS.read_write(report_file),
132+
AccessFS.make_reg(report_file.parent),
133+
]
134+
135+
if "pytest" in sys.modules:
136+
restrictions += [
137+
AccessFS.read_write("/tmp"), # noqa: S108
138+
AccessFS.read_write("/build"),
139+
AccessFS.read_write(Path(__file__).parent.parent.resolve().as_posix()),
140+
]
141+
142+
restrict_access(*restrictions)
143+
144+
115145
@terminate_gracefully
116146
def process_file(
117147
config: ExtractionConfig, input_path: Path, report_file: Optional[Path] = None
@@ -136,6 +166,13 @@ def process_file(
136166
)
137167
return ProcessResult()
138168

169+
try:
170+
if not hasattr(process_file, "_sandboxed"):
171+
sandbox(extract_dir, report_file)
172+
process_file._sandboxed = True # noqa: SLF001
173+
except SandboxError:
174+
logger.warning("Sandboxing FS access is unavailable on this system, skipping.")
175+
139176
process_result = _process_task(config, task)
140177

141178
if not config.skip_extraction:

0 commit comments

Comments
 (0)