Skip to content

Commit 59659a3

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

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

unblob/processing.py

Lines changed: 29 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,7 @@
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 AccessFS, restrict_access # type: ignore
1214

1315
from unblob.handlers import BUILTIN_DIR_HANDLERS, BUILTIN_HANDLERS, Handlers
1416

@@ -112,6 +114,29 @@ def get_extract_dir_for(self, path: Path) -> Path:
112114
return extract_dir.expanduser().resolve()
113115

114116

117+
def sandbox(extract_dir: Path, report_file: Optional[Path]):
118+
restrictions = [
119+
AccessFS.read("/"),
120+
AccessFS.read_write("/dev/shm"), # noqa: S108
121+
AccessFS.read_write(extract_dir.as_posix()),
122+
AccessFS.make_dir(extract_dir.parent.as_posix()),
123+
]
124+
125+
if report_file:
126+
restrictions += [
127+
AccessFS.read_write(report_file),
128+
AccessFS.make_reg(report_file.parent),
129+
]
130+
131+
if "pytest" in sys.modules:
132+
restrictions += [
133+
AccessFS.read_write("/tmp"), # noqa: S108
134+
AccessFS.read_write(Path(__file__).parent.parent.resolve().as_posix()),
135+
]
136+
137+
restrict_access(*restrictions)
138+
139+
115140
@terminate_gracefully
116141
def process_file(
117142
config: ExtractionConfig, input_path: Path, report_file: Optional[Path] = None
@@ -136,6 +161,10 @@ def process_file(
136161
)
137162
return ProcessResult()
138163

164+
if not hasattr(process_file, "_sandboxed"):
165+
sandbox(extract_dir, report_file)
166+
process_file._sandboxed = True # noqa: SLF001
167+
139168
process_result = _process_task(config, task)
140169

141170
if not config.skip_extraction:

0 commit comments

Comments
 (0)