File size: 8,605 Bytes
d2507b5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 | package bundle
import (
"path/filepath"
"strings"
)
// PycAnalyzer inspects compiled Python bytecode (.pyc) — the xz-utils "shipped
// artifact != source" vector. ANY shipped .pyc is SevHigh-by-default. It parses
// the pyc header and marshal-decodes the top-level code object to recover
// co_names/co_consts/strings, scans them for exfil primitives, and diffs the
// recovered symbols against the same-stem sibling .py so a clean decoy source
// cannot launder a malicious .pyc. Decoding is PURE-GO ONLY: the scanner never
// shells out to the system python (`python3 -m dis`) on an untrusted .pyc —
// disassembling attacker-supplied bytecode through the interpreter is a
// code-execution surface and the exact payload class this tool exists to flag.
// Bytecode that pure-Go cannot decode is reported as a SevHigh-Opaque artifact,
// never executed. Never panics on truncated/forged-magic/malformed bytecode.
type PycAnalyzer struct{}
func (PycAnalyzer) Name() string { return "pyc" }
func (PycAnalyzer) Handles(kind FileKind) bool { return kind == KindPyc }
func (PycAnalyzer) Analyze(f *File, b *Bundle) ([]Finding, error) {
if f == nil {
return nil, nil
}
out := []Finding{
{
Analyzer: "pyc",
File: f.RelPath,
Signal: "ships-compiled-bytecode",
Severity: SevHigh,
Detail: "ships compiled Python bytecode (shipped artifact may differ from source)",
Structural: true,
},
}
// Pure-Go decode only. We deliberately do NOT fall back to `python3 -m dis`
// (or any subprocess/interpreter) on an untrusted .pyc: running the system
// python against attacker-supplied bytecode is a code-execution surface.
// Undecodable bytecode is an opaque artifact (which escalates), not a reason
// to execute it.
symbols, ok := recoverPycStrings(f.Sniff)
if !ok {
out = append(out, Finding{
Analyzer: "pyc",
File: f.RelPath,
Signal: "opaque-bytecode",
Severity: SevHigh,
Detail: "compiled bytecode could not be decoded (opaque artifact)",
Opaque: true,
Structural: true,
})
return out, nil
}
// Scan recovered strings for exfil/credential/network primitives.
joined := strings.Join(symbols, "\n")
out = append(out, sharedIndicatorScan(joined, f.RelPath, "pyc")...)
// compiled-source-mismatch: symbols present in bytecode but absent from the
// same-stem sibling source. A clean decoy .py does NOT satisfy
// "compiled-without-matching-source".
if src, found := siblingSourceFor(b, f); found {
srcText := strings.ToLower(string(src.Sniff))
var missing []string
for _, sym := range symbols {
if !isInterestingSymbol(sym) {
continue
}
if !strings.Contains(srcText, strings.ToLower(sym)) {
missing = append(missing, sym)
if len(missing) >= 8 {
break
}
}
}
if len(missing) > 0 {
out = append(out, Finding{
Analyzer: "pyc",
File: f.RelPath,
Signal: "compiled-source-mismatch",
Severity: SevHigh,
Detail: "bytecode references symbols absent from sibling source: " + strings.Join(missing, ", "),
Corroborated: true,
})
}
} else {
out = append(out, Finding{
Analyzer: "pyc",
File: f.RelPath,
Signal: "compiled-without-matching-source",
Severity: SevHigh,
Detail: "compiled bytecode ships with no same-stem source file (uninspectable, xz pattern)",
// Escalating, host-agnostic: shipping executable Python BYTECODE with no
// source in a distributed skill is the opaque-execution payload and is
// not a benign idiom (verified: no benign corpus bundle ships a
// sourceless .pyc). Unlike a native .so (which a legit skill may vendor),
// sourceless .pyc has no legitimate distribution reason.
Corroborated: true,
})
}
return dedupeFindings(out), nil
}
// recoverPycStrings attempts a minimal pure-Go recovery of printable
// identifier/const strings from a CPython .pyc marshal stream. It does NOT fully
// implement the marshal format; instead it validates the pyc header, then walks
// the marshal body extracting length-prefixed string objects by their payloads.
// Best-effort and bounded; returns ok=false when the header is not a plausible
// pyc so the caller can fall back. Never panics.
func recoverPycStrings(data []byte) (symbols []string, ok bool) {
defer func() {
if recover() != nil {
symbols = nil
ok = false
}
}()
// pyc header: 4-byte magic, then (3.7+) 4-byte bit field, 4-byte mtime,
// 4-byte source size => 16-byte header. CPython magic ends with \r\n.
if len(data) < 16 {
return nil, false
}
if data[2] != 0x0d || data[3] != 0x0a {
return nil, false
}
body := data[16:]
syms := walkMarshalStrings(body)
// Header was valid => decode succeeded even if zero strings were found.
return syms, true
}
// marshal type codes for string-like objects (flag bit 0x80 = interned/ref).
const (
marshalString = 's' // TYPE_STRING (bytes), 4-byte length prefix
marshalUnicode = 'u' // TYPE_UNICODE, 4-byte length prefix
marshalInterned = 't' // TYPE_INTERNED, 4-byte length prefix
marshalShortASCII = 'z' // TYPE_SHORT_ASCII, 1-byte length prefix
marshalShortInt = 'Z' // TYPE_SHORT_ASCII_INTERNED, 1-byte length prefix
marshalASCII = 'a' // TYPE_ASCII, 4-byte length prefix
marshalASCIIInt = 'A' // TYPE_ASCII_INTERNED, 4-byte length prefix
)
// walkMarshalStrings linearly scans the marshal body for string-typed objects
// and lifts their payloads. Intentionally a tolerant scanner (not a full
// recursive unmarshaller): it slides over the bytes, and whenever it sees a
// recognized string type code followed by a plausible length, it extracts the
// payload. Bounded by input length and a string cap; safe on truncated data.
func walkMarshalStrings(body []byte) []string {
var out []string
n := len(body)
i := 0
const maxStrings = 4096
for i < n && len(out) < maxStrings {
c := body[i] & 0x7f // strip the ref flag
switch c {
case marshalString, marshalUnicode, marshalInterned, marshalASCII, marshalASCIIInt:
if i+5 > n {
i++
continue
}
length := int(body[i+1]) | int(body[i+2])<<8 | int(body[i+3])<<16 | int(body[i+4])<<24
if length < 0 || length > 1<<16 || i+5+length > n {
i++
continue
}
s := string(body[i+5 : i+5+length])
if isPrintableRun(s) {
out = append(out, s)
i += 5 + length
continue
}
i++
case marshalShortASCII, marshalShortInt:
if i+2 > n {
i++
continue
}
length := int(body[i+1])
if i+2+length > n {
i++
continue
}
s := string(body[i+2 : i+2+length])
if isPrintableRun(s) {
out = append(out, s)
i += 2 + length
continue
}
i++
default:
i++
}
}
return dedupeStrings(out)
}
// siblingSourceFor returns the same-stem .py sibling of a .pyc, if present.
// Handles the CPython cache naming "name.cpython-312.pyc" -> "name.py".
func siblingSourceFor(b *Bundle, pyc *File) (*File, bool) {
if b == nil {
return nil, false
}
stem := pycStem(filepath.Base(pyc.RelPath))
dir := filepath.Dir(pyc.RelPath)
want := stem + ".py"
for _, f := range b.Files {
if f == nil || f == pyc {
continue
}
if f.Kind != KindPythonSource {
continue
}
if filepath.Dir(f.RelPath) != dir {
continue
}
if filepath.Base(f.RelPath) == want {
return f, true
}
}
return nil, false
}
// pycStem strips ".pyc" and an optional ".cpython-XYZ"/".opt-N" cache tag.
func pycStem(base string) string {
base = strings.TrimSuffix(base, ".pyc")
if idx := strings.Index(base, ".cpython-"); idx >= 0 {
base = base[:idx]
}
if idx := strings.Index(base, ".opt-"); idx >= 0 {
base = base[:idx]
}
return base
}
// isInterestingSymbol filters recovered marshal strings down to plausible
// identifiers/dotted-attrs/exfil tokens worth diffing against source.
func isInterestingSymbol(s string) bool {
s = strings.TrimSpace(s)
if len(s) < 3 || len(s) > 200 {
return false
}
if strings.ContainsAny(s, " \t") && !strings.Contains(s, "://") {
return false
}
return true
}
func dedupeStrings(in []string) []string {
seen := map[string]bool{}
var out []string
for _, s := range in {
if s == "" || seen[s] {
continue
}
seen[s] = true
out = append(out, s)
}
return out
}
// isPrintableRun reports whether s is mostly printable ASCII (a recovered
// string, not random bytes).
func isPrintableRun(s string) bool {
if s == "" {
return false
}
runes := []rune(s)
printable := 0
for _, r := range runes {
if r >= 0x20 && r < 0x7f {
printable++
}
}
return float64(printable)/float64(len(runes)) >= 0.85
}
|