peobf 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
peobf-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 gem3match-dev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
peobf-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,140 @@
1
+ Metadata-Version: 2.4
2
+ Name: peobf
3
+ Version: 1.0.0
4
+ Summary: Detect XOR-style obfuscation in PE sections by disassembly coverage, because Shannon entropy is blind to bijections.
5
+ Author: gem3match-dev
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/gem3match-dev/pe-obfuscation-detection
8
+ Project-URL: Repository, https://github.com/gem3match-dev/pe-obfuscation-detection
9
+ Keywords: pe,obfuscation,entropy,reverse-engineering,malware-analysis,capstone,windows
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Topic :: Security
14
+ Classifier: Topic :: Software Development :: Disassemblers
15
+ Classifier: Intended Audience :: Developers
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: pefile>=2023.2.7
20
+ Requires-Dist: capstone>=5.0
21
+ Dynamic: license-file
22
+
23
+ # peobf
24
+
25
+ Detect XOR-style obfuscation in PE sections by **disassembly coverage**, because Shannon entropy is blind to bijections.
26
+
27
+ ```
28
+ pip install peobf
29
+ peobf check C:\Windows\System32\version.dll
30
+ ```
31
+
32
+ ## The problem
33
+
34
+ Most packer/obfuscation detectors threshold on Shannon entropy: above ~7.0 means "compressed or encrypted". That test misses the most common cheap obfuscation there is.
35
+
36
+ XOR is a **bijection** — it permutes the byte-value labels one-to-one. Shannon entropy is computed from the multiset of byte frequencies, so the entropy is *exactly* unchanged:
37
+
38
+ ```
39
+ H(XOR(data, k)) == H(data) for every key k
40
+ ```
41
+
42
+ Measured on real Windows binaries:
43
+
44
+ ```
45
+ C:\Windows\System32\version.dll .text 12,288 bytes
46
+
47
+ case entropy disassembly coverage
48
+ original 5.4067 100.00%
49
+ xor 0x5A 5.4067 2.54%
50
+ xor 0xFF 5.4067 0.69%
51
+ xor 0x01 5.4067 0.13%
52
+ permuted 5.4067 0.41%
53
+ ```
54
+
55
+ Entropy delta on every transformed row: **+0.0000**. A tool that only measures entropy reports "normal" for a section whose code is entirely undecodable.
56
+
57
+ ```
58
+ C:\Windows\System32\advapi32.dll .text 471,040 bytes
59
+
60
+ case entropy disassembly coverage
61
+ original 6.2347 22.14%
62
+ xor 0x5A 6.2347 0.00%
63
+ xor 0xFF 6.2347 0.00%
64
+ permuted 6.2347 0.01%
65
+ ```
66
+
67
+ ## What peobf measures instead
68
+
69
+ **Decodable instruction coverage**: start a disassembler at the section base and count what fraction of bytes valid instructions consume.
70
+
71
+ - Real x64 code is typically 20–100% (not 100% — alignment padding and inline data sit between functions).
72
+ - XOR-obfuscated code drops to **0.00%**: the decoder cannot form a single valid instruction.
73
+
74
+ That gap is the signal. It needs no key, no unpacking, no execution.
75
+
76
+ ## Usage
77
+
78
+ ```bash
79
+ # 快速看所有节区(不反汇编,毫秒级)
80
+ peobf sections suspicious.dll
81
+
82
+ # 深入分析一个节区
83
+ peobf check suspicious.dll --section .text
84
+ ```
85
+
86
+ `check` prints the entropy and coverage for the original plus four bijective transforms, then gives a verdict:
87
+
88
+ | verdict | meaning |
89
+ |---|---|
90
+ | `looks_normal` | section decodes normally; no obfuscation evidence |
91
+ | `possibly_encrypted` | coverage <5% **and** entropy >6 |
92
+ | `undecodable_low_entropy` | coverage <5% but entropy low — transformed, or filled with data |
93
+
94
+ ## As a library
95
+
96
+ ```python
97
+ from peobf import section_report, summarize
98
+
99
+ rep = section_report(r"C:\Windows\System32\version.dll", ".text")
100
+ s = summarize(rep)
101
+
102
+ print(s["verdict"]) # looks_normal
103
+ print(s["base_coverage"]) # 1.0
104
+ print(s["entropy_blind_cases"]) # 4 ← transforms entropy missed entirely
105
+ ```
106
+
107
+ `list_sections(path)` returns name / VA / raw size / entropy / permissions for every section without disassembling.
108
+
109
+ ## Real section layout, for calibration
110
+
111
+ `advapi32.dll` (778,352 bytes, PE32+, 8 sections):
112
+
113
+ ```
114
+ name VA raw size entropy perms
115
+ .text 0x1000 471,040 6.2347 RX
116
+ fothk 0x74000 4,096 0.0159 RX
117
+ .rdata 0x75000 233,472 4.6996 R
118
+ .data 0xae000 12,288 0.8552 RW
119
+ .pdata 0xb3000 20,480 5.2377 R
120
+ .didat 0xb8000 4,096 1.2959 RW
121
+ .rsrc 0xb9000 4,096 1.6339 R
122
+ .reloc 0xba000 8,192 5.0584 R
123
+ ```
124
+
125
+ Both directions of false positive are real. `fothk` has entropy **0.0159** — near zero because it is a jump table of identical stubs. Entropy flags nothing; coverage would flag it as suspicious because almost nothing decodes. Reading it shows it is benign. That is why the verdict combines both numbers instead of thresholding one.
126
+
127
+ ## Limits — read before trusting it
128
+
129
+ - **Does not recover the key.** Single-byte XOR is trivially brute-forced (try 255 keys, score coverage); longer keys and block ciphers need real work.
130
+ - **Does not prove maliciousness.** Protectors and packers obfuscate legitimately. The measurement says "this code is not decodable as-is", nothing more.
131
+ - **Coverage near 0 can be benign** if a section legitimately holds data with code-like flags. Check permissions and the section name before concluding.
132
+ - **Only PE.** ELF/Mach-O need different parsers; the coverage idea transfers, the code does not.
133
+
134
+ ## Requirements
135
+
136
+ Python 3.9+. `pefile` and `capstone` are installed as dependencies.
137
+
138
+ ## License
139
+
140
+ MIT
peobf-1.0.0/README.md ADDED
@@ -0,0 +1,118 @@
1
+ # peobf
2
+
3
+ Detect XOR-style obfuscation in PE sections by **disassembly coverage**, because Shannon entropy is blind to bijections.
4
+
5
+ ```
6
+ pip install peobf
7
+ peobf check C:\Windows\System32\version.dll
8
+ ```
9
+
10
+ ## The problem
11
+
12
+ Most packer/obfuscation detectors threshold on Shannon entropy: above ~7.0 means "compressed or encrypted". That test misses the most common cheap obfuscation there is.
13
+
14
+ XOR is a **bijection** — it permutes the byte-value labels one-to-one. Shannon entropy is computed from the multiset of byte frequencies, so the entropy is *exactly* unchanged:
15
+
16
+ ```
17
+ H(XOR(data, k)) == H(data) for every key k
18
+ ```
19
+
20
+ Measured on real Windows binaries:
21
+
22
+ ```
23
+ C:\Windows\System32\version.dll .text 12,288 bytes
24
+
25
+ case entropy disassembly coverage
26
+ original 5.4067 100.00%
27
+ xor 0x5A 5.4067 2.54%
28
+ xor 0xFF 5.4067 0.69%
29
+ xor 0x01 5.4067 0.13%
30
+ permuted 5.4067 0.41%
31
+ ```
32
+
33
+ Entropy delta on every transformed row: **+0.0000**. A tool that only measures entropy reports "normal" for a section whose code is entirely undecodable.
34
+
35
+ ```
36
+ C:\Windows\System32\advapi32.dll .text 471,040 bytes
37
+
38
+ case entropy disassembly coverage
39
+ original 6.2347 22.14%
40
+ xor 0x5A 6.2347 0.00%
41
+ xor 0xFF 6.2347 0.00%
42
+ permuted 6.2347 0.01%
43
+ ```
44
+
45
+ ## What peobf measures instead
46
+
47
+ **Decodable instruction coverage**: start a disassembler at the section base and count what fraction of bytes valid instructions consume.
48
+
49
+ - Real x64 code is typically 20–100% (not 100% — alignment padding and inline data sit between functions).
50
+ - XOR-obfuscated code drops to **0.00%**: the decoder cannot form a single valid instruction.
51
+
52
+ That gap is the signal. It needs no key, no unpacking, no execution.
53
+
54
+ ## Usage
55
+
56
+ ```bash
57
+ # 快速看所有节区(不反汇编,毫秒级)
58
+ peobf sections suspicious.dll
59
+
60
+ # 深入分析一个节区
61
+ peobf check suspicious.dll --section .text
62
+ ```
63
+
64
+ `check` prints the entropy and coverage for the original plus four bijective transforms, then gives a verdict:
65
+
66
+ | verdict | meaning |
67
+ |---|---|
68
+ | `looks_normal` | section decodes normally; no obfuscation evidence |
69
+ | `possibly_encrypted` | coverage <5% **and** entropy >6 |
70
+ | `undecodable_low_entropy` | coverage <5% but entropy low — transformed, or filled with data |
71
+
72
+ ## As a library
73
+
74
+ ```python
75
+ from peobf import section_report, summarize
76
+
77
+ rep = section_report(r"C:\Windows\System32\version.dll", ".text")
78
+ s = summarize(rep)
79
+
80
+ print(s["verdict"]) # looks_normal
81
+ print(s["base_coverage"]) # 1.0
82
+ print(s["entropy_blind_cases"]) # 4 ← transforms entropy missed entirely
83
+ ```
84
+
85
+ `list_sections(path)` returns name / VA / raw size / entropy / permissions for every section without disassembling.
86
+
87
+ ## Real section layout, for calibration
88
+
89
+ `advapi32.dll` (778,352 bytes, PE32+, 8 sections):
90
+
91
+ ```
92
+ name VA raw size entropy perms
93
+ .text 0x1000 471,040 6.2347 RX
94
+ fothk 0x74000 4,096 0.0159 RX
95
+ .rdata 0x75000 233,472 4.6996 R
96
+ .data 0xae000 12,288 0.8552 RW
97
+ .pdata 0xb3000 20,480 5.2377 R
98
+ .didat 0xb8000 4,096 1.2959 RW
99
+ .rsrc 0xb9000 4,096 1.6339 R
100
+ .reloc 0xba000 8,192 5.0584 R
101
+ ```
102
+
103
+ Both directions of false positive are real. `fothk` has entropy **0.0159** — near zero because it is a jump table of identical stubs. Entropy flags nothing; coverage would flag it as suspicious because almost nothing decodes. Reading it shows it is benign. That is why the verdict combines both numbers instead of thresholding one.
104
+
105
+ ## Limits — read before trusting it
106
+
107
+ - **Does not recover the key.** Single-byte XOR is trivially brute-forced (try 255 keys, score coverage); longer keys and block ciphers need real work.
108
+ - **Does not prove maliciousness.** Protectors and packers obfuscate legitimately. The measurement says "this code is not decodable as-is", nothing more.
109
+ - **Coverage near 0 can be benign** if a section legitimately holds data with code-like flags. Check permissions and the section name before concluding.
110
+ - **Only PE.** ELF/Mach-O need different parsers; the coverage idea transfers, the code does not.
111
+
112
+ ## Requirements
113
+
114
+ Python 3.9+. `pefile` and `capstone` are installed as dependencies.
115
+
116
+ ## License
117
+
118
+ MIT
@@ -0,0 +1,31 @@
1
+ """
2
+ peobf — 用反汇编覆盖率检测 PE 节区的 XOR 类混淆
3
+
4
+ 核心事实:XOR 是双射,Shannon 熵对它完全不敏感(精确不变)。
5
+ 判别信号只能是「反汇编可解码字节占比」。
6
+
7
+ 在真实 Windows 二进制上实测:
8
+ version.dll .text 原始 100.00% → XOR 0x5A 后 2.54%
9
+ advapi32.dll .text 原始 22.14% → XOR 0x5A 后 0.00%
10
+ 两种情况下熵都是 5.4067 / 6.2347,变化 +0.0000
11
+ """
12
+ from __future__ import annotations
13
+
14
+ from .core import (
15
+ disasm_coverage,
16
+ section_report,
17
+ shannon_entropy,
18
+ summarize,
19
+ xform_cases,
20
+ )
21
+
22
+ __version__ = "1.0.0"
23
+
24
+ __all__ = [
25
+ "disasm_coverage",
26
+ "section_report",
27
+ "shannon_entropy",
28
+ "summarize",
29
+ "xform_cases",
30
+ "__version__",
31
+ ]
@@ -0,0 +1,7 @@
1
+ """支持 python -m peobf。"""
2
+ import sys
3
+
4
+ from .cli import main
5
+
6
+ if __name__ == "__main__":
7
+ sys.exit(main())
@@ -0,0 +1,96 @@
1
+ """peobf 命令行入口。"""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import os
6
+ import sys
7
+
8
+ from .core import list_sections, section_report, summarize
9
+
10
+
11
+ def _fmt_pct(x) -> str:
12
+ return "n/a" if x is None else f"{x * 100:6.2f}%"
13
+
14
+
15
+ def cmd_sections(args) -> int:
16
+ try:
17
+ rows = list_sections(args.path)
18
+ except Exception as e:
19
+ print(f"读取失败: {e}")
20
+ return 1
21
+
22
+ print(f"{os.path.basename(args.path)} 架构 {rows[0]['arch'] if rows else '?'}")
23
+ print()
24
+ print(f" {'节名':<10} {'VA':>10} {'原始大小':>12} {'熵':>9} {'权限':<5}")
25
+ print(" " + "-" * 62)
26
+ for r in rows:
27
+ flag = " <-- 高熵" if r["entropy"] > 7.0 else ""
28
+ print(f" {r['name']:<10} {hex(r['va']):>10} {r['raw_size']:>12,} "
29
+ f"{r['entropy']:>9.4f} {r['perms']:<5}{flag}")
30
+ return 0
31
+
32
+
33
+ def cmd_check(args) -> int:
34
+ try:
35
+ rep = section_report(args.path, args.section, with_coverage=not args.entropy_only)
36
+ s = summarize(rep)
37
+ except Exception as e:
38
+ print(f"分析失败: {e}")
39
+ return 1
40
+
41
+ print("=" * 74)
42
+ print(f"文件 {os.path.basename(args.path)}")
43
+ print(f"节 {rep['section']} {rep['size']:,} 字节 权限 {rep['perms']} 架构 {rep['arch']}")
44
+ print("=" * 74)
45
+
46
+ print(f"\n {'情形':<16} {'熵':>9} {'反汇编覆盖率':>14}")
47
+ print(" " + "-" * 44)
48
+
49
+ base_e = rep["cases"][0]["entropy"]
50
+ for c in rep["cases"]:
51
+ d = c["entropy"] - base_e
52
+ dstr = f"{d:+.4f}" if c["case"] != "original" else ""
53
+ cov = _fmt_pct(c.get("coverage"))
54
+ print(f" {c['case']:<16} {c['entropy']:>9.4f} {cov:>14} {dstr}")
55
+
56
+ print("\n" + "=" * 74)
57
+ print(f"判定: {s['verdict']}")
58
+ print(f"理由: {s['reason']}")
59
+ if s["entropy_only"] if "entropy_only" in s else False:
60
+ pass
61
+ blind = s.get("entropy_blind_cases", 0)
62
+ if blind:
63
+ print(f"\n{s['entropy_blind_cases']} 个双射变换:熵完全不变但代码不可解码。")
64
+ print("只测熵的工具会把这些全判成「正常」——这是漏检。")
65
+ print("=" * 74)
66
+ return 0
67
+
68
+
69
+ def main(argv: list[str] | None = None) -> int:
70
+ ap = argparse.ArgumentParser(
71
+ prog="peobf",
72
+ description="用反汇编覆盖率检测 PE 节区的 XOR 类混淆(熵检测对双射无效)",
73
+ )
74
+ sub = ap.add_subparsers(dest="cmd")
75
+
76
+ p1 = sub.add_parser("sections", help="列出所有节区与熵(快,不反汇编)")
77
+ p1.add_argument("path", help="PE 文件路径")
78
+ p1.set_defaults(func=cmd_sections)
79
+
80
+ p2 = sub.add_parser("check", help="分析指定节区:熵 vs 反汇编覆盖率")
81
+ p2.add_argument("path", help="PE 文件路径")
82
+ p2.add_argument("--section", default=".text", help="节名(默认 .text)")
83
+ p2.add_argument("--entropy-only", action="store_true", help="只算熵,不反汇编")
84
+ p2.set_defaults(func=cmd_check)
85
+
86
+ ap.add_argument("--version", action="version", version="peobf 1.0.0")
87
+
88
+ args = ap.parse_args(argv)
89
+ if not getattr(args, "func", None):
90
+ ap.print_help()
91
+ return 2
92
+ return args.func(args)
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
@@ -0,0 +1,222 @@
1
+ """核心测量:熵 vs 反汇编覆盖率。"""
2
+ from __future__ import annotations
3
+
4
+ import collections
5
+ import math
6
+ from typing import Iterable
7
+
8
+ try:
9
+ import capstone
10
+ except ImportError as e: # pragma: no cover
11
+ raise ImportError("peobf 需要 capstone:pip install capstone") from e
12
+
13
+ try:
14
+ import pefile
15
+ except ImportError as e: # pragma: no cover
16
+ raise ImportError("peobf 需要 pefile:pip install pefile") from e
17
+
18
+
19
+ # ---- 熵 -------------------------------------------------------------------
20
+
21
+ def shannon_entropy(data: bytes) -> float:
22
+ """
23
+ 字节级 Shannon 熵,范围 0..8。
24
+
25
+ 注意:这个值对 XOR / 置换类变换完全不敏感,别单独用它判断混淆。
26
+ """
27
+ if not data:
28
+ return 0.0
29
+ counts = collections.Counter(data)
30
+ n = len(data)
31
+ return -sum((c / n) * math.log2(c / n) for c in counts.values())
32
+
33
+
34
+ # ---- 反汇编覆盖率 ---------------------------------------------------------
35
+
36
+ _ARCH_MAP = {
37
+ "x64": (capstone.CS_ARCH_X86, capstone.CS_MODE_64),
38
+ "x86": (capstone.CS_ARCH_X86, capstone.CS_MODE_32),
39
+ "arm64": (capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM),
40
+ "arm": (capstone.CS_ARCH_ARM, capstone.CS_MODE_ARM),
41
+ }
42
+
43
+
44
+ def disasm_coverage(code: bytes, arch: str = "x64", base: int = 0x1000) -> float:
45
+ """
46
+ 从节区起始地址开始反汇编,返回被有效指令消耗的字节占比(0..1)。
47
+
48
+ 正常的 x64 代码节通常 20%-100% —— 不是 100%,因为章节之间夹着对齐填充
49
+ 和内联数据。但 XOR 之后通常是 0.00%:第一个字节就解不出合法指令。
50
+ """
51
+ if not code:
52
+ return 0.0
53
+ arch = arch.lower()
54
+ if arch not in _ARCH_MAP:
55
+ raise ValueError(f"不支持的架构 {arch!r},可选: {', '.join(sorted(_ARCH_MAP))}")
56
+
57
+ md = capstone.Cs(*_ARCH_MAP[arch])
58
+ md.skipdata = False
59
+
60
+ covered = 0
61
+ try:
62
+ for ins in md.disasm(code, base):
63
+ covered += ins.size
64
+ except capstone.CsError: # pragma: no cover
65
+ pass
66
+ return covered / len(code)
67
+
68
+
69
+ # ---- 变换对照 -------------------------------------------------------------
70
+
71
+ def xform_cases(orig: bytes) -> list[tuple[str, bytes]]:
72
+ """
73
+ 返回 (名称, 变换后字节) 列表。除了第一项,其余全是双射变换 ——
74
+ 熵必须完全不变,只有覆盖率会掉。
75
+ """
76
+ out: list[tuple[str, bytes]] = [("original", orig)]
77
+ for k in (0x5A, 0xFF, 0x01):
78
+ out.append((f"xor 0x{k:02X}", bytes(b ^ k for b in orig)))
79
+ if orig:
80
+ # 位置置换:模拟块加密打散
81
+ n = len(orig)
82
+ out.append(("permuted", bytes(orig[(i * 7 + 3) % n] for i in range(n))))
83
+ return out
84
+
85
+
86
+ # ---- PE 读取 --------------------------------------------------------------
87
+
88
+ def pick_arch(pe) -> str:
89
+ machine = pe.FILE_HEADER.Machine
90
+ return {0x8664: "x64", 0x14c: "x86", 0xAA64: "arm64", 0x1C0: "arm"}.get(machine, "x64")
91
+
92
+
93
+ def find_section(pe, name: str):
94
+ want = name.encode() if isinstance(name, str) else name
95
+ want = want.rstrip(b"\0")
96
+ for s in pe.sections:
97
+ if s.Name.rstrip(b"\0") == want:
98
+ return s
99
+ return None
100
+
101
+
102
+ def section_perms(section) -> str:
103
+ ch = section.Characteristics
104
+ p = ""
105
+ if ch & 0x40000000:
106
+ p += "R"
107
+ if ch & 0x80000000:
108
+ p += "W"
109
+ if ch & 0x20000000:
110
+ p += "X"
111
+ return p or "-"
112
+
113
+
114
+ def list_sections(path: str) -> list[dict]:
115
+ """列出所有节区的名称/大小/熵/权限 —— 不反汇编,很快。"""
116
+ pe = pefile.PE(path, fast_load=True)
117
+ arch = pick_arch(pe)
118
+ rows = []
119
+ for s in pe.sections:
120
+ try:
121
+ data = s.get_data()
122
+ except Exception:
123
+ data = b""
124
+ rows.append({
125
+ "name": s.Name.rstrip(b"\0").decode("latin1", "replace"),
126
+ "va": s.VirtualAddress,
127
+ "raw_size": s.SizeOfRawData,
128
+ "entropy": shannon_entropy(data),
129
+ "perms": section_perms(s),
130
+ "arch": arch,
131
+ })
132
+ return rows
133
+
134
+
135
+ def section_report(path: str, section: str = ".text", with_coverage: bool = True) -> dict:
136
+ """
137
+ 分析一个节区:原始熵、原始覆盖率,以及各双射变换后的熵与覆盖率。
138
+
139
+ with_coverage=False 时只算熵(快,但不给判别信号)。
140
+ """
141
+ pe = pefile.PE(path, fast_load=True)
142
+ arch = pick_arch(pe)
143
+ sec = find_section(pe, section)
144
+ if sec is None:
145
+ avail = ", ".join(s.Name.rstrip(b"\0").decode("latin1", "replace") for s in pe.sections)
146
+ raise ValueError(f"找不到节 {section!r}。可选: {avail}")
147
+
148
+ orig = sec.get_data()
149
+ if not orig:
150
+ raise ValueError(f"节 {section!r} 为空")
151
+
152
+ cases = []
153
+ for name, data in xform_cases(orig):
154
+ row = {"case": name, "entropy": shannon_entropy(data)}
155
+ if with_coverage:
156
+ row["coverage"] = disasm_coverage(data, arch)
157
+ cases.append(row)
158
+
159
+ return {
160
+ "path": path,
161
+ "section": section,
162
+ "arch": arch,
163
+ "size": len(orig),
164
+ "perms": section_perms(sec),
165
+ "cases": cases,
166
+ }
167
+
168
+
169
+ # ---- 判定 -----------------------------------------------------------------
170
+
171
+ def summarize(report: dict) -> dict:
172
+ """
173
+ 从 section_report 的结果给出判定。
174
+
175
+ 判别规则(基于实测,不是拍脑袋):
176
+ · 熵变化 < 1e-6 且覆盖率掉到 <5% → 双射变换,熵检测必然漏检
177
+ · 原始覆盖率本身 <5% 且熵 >6 → 该节可能已被加密/压缩
178
+ · 否则 → 未见变换迹象
179
+ """
180
+ cases = report["cases"]
181
+ base = cases[0]
182
+ base_e = base["entropy"]
183
+ base_cov = base.get("coverage")
184
+
185
+ transformed = []
186
+ for c in cases[1:]:
187
+ d_e = c["entropy"] - base_e
188
+ cov = c.get("coverage")
189
+ invisible = abs(d_e) < 1e-6
190
+ broken = cov is not None and cov < 0.05
191
+ transformed.append({
192
+ "case": c["case"],
193
+ "entropy_delta": d_e,
194
+ "coverage": cov,
195
+ "entropy_blind": invisible,
196
+ "code_broken": broken,
197
+ })
198
+
199
+ blind_count = sum(1 for t in transformed if t["entropy_blind"] and t["code_broken"])
200
+
201
+ if base_cov is not None:
202
+ if base_cov < 0.05 and base_e > 6.0:
203
+ verdict = "possibly_encrypted"
204
+ why = f"该节不可解码(覆盖率 {base_cov*100:.2f}%)且熵 {base_e:.4f} 偏高"
205
+ elif base_cov < 0.05:
206
+ verdict = "undecodable_low_entropy"
207
+ why = f"该节不可解码但熵只有 {base_e:.4f} —— 可能是变换过或被数据填满"
208
+ else:
209
+ verdict = "looks_normal"
210
+ why = f"该节可解码(覆盖率 {base_cov*100:.2f}%),未见变换迹象"
211
+ else:
212
+ verdict = "entropy_only"
213
+ why = "只算了熵,没有反汇编,无法判定"
214
+
215
+ return {
216
+ "verdict": verdict,
217
+ "reason": why,
218
+ "base_entropy": base_e,
219
+ "base_coverage": base_cov,
220
+ "entropy_blind_cases": blind_count,
221
+ "transformed": transformed,
222
+ }
@@ -0,0 +1,140 @@
1
+ Metadata-Version: 2.4
2
+ Name: peobf
3
+ Version: 1.0.0
4
+ Summary: Detect XOR-style obfuscation in PE sections by disassembly coverage, because Shannon entropy is blind to bijections.
5
+ Author: gem3match-dev
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/gem3match-dev/pe-obfuscation-detection
8
+ Project-URL: Repository, https://github.com/gem3match-dev/pe-obfuscation-detection
9
+ Keywords: pe,obfuscation,entropy,reverse-engineering,malware-analysis,capstone,windows
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Topic :: Security
14
+ Classifier: Topic :: Software Development :: Disassemblers
15
+ Classifier: Intended Audience :: Developers
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: pefile>=2023.2.7
20
+ Requires-Dist: capstone>=5.0
21
+ Dynamic: license-file
22
+
23
+ # peobf
24
+
25
+ Detect XOR-style obfuscation in PE sections by **disassembly coverage**, because Shannon entropy is blind to bijections.
26
+
27
+ ```
28
+ pip install peobf
29
+ peobf check C:\Windows\System32\version.dll
30
+ ```
31
+
32
+ ## The problem
33
+
34
+ Most packer/obfuscation detectors threshold on Shannon entropy: above ~7.0 means "compressed or encrypted". That test misses the most common cheap obfuscation there is.
35
+
36
+ XOR is a **bijection** — it permutes the byte-value labels one-to-one. Shannon entropy is computed from the multiset of byte frequencies, so the entropy is *exactly* unchanged:
37
+
38
+ ```
39
+ H(XOR(data, k)) == H(data) for every key k
40
+ ```
41
+
42
+ Measured on real Windows binaries:
43
+
44
+ ```
45
+ C:\Windows\System32\version.dll .text 12,288 bytes
46
+
47
+ case entropy disassembly coverage
48
+ original 5.4067 100.00%
49
+ xor 0x5A 5.4067 2.54%
50
+ xor 0xFF 5.4067 0.69%
51
+ xor 0x01 5.4067 0.13%
52
+ permuted 5.4067 0.41%
53
+ ```
54
+
55
+ Entropy delta on every transformed row: **+0.0000**. A tool that only measures entropy reports "normal" for a section whose code is entirely undecodable.
56
+
57
+ ```
58
+ C:\Windows\System32\advapi32.dll .text 471,040 bytes
59
+
60
+ case entropy disassembly coverage
61
+ original 6.2347 22.14%
62
+ xor 0x5A 6.2347 0.00%
63
+ xor 0xFF 6.2347 0.00%
64
+ permuted 6.2347 0.01%
65
+ ```
66
+
67
+ ## What peobf measures instead
68
+
69
+ **Decodable instruction coverage**: start a disassembler at the section base and count what fraction of bytes valid instructions consume.
70
+
71
+ - Real x64 code is typically 20–100% (not 100% — alignment padding and inline data sit between functions).
72
+ - XOR-obfuscated code drops to **0.00%**: the decoder cannot form a single valid instruction.
73
+
74
+ That gap is the signal. It needs no key, no unpacking, no execution.
75
+
76
+ ## Usage
77
+
78
+ ```bash
79
+ # 快速看所有节区(不反汇编,毫秒级)
80
+ peobf sections suspicious.dll
81
+
82
+ # 深入分析一个节区
83
+ peobf check suspicious.dll --section .text
84
+ ```
85
+
86
+ `check` prints the entropy and coverage for the original plus four bijective transforms, then gives a verdict:
87
+
88
+ | verdict | meaning |
89
+ |---|---|
90
+ | `looks_normal` | section decodes normally; no obfuscation evidence |
91
+ | `possibly_encrypted` | coverage <5% **and** entropy >6 |
92
+ | `undecodable_low_entropy` | coverage <5% but entropy low — transformed, or filled with data |
93
+
94
+ ## As a library
95
+
96
+ ```python
97
+ from peobf import section_report, summarize
98
+
99
+ rep = section_report(r"C:\Windows\System32\version.dll", ".text")
100
+ s = summarize(rep)
101
+
102
+ print(s["verdict"]) # looks_normal
103
+ print(s["base_coverage"]) # 1.0
104
+ print(s["entropy_blind_cases"]) # 4 ← transforms entropy missed entirely
105
+ ```
106
+
107
+ `list_sections(path)` returns name / VA / raw size / entropy / permissions for every section without disassembling.
108
+
109
+ ## Real section layout, for calibration
110
+
111
+ `advapi32.dll` (778,352 bytes, PE32+, 8 sections):
112
+
113
+ ```
114
+ name VA raw size entropy perms
115
+ .text 0x1000 471,040 6.2347 RX
116
+ fothk 0x74000 4,096 0.0159 RX
117
+ .rdata 0x75000 233,472 4.6996 R
118
+ .data 0xae000 12,288 0.8552 RW
119
+ .pdata 0xb3000 20,480 5.2377 R
120
+ .didat 0xb8000 4,096 1.2959 RW
121
+ .rsrc 0xb9000 4,096 1.6339 R
122
+ .reloc 0xba000 8,192 5.0584 R
123
+ ```
124
+
125
+ Both directions of false positive are real. `fothk` has entropy **0.0159** — near zero because it is a jump table of identical stubs. Entropy flags nothing; coverage would flag it as suspicious because almost nothing decodes. Reading it shows it is benign. That is why the verdict combines both numbers instead of thresholding one.
126
+
127
+ ## Limits — read before trusting it
128
+
129
+ - **Does not recover the key.** Single-byte XOR is trivially brute-forced (try 255 keys, score coverage); longer keys and block ciphers need real work.
130
+ - **Does not prove maliciousness.** Protectors and packers obfuscate legitimately. The measurement says "this code is not decodable as-is", nothing more.
131
+ - **Coverage near 0 can be benign** if a section legitimately holds data with code-like flags. Check permissions and the section name before concluding.
132
+ - **Only PE.** ELF/Mach-O need different parsers; the coverage idea transfers, the code does not.
133
+
134
+ ## Requirements
135
+
136
+ Python 3.9+. `pefile` and `capstone` are installed as dependencies.
137
+
138
+ ## License
139
+
140
+ MIT
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ peobf/__init__.py
5
+ peobf/__main__.py
6
+ peobf/cli.py
7
+ peobf/core.py
8
+ peobf.egg-info/PKG-INFO
9
+ peobf.egg-info/SOURCES.txt
10
+ peobf.egg-info/dependency_links.txt
11
+ peobf.egg-info/entry_points.txt
12
+ peobf.egg-info/requires.txt
13
+ peobf.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ peobf = peobf.cli:main
@@ -0,0 +1,2 @@
1
+ pefile>=2023.2.7
2
+ capstone>=5.0
@@ -0,0 +1 @@
1
+ peobf
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "peobf"
7
+ version = "1.0.0"
8
+ description = "Detect XOR-style obfuscation in PE sections by disassembly coverage, because Shannon entropy is blind to bijections."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "gem3match-dev" }]
13
+ keywords = ["pe", "obfuscation", "entropy", "reverse-engineering", "malware-analysis", "capstone", "windows"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ "Topic :: Security",
19
+ "Topic :: Software Development :: Disassemblers",
20
+ "Intended Audience :: Developers",
21
+ ]
22
+ dependencies = ["pefile>=2023.2.7", "capstone>=5.0"]
23
+
24
+ [project.urls]
25
+ Homepage = "https://github.com/gem3match-dev/pe-obfuscation-detection"
26
+ Repository = "https://github.com/gem3match-dev/pe-obfuscation-detection"
27
+
28
+ [project.scripts]
29
+ peobf = "peobf.cli:main"
30
+
31
+ [tool.setuptools]
32
+ packages = ["peobf"]
peobf-1.0.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+