Files
dlp-io/tests/test_dlp_io_encryption.py
T
Li.jiaqi44 2c5c36f9a3
publish-dlp-io / publish (push) Failing after 50s
feat: is_encrypted 改用物理/逻辑大小判定 (0.4.0)
- 判定改为 GetCompressedFileSizeW 物理大小 vs 白名单 helper 逻辑大小:加密文件
  多 1,024 字节尾块,物理大于逻辑即加密,相等即未加密;不读文件内容,也无需判断
  当前进程是否白名单,Python/pyd/EXE 三种环境同一套代码
- 内容比对降为权威回退:压缩/稀疏文件、无尾块主机、helper 不可用时不结论,回退
  certutil 比对;DLP_IO_DETECT=content 可强制走内容比对
- 新增 handle_stat 与 _compressed_size_api/_physical_size/_helper_size/
  _detect_mode/_size_verdict/_content_verdict
- 测试夹具 DLP加密文件.pptx 换成 DLP加密文件.xlsx,加密用例同步覆盖大小判定
- 新增 docs/DLP_DSOC_API_NOTES.md,更新环境调研与库使用文档
2026-11-19 15:28:58 +08:00

370 lines
12 KiB
Python

from __future__ import annotations
import hashlib
import os
from pathlib import Path
import pytest
import dlp_io
pytestmark = pytest.mark.skipif(os.name != "nt", reason="DLP detection requires Windows")
SAMPLES_DIR = Path(__file__).resolve().parent
ENCRYPTED_SAMPLE = SAMPLES_DIR / "DLP加密文件.xlsx"
DECRYPTED_SAMPLE = SAMPLES_DIR / "DLP解密文件.pptx"
@pytest.fixture(autouse=True)
def reset_module_state(monkeypatch):
monkeypatch.delenv(dlp_io._WRITE_CHANNEL_ENV, raising=False)
monkeypatch.delenv(dlp_io._DETECT_ENV, raising=False)
monkeypatch.setattr(dlp_io, "_config", dlp_io.DlpConfig())
dlp_io._write_channel_cache.clear()
dlp_io.shutdown()
yield
dlp_io._write_channel_cache.clear()
dlp_io.shutdown()
def _native_sha256(path: Path) -> bytes:
return hashlib.sha256(path.read_bytes()).digest()
def _dlp_host() -> bool:
"""本机是否启用 DLP:加密样本的原始盘内字节与本地视图是否不一致。"""
return dlp_io._raw_sha256(str(ENCRYPTED_SAMPLE)) != _native_sha256(ENCRYPTED_SAMPLE)
# ---------------------------------------------------------------------------
# is_encrypted against the real DLP samples
def test_encrypted_sample_matches_host_dlp_capability() -> None:
assert dlp_io.is_encrypted(ENCRYPTED_SAMPLE) == _dlp_host()
def test_decrypted_sample_is_never_reported_encrypted() -> None:
assert dlp_io.is_encrypted(DECRYPTED_SAMPLE) is False
def test_is_encrypted_missing_file_raises() -> None:
with pytest.raises(FileNotFoundError):
dlp_io.is_encrypted(SAMPLES_DIR / "missing-sample.bin")
# ---------------------------------------------------------------------------
# is_encrypted decision branches (mocked channels)
def test_is_encrypted_short_circuits_when_raw_digest_differs(monkeypatch) -> None:
monkeypatch.setattr(dlp_io, "_native_sha256", lambda path: b"\x01" * 32)
monkeypatch.setattr(dlp_io, "_raw_sha256", lambda path: b"\x02" * 32)
monkeypatch.setattr(
dlp_io,
"_get_default_session",
lambda: pytest.fail("helper must not start when digests differ"),
)
assert dlp_io.is_encrypted("payload.bin") is True
@pytest.mark.parametrize(
("helper_head", "native_head", "expected"),
[
(b"\x50\x4b\x03\x04", b"\x18\x1b\x03\x1a", True),
(b"\x50\x4b\x03\x04", b"\x50\x4b\x03\x04", False),
],
)
def test_is_encrypted_ambiguous_case_compares_helper_head(
monkeypatch, helper_head: bytes, native_head: bytes, expected: bool
) -> None:
digest = b"\x01" * 32
monkeypatch.setattr(dlp_io, "_native_sha256", lambda path: digest)
monkeypatch.setattr(dlp_io, "_raw_sha256", lambda path: digest)
monkeypatch.setattr(dlp_io, "_native_head", lambda path, size: native_head)
monkeypatch.setattr(dlp_io, "_helper_head", lambda path, size: helper_head)
assert dlp_io.is_encrypted("payload.bin") is expected
# ---------------------------------------------------------------------------
# is_encrypted size fast path (physical on-disk size vs helper logical size)
def test_helper_stat_size_matches_native_view() -> None:
expected = ENCRYPTED_SAMPLE.stat().st_size
assert dlp_io._get_default_session().stat_size(str(ENCRYPTED_SAMPLE)) == expected
def test_encrypted_sample_is_detected_without_content_read(monkeypatch) -> None:
physical = dlp_io._physical_size(str(ENCRYPTED_SAMPLE))
if physical is None or physical <= ENCRYPTED_SAMPLE.stat().st_size:
pytest.skip("host stores no on-disk trailer for encrypted files")
monkeypatch.setattr(
dlp_io, "_native_sha256", lambda path: pytest.fail("content path used")
)
monkeypatch.setattr(
dlp_io, "_raw_sha256", lambda path: pytest.fail("content path used")
)
assert dlp_io.is_encrypted(ENCRYPTED_SAMPLE) is True
def test_size_delta_above_zero_reports_encrypted(monkeypatch, tmp_path) -> None:
target = tmp_path / "payload.bin"
target.write_bytes(b"x")
monkeypatch.setattr(dlp_io, "_physical_size", lambda path: 2048)
monkeypatch.setattr(dlp_io, "_helper_size", lambda path: 1024)
monkeypatch.setattr(
dlp_io, "_native_sha256", lambda path: pytest.fail("content path used")
)
assert dlp_io.is_encrypted(target) is True
def test_size_equal_to_logical_reports_plain(monkeypatch, tmp_path) -> None:
target = tmp_path / "payload.bin"
target.write_bytes(b"x")
monkeypatch.setattr(dlp_io, "_physical_size", lambda path: 1024)
monkeypatch.setattr(dlp_io, "_helper_size", lambda path: 1024)
monkeypatch.setattr(
dlp_io, "_native_sha256", lambda path: pytest.fail("content path used")
)
assert dlp_io.is_encrypted(target) is False
def test_physical_below_logical_falls_back_to_content(monkeypatch, tmp_path) -> None:
target = tmp_path / "payload.bin"
target.write_bytes(b"x")
calls = []
monkeypatch.setattr(dlp_io, "_physical_size", lambda path: 512)
monkeypatch.setattr(dlp_io, "_helper_size", lambda path: 1024)
monkeypatch.setattr(
dlp_io, "_native_sha256", lambda path: calls.append(path) or b"\x01" * 32
)
monkeypatch.setattr(dlp_io, "_raw_sha256", lambda path: b"\x02" * 32)
assert dlp_io.is_encrypted(target) is True
assert calls
def test_unavailable_helper_falls_back_to_content(monkeypatch, tmp_path) -> None:
target = tmp_path / "payload.bin"
target.write_bytes(b"x")
calls = []
def unavailable(path):
raise dlp_io.DlpHelperStartError("no approved python on this host")
monkeypatch.setattr(dlp_io, "_physical_size", lambda path: 2048)
monkeypatch.setattr(dlp_io, "_helper_size", unavailable)
monkeypatch.setattr(
dlp_io, "_native_sha256", lambda path: calls.append(path) or b"\x01" * 32
)
monkeypatch.setattr(dlp_io, "_raw_sha256", lambda path: b"\x02" * 32)
assert dlp_io.is_encrypted(target) is True
assert calls
def test_detect_env_content_skips_size_probe(monkeypatch, tmp_path) -> None:
target = tmp_path / "payload.bin"
target.write_bytes(b"x")
monkeypatch.setenv(dlp_io._DETECT_ENV, dlp_io._DETECT_CONTENT)
monkeypatch.setattr(
dlp_io,
"_physical_size",
lambda path: pytest.fail("size probe must be skipped"),
)
monkeypatch.setattr(dlp_io, "_native_sha256", lambda path: b"\x01" * 32)
monkeypatch.setattr(dlp_io, "_raw_sha256", lambda path: b"\x02" * 32)
assert dlp_io.is_encrypted(target) is True
def test_detect_env_rejects_unknown_value(monkeypatch, tmp_path) -> None:
target = tmp_path / "payload.bin"
target.write_bytes(b"x")
monkeypatch.setenv(dlp_io._DETECT_ENV, "size-only")
with pytest.raises(dlp_io.DlpConfigurationError):
dlp_io.is_encrypted(target)
# ---------------------------------------------------------------------------
# Write channel selection
def test_select_write_channel_honours_probes(monkeypatch, tmp_path) -> None:
monkeypatch.setattr(dlp_io, "_probe_direct_write", lambda suffix: True)
monkeypatch.setattr(
dlp_io,
"_probe_powershell_write",
lambda suffix: pytest.fail("powershell probe must be skipped"),
)
assert dlp_io._select_write_channel(".bin") is dlp_io.WriteChannel.DIRECT
monkeypatch.setattr(dlp_io, "_probe_direct_write", lambda suffix: False)
monkeypatch.setattr(dlp_io, "_probe_powershell_write", lambda suffix: True)
assert dlp_io._select_write_channel(".pptx") is dlp_io.WriteChannel.POWERSHELL
def test_select_write_channel_raises_when_no_channel_works(monkeypatch) -> None:
monkeypatch.setattr(dlp_io, "_probe_direct_write", lambda suffix: False)
monkeypatch.setattr(dlp_io, "_probe_powershell_write", lambda suffix: False)
with pytest.raises(dlp_io.DlpWriteError):
dlp_io._select_write_channel(".bin")
def test_select_write_channel_caches_per_suffix(monkeypatch) -> None:
calls = []
monkeypatch.setattr(
dlp_io, "_probe_direct_write", lambda suffix: calls.append(suffix) or True
)
assert dlp_io._select_write_channel(".BIN") is dlp_io.WriteChannel.DIRECT
assert dlp_io._select_write_channel(".bin") is dlp_io.WriteChannel.DIRECT
assert len(calls) == 1
def test_write_channel_env_override(monkeypatch) -> None:
monkeypatch.setenv(dlp_io._WRITE_CHANNEL_ENV, "PowerShell")
monkeypatch.setattr(
dlp_io,
"_probe_direct_write",
lambda suffix: pytest.fail("override must skip probing"),
)
assert dlp_io._select_write_channel(".bin") is dlp_io.WriteChannel.POWERSHELL
monkeypatch.setenv(dlp_io._WRITE_CHANNEL_ENV, "bogus")
with pytest.raises(dlp_io.DlpConfigurationError):
dlp_io._select_write_channel(".bin")
def test_real_probe_selects_a_working_channel(tmp_path) -> None:
try:
channel = dlp_io._select_write_channel(".bin")
except dlp_io.DlpWriteError:
pytest.skip("host cannot produce unencrypted writes")
direct_ok = dlp_io._probe_direct_write(".bin")
expected = dlp_io.WriteChannel.DIRECT if direct_ok else dlp_io.WriteChannel.POWERSHELL
assert channel is expected
# ---------------------------------------------------------------------------
# PowerShell relay writer
def test_powershell_relay_writes_exact_binary_and_lands_plaintext(tmp_path) -> None:
payload = bytes(range(256)) * 64 + b"\x00\x1a\xff"
target = tmp_path / "relay输出.bin"
with dlp_io._PowerShellRelayRaw(str(target), "Create") as raw:
assert raw.writable()
assert raw.write(payload) == len(payload)
assert target.read_bytes() == payload
assert dlp_io._raw_sha256(str(target)) == hashlib.sha256(payload).digest()
def test_powershell_relay_append_preserves_existing_content(tmp_path) -> None:
target = tmp_path / "relay.bin"
with dlp_io._PowerShellRelayRaw(str(target), "Create") as raw:
raw.write(b"ab")
with dlp_io._PowerShellRelayRaw(str(target), "Append") as raw:
raw.write(b"cd")
assert target.read_bytes() == b"abcd"
def test_powershell_relay_create_new_fails_on_existing_file(tmp_path) -> None:
target = tmp_path / "relay.bin"
target.write_bytes(b"existing")
with pytest.raises(dlp_io.DlpWriteError):
with dlp_io._PowerShellRelayRaw(str(target), "CreateNew"):
pass
def test_open_write_routes_through_relay_when_selected(monkeypatch, tmp_path) -> None:
monkeypatch.setattr(
dlp_io, "_select_write_channel", lambda suffix: dlp_io.WriteChannel.POWERSHELL
)
payload = bytes(range(256)) * 32
target = tmp_path / "routed.bin"
with dlp_io.open(target, "wb") as file:
file.write(payload)
assert target.read_bytes() == payload
def test_open_text_write_routes_through_relay(monkeypatch, tmp_path) -> None:
monkeypatch.setattr(
dlp_io, "_select_write_channel", lambda suffix: dlp_io.WriteChannel.POWERSHELL
)
payload = "中文内容\n第二行".encode("utf-8")
target = tmp_path / "routed.txt"
with dlp_io.open(target, "w", encoding="utf-8", newline="") as file:
file.write(payload.decode("utf-8"))
with dlp_io.open(target, "a", encoding="utf-8", newline="") as file:
file.write("追加")
assert target.read_bytes() == payload + "追加".encode("utf-8")
def test_open_exclusive_create_is_atomic_before_channel_selection(
monkeypatch, tmp_path
) -> None:
monkeypatch.setattr(
dlp_io,
"_select_write_channel",
lambda suffix: pytest.fail("existing target must fail before probing"),
)
target = tmp_path / "existing.bin"
target.write_bytes(b"data")
with pytest.raises(FileExistsError):
dlp_io.open(target, "xb")
assert target.read_bytes() == b"data"
def test_open_write_direct_channel_uses_native_open(monkeypatch, tmp_path) -> None:
monkeypatch.setattr(
dlp_io, "_select_write_channel", lambda suffix: dlp_io.WriteChannel.DIRECT
)
target = tmp_path / "direct.bin"
with dlp_io.open(target, "wb") as file:
assert not isinstance(file, dlp_io._PowerShellRelayRaw)
file.write(b"native")
assert target.read_bytes() == b"native"
def test_patched_open_write_uses_same_channel_routing(monkeypatch, tmp_path) -> None:
import builtins
monkeypatch.setattr(
dlp_io, "_select_write_channel", lambda suffix: dlp_io.WriteChannel.POWERSHELL
)
target = tmp_path / "patched.bin"
dlp_io.install_open_patch()
try:
with builtins.open(target, "wb") as file:
file.write(b"patched-write")
finally:
dlp_io.uninstall_open_patch()
assert target.read_bytes() == b"patched-write"