[security] fix(data): restrict LaTeXOCR pickle loading (#17950)

* [security] fix(data): restrict LaTeXOCR pickle loading

* style(data): apply black formatting

* test: restore LaTeXOCR stubs after tests

---------

Co-authored-by: Lin Manhui <mhlin425@whu.edu.cn>
This commit is contained in:
HinotobiandLin Manhui authored and GitHub committed 2026-05-13 10:43:47 +08:00
1 parent 4d653b148a
commit d4323720c5
2 files changed
+158 -2

No files matched your search

+34 -2
View File
@@ -31,6 +31,34 @@ from .imaug.label_ops import LatexOCRLabelEncode
from .imaug import transform, create_operators
_ALLOWED_PICKLE_GLOBALS = {
("builtins", "dict"): dict,
("builtins", "list"): list,
("builtins", "tuple"): tuple,
("builtins", "set"): set,
("builtins", "frozenset"): frozenset,
("builtins", "str"): str,
("builtins", "int"): int,
("builtins", "float"): float,
("builtins", "bool"): bool,
("builtins", "bytes"): bytes,
}
class _RestrictedDatasetUnpickler(pickle.Unpickler):
def find_class(self, module, name):
allowed = _ALLOWED_PICKLE_GLOBALS.get((module, name))
if allowed is None:
raise pickle.UnpicklingError(
"Unsupported pickle global in LaTeXOCR dataset payload"
)
return allowed
def _restricted_pickle_load(file_obj):
return _RestrictedDatasetUnpickler(file_obj).load()
class LaTeXOCRDataSet(Dataset):
def __init__(self, config, mode, logger, seed=None):
super(LaTeXOCRDataSet, self).__init__()
@@ -51,8 +79,12 @@ class LaTeXOCRDataSet(Dataset):
self.rec_char_dict_path = global_config.pop("rec_char_dict_path")
self.tokenizer = LatexOCRLabelEncode(self.rec_char_dict_path)
file = open(pkl_path, "rb")
data = pickle.load(file)
with open(pkl_path, "rb") as file:
data = _restricted_pickle_load(file)
if not isinstance(data, dict):
raise pickle.UnpicklingError(
"LaTeXOCR dataset payload must deserialize to a dict"
)
temp = {}
for k in data:
if (
+124
View File
@@ -0,0 +1,124 @@
import importlib.util
import io
import pickle
import sys
import types
from pathlib import Path
import numpy as np
import pytest
def _load_latexocr_module(monkeypatch):
module_name = "ppocr.data.latexocr_dataset"
module_path = (
Path(__file__).resolve().parents[1] / "ppocr" / "data" / "latexocr_dataset.py"
)
ppocr_pkg = types.ModuleType("ppocr")
ppocr_pkg.__path__ = []
data_pkg = types.ModuleType("ppocr.data")
data_pkg.__path__ = []
imaug_pkg = types.ModuleType("ppocr.data.imaug")
imaug_pkg.__path__ = []
label_ops_mod = types.ModuleType("ppocr.data.imaug.label_ops")
class _Tokenizer:
def __init__(self, *_args, **_kwargs):
pass
label_ops_mod.LatexOCRLabelEncode = _Tokenizer
imaug_pkg.transform = lambda data, ops: data
imaug_pkg.create_operators = lambda transforms, global_config: []
paddle_mod = types.ModuleType("paddle")
paddle_io_mod = types.ModuleType("paddle.io")
class _Dataset:
pass
paddle_io_mod.Dataset = _Dataset
paddle_mod.io = paddle_io_mod
paddle_mod.arange = lambda n: list(range(n))
paddle_mod.randperm = lambda n: list(range(n))
for name, module in {
"ppocr": ppocr_pkg,
"ppocr.data": data_pkg,
"ppocr.data.imaug": imaug_pkg,
"ppocr.data.imaug.label_ops": label_ops_mod,
"paddle": paddle_mod,
"paddle.io": paddle_io_mod,
"cv2": types.ModuleType("cv2"),
}.items():
monkeypatch.setitem(sys.modules, name, module)
spec = importlib.util.spec_from_file_location(module_name, module_path)
module = importlib.util.module_from_spec(spec)
assert spec.loader is not None
monkeypatch.setitem(sys.modules, module_name, module)
spec.loader.exec_module(module)
return module
class _Payload:
def __init__(self, marker_path: Path):
self.marker_path = marker_path
def __reduce__(self):
expression = (
f"(__import__('pathlib').Path({self.marker_path.as_posix()!r}).write_text('pwned'), "
"{(32, 32): [('eq', 'img.png')]})[1]"
)
return (eval, (expression,))
@pytest.fixture
def latexocr_config(tmp_path):
return {
"Global": {
"max_seq_len": 16,
"rec_char_dict_path": str(tmp_path / "dict.txt"),
},
"Train": {
"dataset": {
"data": str(tmp_path / "dataset.pkl"),
"data_dir": str(tmp_path),
"min_dimensions": [1, 1],
"max_dimensions": [128, 128],
"batch_size_per_pair": 1,
"keep_smaller_batches": True,
"transforms": [],
},
"loader": {"shuffle": False},
},
}
def test_latexocr_dataset_rejects_executable_pickle_payload(
tmp_path, latexocr_config, monkeypatch
):
module = _load_latexocr_module(monkeypatch)
marker_path = tmp_path / "marker.txt"
payload_path = Path(latexocr_config["Train"]["dataset"]["data"])
payload_path.write_bytes(pickle.dumps(_Payload(marker_path)))
with pytest.raises(pickle.UnpicklingError):
module.LaTeXOCRDataSet(latexocr_config, "Train", logger=types.SimpleNamespace())
assert not marker_path.exists()
def test_latexocr_dataset_accepts_basic_dict_payload(
tmp_path, latexocr_config, monkeypatch
):
module = _load_latexocr_module(monkeypatch)
payload_path = Path(latexocr_config["Train"]["dataset"]["data"])
payload_path.write_bytes(pickle.dumps({(32, 32): [("eq", "img.png")]}))
dataset = module.LaTeXOCRDataSet(
latexocr_config, "Train", logger=types.SimpleNamespace()
)
assert dataset.size == 1
assert dataset.data == {(32, 32): [("eq", "img.png")]}