diff --git a/README.md b/README.md index c5093c1..c26ad1d 100644 --- a/README.md +++ b/README.md @@ -19,9 +19,11 @@ io-compatible file reads through an approved Python helper on Windows DLP hosts. - **读取始终明文**:打包 EXE(非白名单)经 stdin 注入 helper 源码拉起白名单 `python.exe`,由它读明文、经认证 Named Pipe 回传(python 按身份白名单, 任何父进程拉起都有效)。 -- **`is_encrypted(path)` 加密判定**:先比 certutil 原始哈希与当前进程视图哈希, - 不等即加密;相等时存在歧义(未加密,或 EXE 读加密文件),再比 helper 视图与 - 本地视图的前 64 KiB 定案——Python/pyd/EXE 三种环境都正确。 +- **`is_encrypted(path)` 加密判定**:比 `GetCompressedFileSizeW` 的物理大小与 helper + 报告的白名单逻辑大小——加密文件多一个 1,024 字节尾块,物理大于逻辑即加密,相等即 + 未加密。逻辑大小始终取自白名单 helper,所以不需要判断当前进程是否白名单, + Python/pyd/EXE 三种环境同一套代码。压缩/稀疏文件、helper 不可用等不结论的情况 + 回退到 certutil 内容比对;`DLP_IO_DETECT=content` 可强制内容比对。 - **写入始终未加密**:按文件后缀探测直写是否落盘明文(写探针文件后用 certutil 原始哈希校验);若直写会被加密,自动切换到 PowerShell stdin 管道中转写盘, 字节不落地任何临时文件;两通道均不可用则抛 `DlpWriteError`,绝不静默写密文。 diff --git a/dlp_io.py b/dlp_io.py index ebc5766..67edd94 100644 --- a/dlp_io.py +++ b/dlp_io.py @@ -4,6 +4,7 @@ from __future__ import annotations import atexit import builtins +import ctypes import errno import hashlib import io @@ -13,6 +14,7 @@ import os import queue import re import shutil +import stat import subprocess import tempfile import threading @@ -21,7 +23,7 @@ from enum import Enum from multiprocessing.context import AuthenticationError from multiprocessing.connection import Client -__version__ = "0.3.0" +__version__ = "0.4.0" __all__ = [ "DlpConfig", @@ -181,6 +183,19 @@ def handle_read(conn, request): stream.close() +def handle_stat(conn, request): + path = request.get("path") + if not isinstance(path, str) or not path: + error(conn, "invalid_path", "path must be a non-empty string") + return + try: + size = os.path.getsize(path) + except Exception as exc: + error(conn, "file_access", "%s: %s" % (type(exc).__name__, exc)) + return + send_json(conn, {"version": VERSION, "ok": True, "size": size}) + + def handle(conn): try: request = json.loads(conn.recv_bytes(maxlength=CONTROL_LIMIT).decode("utf-8")) @@ -205,6 +220,9 @@ def handle(conn): if operation == "read": handle_read(conn, request) return True + if operation == "stat": + handle_stat(conn, request) + return True if operation == "quit": send_json(conn, {"version": VERSION, "ok": True}) return False @@ -569,6 +587,25 @@ class DlpSession: raise DlpProtocolError(header.get("error", "ping failed")) return header + def stat_size(self, path) -> int: + """Logical size of a path as seen by the approved helper.""" + with self._state_lock: + self._ensure_open() + conn, header = self._request( + { + "version": PROTOCOL_VERSION, + "op": "stat", + "path": os.fsdecode(os.fspath(path)), + } + ) + conn.close() + if not header["ok"]: + raise OSError(header.get("error", "helper stat failed")) + size = header.get("size") + if isinstance(size, bool) or not isinstance(size, int) or size < 0: + raise DlpProtocolError("helper returned an invalid file size") + return size + def _open_conn(self, path: str, offset: int = 0): conn, header = self._request( { @@ -918,14 +955,107 @@ def uninstall_open_patch() -> None: # Encryption detection and unencrypted writes # # DLP transparent encryption stores ciphertext on disk. Approved processes -# (the whitelisted Python) see plaintext through the filter driver, while -# non-whitelisted tools such as certutil see the raw on-disk bytes. File -# attributes (attrib, ADS, size) are identical between encrypted and plain -# files, so content comparison is the only reliable discriminator. +# (the whitelisted Python helper) see plaintext through the filter driver, +# while non-whitelisted tools such as certutil see the raw on-disk bytes. +# +# Standard attributes (attrib, ADS) are identical between encrypted and plain +# files, but the on-disk size is not: DSOC keeps a fixed 1,024-byte trailer on +# encrypted files and the driver virtualises the logical size for approved +# readers. GetCompressedFileSizeW reports the physical size to every process, +# while the helper always reports the approved logical size, so that pair +# decides encryption without reading the file and without needing to know +# whether the *current* process is approved. +# +# Content comparison remains the authoritative fallback: compressed or sparse +# files (physical below logical), hosts whose encryption adds no trailer, and +# an unavailable helper all fall through to it, and DLP_IO_DETECT=content +# forces it. _DETECT_HEAD_SIZE = 64 * 1024 _RAW_HASH_PATTERN = re.compile(rb"^[ \t]*([0-9a-fA-F]{64})[ \t\r]*$", re.MULTILINE) +_DETECT_ENV = "DLP_IO_DETECT" +_DETECT_AUTO = "auto" +_DETECT_CONTENT = "content" + +_compressed_size_lock = threading.Lock() +_compressed_size_entry = None + + +def _compressed_size_api(): + """Lazily bind GetCompressedFileSizeW (physical size, never virtualised).""" + global _compressed_size_entry + with _compressed_size_lock: + if _compressed_size_entry is None: + from ctypes import wintypes + + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + entry = kernel32.GetCompressedFileSizeW + entry.restype = wintypes.DWORD + entry.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(wintypes.DWORD)] + _compressed_size_entry = entry + return _compressed_size_entry + + +def _physical_size(path): + """Bytes actually occupied on disk, bypassing DLP size virtualisation.""" + if os.name != "nt": + return None + from ctypes import wintypes + + entry = _compressed_size_api() + high = wintypes.DWORD(0) + ctypes.set_last_error(0) + low = entry(path, ctypes.byref(high)) + if low == 0xFFFFFFFF and ctypes.get_last_error() != 0: + return None + return (high.value << 32) | low + + +def _helper_size(path) -> int: + """Logical size of the file as seen by the approved helper.""" + return _get_default_session().stat_size(path) + + +def _detect_mode() -> str: + raw = os.environ.get(_DETECT_ENV) + if raw is None or not raw.strip(): + return _DETECT_AUTO + value = raw.strip().lower() + if value in (_DETECT_AUTO, _DETECT_CONTENT): + return value + raise DlpConfigurationError( + "%s must be %r or %r, not %r" % (_DETECT_ENV, _DETECT_AUTO, _DETECT_CONTENT, raw) + ) + + +def _size_verdict(path): + """Decide encryption from the physical/logical size delta, or return None. + + A positive delta means ciphertext plus trailer is on disk, so the answer is + conclusive whatever identity the calling process has. An equal pair means + no trailer was stored. Anything else (compressed, sparse, unavailable + helper, non-regular file) is left to content comparison. + """ + physical = _physical_size(path) + if physical is None: + return None + try: + info = os.stat(path) + except OSError: + return None + if not stat.S_ISREG(info.st_mode): + return None + try: + logical = _helper_size(path) + except (DlpIoError, OSError): + return None + if physical > logical: + return True + if physical == logical: + return False + return None + def _raw_sha256(path) -> bytes: """SHA-256 of the raw on-disk bytes, read by non-whitelisted certutil. @@ -973,26 +1103,39 @@ def _helper_head(path, size) -> bytes: raw.close() +def _content_verdict(path) -> bool: + """Compare the raw on-disk digest with what the current process sees.""" + native_hash = _native_sha256(path) + raw_hash = _raw_sha256(path) + if raw_hash != native_hash: + return True + return _helper_head(path, _DETECT_HEAD_SIZE) != _native_head( + path, _DETECT_HEAD_SIZE + ) + + def is_encrypted(path) -> bool: """Return True when the file on disk holds DLP ciphertext. - The raw on-disk digest (certutil) is compared with what the current - process sees. A mismatch means the file is encrypted and the current - process is approved. When both match the result is ambiguous — the file - is either plain, or encrypted while the current process is not approved - (packaged .exe) — so the first bytes seen by the approved helper are - compared with the first bytes seen by the current process. + The physical on-disk size is compared with the logical size reported by the + approved helper. Encrypted files carry a fixed trailer that approved readers + do not see, so a positive delta is conclusive and an equal pair means plain. + Because the logical side always comes from the approved helper, the result + does not depend on whether the *current* process is approved — which is what + makes it work from a packaged .exe as well as from Python. + + Compressed or sparse files, hosts without the size trailer, and an + unavailable helper fall back to comparing the raw on-disk digest with the + current process view. Set DLP_IO_DETECT=content to force that comparison. """ if os.name != "nt": return False normalized = os.fsdecode(os.fspath(path)) - native_hash = _native_sha256(normalized) - raw_hash = _raw_sha256(normalized) - if raw_hash != native_hash: - return True - return _helper_head(normalized, _DETECT_HEAD_SIZE) != _native_head( - normalized, _DETECT_HEAD_SIZE - ) + if _detect_mode() == _DETECT_AUTO: + verdict = _size_verdict(normalized) + if verdict is not None: + return verdict + return _content_verdict(normalized) class WriteChannel(str, Enum): diff --git a/docs/DLP_DSOC_API_NOTES.md b/docs/DLP_DSOC_API_NOTES.md new file mode 100644 index 0000000..d49209b --- /dev/null +++ b/docs/DLP_DSOC_API_NOTES.md @@ -0,0 +1,218 @@ +# DSOC 加密状态前置判断调研 + +本机 DLP 产品为 **DSOC(亿赛通数据安全)**,安装于 `C:\Program Files (x86)\DSOC`。 +本文记录"加密文件属性"页签的真实来源、厂商 API 路线为何不可用,以及最终找到的 +标准 Win32 API 前置判断方案。 + +> 状态:调研完成。 +> 结论:厂商内部 API 路线不可行(依赖模块在本机缺失,且关键函数未导出); +> 改用 `GetCompressedFileSizeW` 读取物理大小与逻辑大小之差,O(1) 且 +> 与现有 certutil 判定在全部抽检样本上一致。 + +## 一、现象 + +`tests/DLP加密文件.xlsx` 的资源管理器属性对话框里有额外的「加密文件属性」页签, +显示"文件安全域"和"用户对文件权限(可否打开/打印/解密/调整)"; +`tests/DLP解密文件.pptx` 没有该页签。 + +## 二、页签归属 + +属性页由 DSOC 的 shell 扩展提供: + +| 项 | 值 | +|----|----| +| 注册位置 | `HKEY_CLASSES_ROOT\*\shellex\PropertySheetHandlers\{A99D5B0F-A7FD-4186-B0BD-F2D237D31FF8}` | +| 实现 DLL | `C:\Program Files (x86)\DSOC\DSM\DGFileProperty64.dll` | +| 同目录另有 | `DocLableShellExt64.dll`(`{00683b60-...}`,文档标签页) | + +关键点:注册在 `*`(所有文件)上,**不是**按 `.xlsx` / `.pptx` 分别注册 +(`.xlsx`、`.pptx`、`.xls`、`.docx` 下均无 `PropertySheetHandlers` 子键)。 +所以页签"出现/不出现"不是注册表决定的,而是运行时判定后 `HidePropertyTab`。 + +## 三、显示逻辑 + +`DGFileProperty64.dll` 只静态导入系统 DLL(SHLWAPI/KERNEL32/USER32/ADVAPI32/ +ole32/SHELL32/OLEAUT32/COMCTL32),其余模块全部 `LoadLibraryW` + `GetProcAddress` +动态解析。其字符串常量直接暴露了判定逻辑: + +``` +CDGShellExt::Initialize +HidePropertyTab +CDGShellExt::AddPages +file: %s type: [%d] +CreatePropertySheetPage +.IsCryptedFile +GetEncryptFileType +``` + +即 `CDGShellExt::IsCryptedFile` 调 `GetEncryptFileType(path)` 拿到 `type`, +据此决定是否隐藏页签。这解释了"加密 xlsx 有页签、明文 pptx 没页签"。 + +## 四、为什么它不是"文件属性" + +页签在 `explorer.exe` 进程内、打开属性对话框时才渲染,数据由 DLP 客户端 +(驱动 + 服务)实时提供。文件系统层面没有承载: + +- `dir /r` 无附加数据流(ADS) +- 标准属性位(含 EFS 的 `E`)无差异 +- 文件大小对同一进程的不同 API 甚至不一致(见第七节) + +因此不存在"读一下属性就知道"的**标准属性**通道,只能去复用其背后的取数逻辑。 + +## 五、已排除/不适用的其他通道 + +| 通道 | 结论 | +|------|------| +| `common\AuthrizeFileDatabase.db` | `FILE_COMMON_INFO` 含 `security_name`/`security_id`(正对应"文件安全域"),但只登记**自认证**文件,实测 0 行 | +| Shell 属性系统(PropertyStore) | `PropertySystem\PropertyHandlers\.xlsx` / `.pptx` 均不存在,没有属性处理器,`IPropertyStore` 读不到自定义属性 | +| 标准 Win32 属性 | 无差异,见第四节 | + +## 六、厂商 API 路线:不可用 + +### 6.1 依赖链 + +`explorer.exe` 里加载的 DLP 模块只有: +`DGCore64.dll`、`ClientConfig64.dll`、`PublicLog64.dll`、`XGKernel64.dll`、 +`CommonSDK64.dll`、`Observer64.dll`、`SecDocExp64.dll`、`BrowerUrlMonitor64.dll`、 +`DGIEAddin64.dll`、`DGRightMenu64.dll`。 + +`SecDocExp64.dll` 的日志字符串显示内部流程: + +``` +GetProcAddress EFS_GetKernalFileAttributeExW failed=%d +GetEncryptFileType explorer dwCurFileType=%d +GetFileTypeFromWbsecdoc explorer dwCurFileType failed +GetFileTypeFromWbsecdoc Filename =%s, FieType=%d, FileLevel=%d +[Debug]LoadSpsVerf.has been loaded +SPSVerf.dll +\csssp\bin\x64 +``` + +即 `GetEncryptFileType` → `GetFileTypeFromWbsecdoc` → 需要 `SecureDoc.dll` / +`SPSVerf.dll`(从 `\csssp\bin\x64` 加载)。 + +### 6.2 关键结论:依赖模块在本机不存在 + +全盘搜索 `SecureDoc.dll`、`SPSVerf.dll`(System32 / SysWOW64 / DSOC / +Common Files)**均不存在**。也就是说这条取数链在本机是降级/假实现的, +这也解释了下面的实测结果。 + +`GetEncryptFileType` 本身在 DSOC 全树中**没有任何模块按名导出** +(对 DSOC 下所有 dll/exe 导出表扫描,0 命中)。`DGCore64.dll` 只有 1 个 +匿名(仅序数)导出,是另一个不透明入口。 + +### 6.3 `EFS_*` 导出实测 + +参数个数由导出函数入口的 x64 序言确定(`mov [rsp+8],rcx` / `[rsp+0x10],rdx` / +`[rsp+0x18],r8` / `[rsp+0x20],r9` 的出现情况): + +| 导出 | 参数个数 | 实测结果 | +|------|----------|----------| +| `EFS_GetFileTypeW(path)` | 1 | 已存在文件一律 `1`,不存在 `2`,**无法区分加密/明文** | +| `EFS_GetFileTypeAndLevelW(path, int*, int*)` | 3 | 全部 `rc=2, type=-1, level=0` | +| `EFS_JudgeFileKeyW(path)` | 1 | 已存在 `2`,不存在 `1` | +| `EFS_GetFileLevelW(path)` | 1 | 一律 `1` | +| `EFS_GetFileDecryptedStatusW(path, ...)` | 4 | ctypes 签名写错即 `access violation`,进程崩溃 | + +对加密 xlsx 与明文 pptx 返回完全相同的值,说明这些导出在本机不提供加密状态。 + +> 风险提示:ctypes 猜签名会直接崩进程。任何试探必须放在一次性子进程里, +> 不能进库的常规路径。 + +## 七、可行替代:物理大小差(标准 Win32 API) + +### 7.1 原理 + +DSOC 的透明加密会在文件尾部附加 **1024 字节**加密数据块,并让驱动对白名单 +读者**虚拟化逻辑大小**。`GetCompressedFileSizeW` 返回的是文件系统实际占用 +(物理)大小,绕过该虚拟化: + +``` +物理大小 > 逻辑大小 → 磁盘上存在加密尾块 → 文件已加密 +``` + +纯本地、O(1)、无子进程、无厂商依赖,且在同一进程内同时拿到两个数字即可比较。 + +### 7.2 实测(`tests` 与桌面样本) + +| 文件 | 逻辑大小 | 物理大小 | 差 | `is_encrypted()` | +|------|----------|----------|----|------------------| +| `tests/DLP加密文件.xlsx` | 53,334 | 54,358 | +1024 | True | +| `tests/DLP解密文件.pptx` | 2,466,572 | 2,466,572 | 0 | False | +| `dlp_io.py` | 38,597 | 38,597 | 0 | False | +| `README.md` | 3,984 | 3,984 | 0 | False | +| `PrefectDemo/D01.ExcelDemo.py` | 4,781 | 5,805 | +1024 | True | +| `PrefectDemo/input_sales.xlsx` | 5,294 | 6,318 | +1024 | True | +| `PrefectDemo/output_sales_report.xlsx` | 5,974 | 6,998 | +1024 | True | +| `~$临时文件.pptx`(锁文件) | 165 | 1,189 | +1024 | True | +| `TestHub讲义.pptx` | 9,713,184 | 9,714,208 | +1024 | True | +| `...验证材料.pptx` | 573,145 | 574,169 | +1024 | True | +| `...验证材料.pdf` | 616,782 | 617,806 | +1024 | True | + +结论:尾块恒定为 1024 字节,与文件大小、扩展名无关;抽检 11/11 与 +`is_encrypted()` 完全一致。 + +### 7.3 分布统计 + +对 `D:\WorkSpace\PythonWork\dlp-io`、桌面、文档三个目录(深度 3)扫描 263 个文件: + +- 差值非 0:10 个,**全部恰为 +1024** +- 差值 0:253 个 + +注意被加密的不只是 Office 文档,`.py`、`.pdf` 同样会被加密。 + +### 7.4 边界与风险 + +| 情况 | 处理 | +|------|------| +| NTFS 压缩文件 | 物理 < 逻辑,不能判为加密,需回退慢路径 | +| 稀疏文件 | 物理 < 逻辑,同上 | +| `GetCompressedFileSizeW` 失败 | 回退慢路径 | +| 策略改为无尾块的加密模式 | 会出现漏判(`docs/DLP_ENVIRONMENT_NOTES.md` 里旧的 pptx 样本对记录为"同尺寸"),因此该方案只适合作为**快路径**,慢路径保留 | + +## 八、集成方式(已实现) + +`is_encrypted()` 的主判据改为物理大小与 helper 逻辑大小的差,原内容比对降为回退: + +``` +physical = GetCompressedFileSizeW(path) # 恒为物理大小 +logical = helper.stat_size(path) # 恒为白名单逻辑大小 + +physical > logical -> True # 存在 1024 字节加密尾块 +physical == logical -> False # 无尾块 +physical < logical -> 回退 certutil 内容比对 # NTFS 压缩 / 稀疏文件 +helper 不可用 -> 回退 certutil 内容比对 +DLP_IO_DETECT=content -> 跳过大小判定,强制内容比对 +``` + +**关键设计点:逻辑大小一律由 helper 提供,而不是用当前进程的 `stat`。** +这样根本不需要判断"当前进程是不是白名单"—— + +- 白名单进程(Python / pyd):本地 `stat` 就是逻辑大小,与 helper 一致。 +- 非白名单进程(打包 EXE):本地 `stat` 会变成物理大小,但 helper 仍是逻辑大小, + 差值照样成立。 + +原设计考虑过"先判定进程身份再决定是否相信 `stat`",那需要在启动时探测或找 +一个已知加密的对照文件,两者都不可靠(明文文件对任何身份都返回相同结果, +探测不出来;对照文件无法保证存在,本库也造不出密文)。以 helper 为锚点后 +这部分复杂度完全消失。 + +`GetCompressedFileSizeW` 是唯一需要 `ctypes` 的地方,`GetCompressedFileSizeW` +失败(网络盘、无权限)返回 `None` 并回退。 + +实测收益:加密样本 `is_encrypted` 从 665 ms(内容比对)降到约 10 ms;helper +首次启动的 1.3 s 是一次性开销,实际读取本来也需要它。 + +## 九、样本事实更新(与旧文档冲突) + +`docs/DLP_ENVIRONMENT_NOTES.md` 第一节记录的"加密与明文样本同尺寸、无附加头尾" +来自旧的 pptx 样本对,对当前 fixture 已不成立:当前加密样本 raw 视图比明文多 +1,024 字节(见 7.2)。 + +raw 视图前 16 字节为 `181b031a1510197c0a190e7c6f726c5f`,与旧文档记录的密文头 +一致。raw 视图尾部 1,024 字节是高熵数据块(大量 `0x60`,长 0x00 明文段异或出的 +密钥流),不是明文可解析的头部/元数据。 + +另外:同一非白名单进程内 `stat -c %s` 报 54,358 而 `wc -c` 报 53,334, +进一步印证驱动对不同 API 做了尺寸虚拟化——所以"比大小"必须用 +`GetCompressedFileSizeW` 对比 `stat` 的逻辑大小,不能拿两个不同的 size API 互比。 diff --git a/docs/DLP_ENVIRONMENT_NOTES.md b/docs/DLP_ENVIRONMENT_NOTES.md index ca48402..ce488c8 100644 --- a/docs/DLP_ENVIRONMENT_NOTES.md +++ b/docs/DLP_ENVIRONMENT_NOTES.md @@ -18,16 +18,29 @@ 特征:同尺寸、全文流式加密、无附加文件头/尾、无静态 magic 可识别。 -## 二、文件属性层面无法区分(重要结论) +> 更正(2026-11):上述"同尺寸、无附加文件头/尾"只对当时的 pptx 样本对成立。 +> 当前 fixture(加密 `tests/DLP加密文件.xlsx` + 明文 `tests/DLP解密文件.pptx`) +> 的加密文件在磁盘上比明文**多 1,024 字节**,详见 +> `docs/DLP_DSOC_API_NOTES.md` 第七、九节。据此已找到 O(1) 的前置判断通道。 -对两个样本逐项对比,全部一致: +## 二、文件属性层面无法区分标准属性,但可区分物理大小 + +对两个样本逐项对比,以下全部一致: - `attrib`:都只有 `A` 属性(无 EFS 的 E 属性等差异) - `dir /r`:均无附加数据流(ADS) -- 文件大小、时间戳:一致 +- 时间戳:一致 -**结论:无法通过任何文件元数据判断加密状态,唯一可靠的判别特征是内容。** -这正是 `is_encrypted()` 采用内容对比的原因。 +**结论:标准文件属性无法判断加密状态。** + +但**物理大小**可以:DSOC 的加密文件在磁盘上带固定的 1,024 字节尾块,而驱动 +对白名单读者虚拟化逻辑大小。用 `GetCompressedFileSizeW`(物理)与 `stat` +(逻辑)相减即可 O(1) 判定,无需读内容、无需子进程。实测抽检 11/11 与本节 +原有的内容比对结论一致,263 个文件扫描中所有加密文件差值恒为 +1024。 +完整证据、边界与集成建议见 `docs/DLP_DSOC_API_NOTES.md`。 + +内容比对仍是权威慢路径(压缩/稀疏文件、异常情况回退时使用), +也是 `is_encrypted()` 现有实现的基准。 ## 三、进程白名单模型(实测矩阵) @@ -86,10 +99,28 @@ DLP 透明加密按「进程身份」决定是否介入读写。用「读取加 ## 五、is_encrypted() 判定逻辑 -判据:文件已加密 ⟺ 白名单视图 ≠ 非白名单(raw)视图。 +主判据(0.4.0 起):**物理大小 > helper(白名单)视角的逻辑大小**。 -难点:当前进程自身是否白名单是未知的(Python/pyd 是白名单,打包 EXE 不是), -单次对比存在歧义。`dlp_io.is_encrypted(path)` 用两阶段消歧: +DSOC 在加密文件的磁盘数据后保留固定的 1,024 字节尾块,同时驱动对白名单读者 +虚拟化逻辑大小。`GetCompressedFileSizeW` 对任何进程都返回物理大小,helper 永远 +返回白名单视角的逻辑大小——两侧一减即可判定,**不需要知道当前进程是否白名单**, +所以 Python 与打包 EXE 共用同一套代码。 + +``` +physical = GetCompressedFileSizeW(path) # 恒为物理大小 +logical = helper.stat_size(path) # 恒为白名单逻辑大小 + +physical > logical -> True # 存在加密尾块 +physical == logical -> False # 无尾块 +physical < logical -> 回退内容比对 # NTFS 压缩 / 稀疏文件 +helper 不可用 -> 回退内容比对 +DLP_IO_DETECT=content -> 跳过大小判定,强制内容比对 +``` + +成本:一次管道 stat + 一次 syscall;实测加密样本约 10 ms,同一文件走内容比对 +约 665 ms。 + +回退路径(内容比对,仅在大小判定不结论时执行): ``` h_raw = certutil -hashfile(path) # 非白名单 raw 视图(经 cmd /c 中转) @@ -108,11 +139,12 @@ return head_helper != head_native | 环境 | 加密文件 | 未加密文件 | |------|----------|------------| -| Python / pyd(白名单) | 阶段一即判定 True | 阶段二两视图一致 → False | -| 打包 EXE(非白名单) | 阶段一相等(都看到密文)→ 阶段二 helper 明文头 ≠ 本地密文头 → True | 阶段二一致 → False | +| Python / pyd(白名单) | 大小差即判定 True | 大小相等 → False | +| 打包 EXE(非白名单) | 本地 stat 变成物理大小,但 helper 仍是逻辑大小,大小差照样成立 → True | 大小相等 → False | -代价:未加密文件需一次完整 certutil 哈希 + 一次本地完整读取 + helper 前 64 KiB -读取;大文件应缓存结果。库故意不引入「期望 magic 表」——内容对比与文件类型无关。 +已知风险:若 DLP 策略改成"无尾块加密"(本文第一节的旧 pptx 样本对就是同尺寸), +大小判定会把加密文件漏判成明文——此时用 `DLP_IO_DETECT=content` 强制内容比对。 +库故意不引入「期望 magic 表」——大小与内容两条判据都与文件类型无关。 ## 六、未加密写入通道选择逻辑 diff --git a/docs/DLP_IO_LIBRARY.md b/docs/DLP_IO_LIBRARY.md index 2cec2b7..94a4954 100644 --- a/docs/DLP_IO_LIBRARY.md +++ b/docs/DLP_IO_LIBRARY.md @@ -2,9 +2,9 @@ `dlp-io` 为 Windows DLP 透明加密环境提供接近 `io.open` 的 Python 文件 API。非白名单进程负责业务逻辑;文件读取由已获 DLP 白名单授权的 Python helper 完成,再通过经过认证的 Windows Named Pipe 返回明文字节;文件写入通过通道探测保证落盘为未加密格式。另提供 `is_encrypted()`,在读取前判断文件是否处于 DLP 加密状态。 -当前版本为 `dlp-io==0.3.0`,distribution 名是 `dlp-io`,import 名是 `dlp_io`。 +当前版本为 `dlp-io==0.4.0`,distribution 名是 `dlp-io`,import 名是 `dlp_io`。 -DLP 环境的实测特征(白名单矩阵、密文样本字节对比、各写入候选通道的可用性实验)与判定/写入逻辑的完整推导记录见 [DLP_ENVIRONMENT_NOTES.md](DLP_ENVIRONMENT_NOTES.md)。 +DLP 环境的实测特征(白名单矩阵、密文样本字节对比、各写入候选通道的可用性实验)与判定/写入逻辑的完整推导记录见 [DLP_ENVIRONMENT_NOTES.md](DLP_ENVIRONMENT_NOTES.md);DSOC 属性页与厂商 API 的调研记录见 [DLP_DSOC_API_NOTES.md](DLP_DSOC_API_NOTES.md)。 ## 安装 @@ -13,7 +13,7 @@ DLP 环境的实测特征(白名单矩阵、密文样本字节对比、各写 registry 已开放匿名下载,一条命令即可安装;pip 会自动选择最匹配的 wheel:Windows 上 CPython 3.10–3.14 会得到对应的 pyd wheel(整个库编译为单个 `.pyd`),3.8/3.9 及其余环境得到纯 Python wheel(库要求 Python >= 3.8,pyd 版仅覆盖 CI 预装的解释器版本)。 ```powershell -py -m pip install --index-url https://gitea.docker.antior.cn/api/packages/antior/pypi/simple dlp-io==0.3.0 +py -m pip install --index-url https://gitea.docker.antior.cn/api/packages/antior/pypi/simple dlp-io==0.4.0 ``` Package 页面: @@ -105,9 +105,13 @@ else: data = stream.read() ``` -判断原理:DLP 透明加密在磁盘上存密文,白名单进程读到明文、非白名单工具(certutil)读到原始盘内字节;加密文件与未加密文件的 attrib 属性、ADS、大小完全一致,只有内容可区分。`is_encrypted()` 先比较 certutil 原始哈希与当前进程视图哈希:不一致则文件已加密且当前进程是白名单;一致时存在歧义(文件未加密,或文件已加密但当前进程是非白名单 EXE),再比较 helper 视图与当前进程视图的前 64 KiB 定案。两种运行环境(Python/pyd 与打包 EXE)结果都正确。 +判断原理:DSOC 在加密文件的磁盘数据之后保留固定的 1,024 字节尾块,同时驱动对白名单读者虚拟化逻辑大小。`GetCompressedFileSizeW` 对任何进程都返回物理大小,而 helper 永远返回白名单视角的逻辑大小,两者相减即可判定——**不需要判断当前进程是否为白名单**,所以 Python/pyd 与打包 EXE 共用同一套代码:物理大于逻辑 → 已加密,相等 → 未加密。 -代价:未加密文件需要一次完整 certutil 哈希、一次本地完整读取和一次 helper 前 64 KiB 读取;大文件请缓存判断结果,不要每次读取前重复调用。helper 未启动时会复用懒加载的默认 session,结束后照常 `dlp_io.shutdown()`。非 Windows 平台直接返回 `False`。 +回退路径:NTFS 压缩或稀疏文件(物理小于逻辑)、`GetCompressedFileSizeW` 失败、helper 不可用时,退回内容比对——比较 certutil 读到的原始盘内字节哈希与当前进程视图哈希,不一致即已加密;一致时再比较 helper 与当前进程读到的前 64 KiB 定案。 + +代价:主路径只是一次 helper stat 管道往返加一次 syscall(实测约 10 ms,同一文件走内容比对约 665 ms),不再有全文件哈希。helper 未启动时会复用懒加载的默认 session,结束后照常 `dlp_io.shutdown()`。非 Windows 平台直接返回 `False`。 + +如需强制走内容比对(例如 DLP 策略改成不保留尾块的加密方式),设 `DLP_IO_DETECT=content`;默认为 `auto`。 ## 未加密写入 diff --git a/tests/DLP加密文件.pptx b/tests/DLP加密文件.pptx deleted file mode 100644 index ee7aed4..0000000 Binary files a/tests/DLP加密文件.pptx and /dev/null differ diff --git a/tests/DLP加密文件.xlsx b/tests/DLP加密文件.xlsx new file mode 100644 index 0000000..7d984d5 Binary files /dev/null and b/tests/DLP加密文件.xlsx differ diff --git a/tests/test_dlp_io_encryption.py b/tests/test_dlp_io_encryption.py index f5eb725..4c60501 100644 --- a/tests/test_dlp_io_encryption.py +++ b/tests/test_dlp_io_encryption.py @@ -12,13 +12,14 @@ 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加密文件.pptx" +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() @@ -88,6 +89,112 @@ def test_is_encrypted_ambiguous_case_compares_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