Repository navigation
Expand file tree
/
Copy pathioc_scan.py
More file actions
executable file
·4495 lines (4124 loc) · 178 KB
/
Copy pathioc_scan.py
File metadata and controls
executable file
·4495 lines (4124 loc) · 178 KB
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""ioc_scan.py — known-malicious-dependency tripwire for an untrusted repo.
Greps every discoverable lockfile in a freshly cloned untrusted repo for any
package identity on the bundled IoC list (`ioc-list.txt` next to this script).
Plain entries are package-wide triggers for identities whose entire release
family is malicious (for example, typosquats). Structured VERSION records turn
an identity into an exact malicious-version denylist: a trusted exact version
not in that denylist is locally safe. When enabled, an exact OSV query can add a
malicious version that has not yet reached the bundled list. Unparseable or
structurally ambiguous version evidence cannot establish a safe version and
still halts.
This runs FIRST in the coldclone flow, on the HOST, right after the hardened
clone and BEFORE sanitize + moving the tree into an isolation environment:
- It only READS lockfiles (no install, no build, no code execution), so it is
safe to run on an untrusted tree.
- A hit HALTs prep (exit 2) so the repo is caught up front — the human decides
whether to treat the repo as hostile or to examine it deliberately inside
their isolation environment.
This is an identity-and-version-exact denylist (high precision via exact
matching; it catches only KNOWN drops, and its few residual false positives fail
SAFE — see the accepted limitation below). Trusted exact-version evidence is
extracted locally from npm-family (package-lock, Yarn, pnpm, Bun text and
binary), Cargo, and Python (uv.lock, poetry.lock, and pip requirements-file
pins; PEP 440 equality) lockfiles. The pip requirements family
(`requirements*.txt`, `*-requirements.txt`, `constraints*.txt`,
`requirements/*.txt`) is discovered by name, and its `-r` / `-c` includes are
followed to in-tree files, which are read as requirements whatever their name.
A VERSION-only package (no plain entry) is ecosystem-scoped and matches only
that ecosystem's lockfiles. By default the scanner
also makes opportunistic exact-version OSV API queries for version-scoped
packages; `--offline` disables those queries. It complements — never replaces —
the auto-execution sanitizer
(`sanitize_repo.py`) and the isolation boundary.
Exit codes: 0 clean, 1 IoC-list stale (>7 days) but no hit, 2 IoC hit (HALT),
3 config error — the gate could not actually run, so FAIL CLOSED and HALT:
IoC list missing / unreadable / EMPTY / invalid, a discovered lockfile that
could not be scanned (unreadable, oversized, malformed structured data, or a
symlink we refuse to follow), a requirements include that cannot be inspected
(remote, environment-dependent, outside the tree, missing, or reached through a
symlink), or a bad repo path. Only 0 and 1 mean "no malicious dependency
found — proceed" (1 also
flags a stale or header-less list). A repo with simply no lockfiles is
legitimately clean -> 0.
Usage: python3 ioc_scan.py <repo-dir> [--ioc-list <path>] [--offline]
Known limitation (accepted): plain package entries are not tagged by ecosystem,
so a slash-delimited path component (e.g. a go.sum module owner
`github.com/<org>/...`) is matched against the whole cross-ecosystem plain-name
list. A benign module whose owner equals an npm/PyPI IoC name can therefore
false-HALT. This fails SAFE (a HALT sends it to human review, never a miss) and
the alternative — matching only the last path component — would instead MISS go
modules whose package is not the last component (e.g. a `/v2` major-version
suffix), which is worse for a tripwire. Structured ecosystem tags scope exact
version evidence. A trusted exact version outside the recorded malicious set is
safe; legacy AFFECTED_SET_COMPLETE records are accepted as provenance but are
not needed to make that decision.
Bundled with the open-source coldclone tool; self-contained (no external deps).
"""
from __future__ import annotations
import argparse
import codecs
import io
import itertools
import posixpath
import json
import os
import re
import stat
import struct
import sys
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass, field, replace
from datetime import date
from pathlib import Path
from typing import Callable, Mapping
try: # tomllib is stdlib >= 3.11; below that TOML lockfiles fall back (see ioc_grep)
import tomllib
except ModuleNotFoundError: # pragma: no cover - exercised via monkeypatch
tomllib = None
# Default: the bundled list shipped next to this script.
_DEFAULT_IOC_LIST = Path(__file__).resolve().parent / "ioc-list.txt"
# Lockfiles grepped, by ecosystem. Reading these is execution-free.
_LOCKFILE_NAMES = frozenset({
"package-lock.json",
"yarn.lock",
"pnpm-lock.yaml",
"Cargo.lock",
"poetry.lock",
"uv.lock",
"requirements.txt",
"Pipfile.lock",
"go.sum",
"composer.lock",
"Gemfile.lock",
"bun.lock",
"bun.lockb",
})
# Python lockfiles. PyPI normalizes distribution names (PEP 503): case-insensitive
# and any run of `-`, `_`, `.` collapses to a single `-`. So `mnemonic_to_address`,
# `mnemonic-to-address`, and `Mnemonic.To.Address` are the SAME package. We apply
# that normalization ONLY when scanning these files — npm and cargo treat `_` vs
# `-` as DISTINCT packages, so normalizing there would create false matches.
_PYPI_LOCKFILES = frozenset({"requirements.txt", "poetry.lock", "Pipfile.lock",
"uv.lock"})
# pip requirements/constraints files are a SPLIT family (requirements-dev.txt,
# requirements/base.txt, constraints.txt, …), all read as `requirements.txt`.
# Mirrors sanitize_repo.py's predicate exactly (a test asserts parity).
_REQUIREMENTS_NAME_RE = re.compile( # bounded quantifiers (ReDoS invariant)
r"(?:requirements[\w.-]{0,128}|[\w.-]{1,128}-requirements|constraints[\w.-]{0,128})\.txt")
# pip's own spellings: a nested file that is a URL is fetched, and `${VAR}` is
# expanded from the install environment.
_PIP_SCHEME_RE = re.compile(r"^(http|https|file):", re.I)
_PIP_ENV_VAR_RE = re.compile(r"\$\{[A-Z0-9_]+\}")
_SHELL_QUOTING = str.maketrans("", "", "\"'\\")
# Characters that can sit between `-` and `r`/`c` in the bytes yet vanish
# before pip's option parser sees them: shlex quoting and escapes, and the line
# break of a `\` continuation.
_INCLUDE_GAP_CHARS = str.maketrans("", "", "\"'\\\r\n\x0b\x0c\x1c\x1d\x1e\x85")
_NON_ASCII_RUN_RES = (
re.compile(r"[\x80-\xff]+"),
re.compile(r"(?:[\x80-\xff][\x30-\x39\x40-\x7e]?)+"),
)
_INCLUDE_TARGET_LIMIT = 10_000
_INCLUDE_RECORD_LIMIT = 100
def _is_requirements_name(parent_name: str | None, name: str) -> bool:
"""True for a pip requirements-family file; `parent_name` is None at the root."""
if _REQUIREMENTS_NAME_RE.fullmatch(name):
return True
return name.endswith(".txt") and parent_name == "requirements"
def _lockfile_kind(path: Path, root: Path | None = None) -> str | None:
"""The format a discovered file is read as, or None when it is not scanned.
Every requirements-family member is `requirements.txt`. `root` (the scan
root) keeps a clone named `requirements` from making its own top-level
`*.txt` files pip inputs.
"""
if path.name in _LOCKFILE_NAMES and path.name != "requirements.txt":
return path.name
parent_name = None if root is not None and path.parent == root else path.parent.name
if _is_requirements_name(parent_name, path.name):
return "requirements.txt"
return None
_LOCKFILE_POLICY_ECOSYSTEMS = {
"package-lock.json": "npm",
"yarn.lock": "npm",
"pnpm-lock.yaml": "npm",
"bun.lock": "npm",
"bun.lockb": "npm",
"Cargo.lock": "crates.io",
"uv.lock": "PyPI",
"poetry.lock": "PyPI",
"requirements.txt": "PyPI",
}
# Which ecosystem a lockfile belongs to for ecosystem-scoped (VERSION-only)
# entries. A superset of the extractor-backed map: a PyPI lockfile with no exact
# extractor (Pipfile.lock) still matches scoped PyPI entries, which then fail
# safe as package-wide hits there.
_LOCKFILE_SCOPE_ECOSYSTEMS = {
**{name: "PyPI" for name in _PYPI_LOCKFILES},
**_LOCKFILE_POLICY_ECOSYSTEMS,
}
assert set(_LOCKFILE_POLICY_ECOSYSTEMS.items()) <= set(
_LOCKFILE_SCOPE_ECOSYSTEMS.items()
)
_TOML_LOCKFILES = frozenset({"uv.lock", "poetry.lock"})
def _pep503(name: str) -> str:
"""PEP 503 normalized PyPI distribution name."""
return re.sub(r"[-_.]+", "-", name).lower()
# Directories never traversed — installed artifacts / build outputs. Matching an
# IoC inside a vendored/installed tree is meaningless (you would not install an
# untrusted repo) and node_modules is huge. NOTE: we deliberately DO descend
# into `lib/` — vendored or submodule source (e.g. the assembled Foundry
# SUBMODULE SOURCE a repo ships under `lib/`) can commit a real malicious
# lockfile, and that is a signal worth catching.
_SKIP_DIRS = frozenset({
"node_modules", "target", "dist", "build", "out", "cache", "artifacts",
"typechain", "typechain-types", "vendor", "venv", ".venv", "__pycache__",
".git",
})
_STALE_DAYS = 7
_OSV_API = "https://api.osv.dev/v1/query"
_OSV_TIMEOUT_SECONDS = 5
_OSV_RESPONSE_LIMIT = 4 * 1024 * 1024
_OSV_QUERY_LIMIT = 10
_LOCKFILE_SIZE_LIMIT = 8 * 1024 * 1024
_LOCKFILE_TOTAL_SIZE_LIMIT = 64 * 1024 * 1024
_LOCKFILE_COUNT_LIMIT = 1024
_DISCOVERY_ENTRY_LIMIT = 100_000
_VERSION_EXTRACTION_LIMIT_PER_LOCKFILE = 16
_YARN_BERRY_METADATA_VERSIONS = frozenset({"6", "7", "8", "9", "10"})
_OSV_MARKER_NODE_LIMIT = 100_000
_JSON_LOCKFILES = frozenset({
"package-lock.json", "Pipfile.lock", "composer.lock",
})
_YAML_LOCKFILES = frozenset({"yarn.lock", "pnpm-lock.yaml"})
# Public registries a fresh npm/Yarn/pnpm/Bun install uses by default. Fetch
# URLs on any other host are surfaced as a non-gating advisory.
_DEFAULT_NPM_REGISTRY_HOSTS = frozenset({"registry.npmjs.org", "registry.yarnpkg.com"})
_URL_SCHEME_CHARS = frozenset(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+.-"
)
_URL_SPECIAL_SCHEMES = frozenset({"http", "https", "ws", "wss", "ftp", "file"})
_URL_AUTHORITY_END_RE = re.compile(r"[/?#\\\s\"'<>{},]")
_YARN_BERRY_METADATA_RE = re.compile(
r"^(?:__metadata|\"__metadata\"|'__metadata')\s*:", re.MULTILINE
)
_HOST_RE = re.compile(r"\[[0-9A-Fa-f:.]+\]|[^\s\"'<>{},:/?#\\\[\]]*")
_REMOTE_SOURCE_DISPLAY_LIMIT = 20
# Bun's text lockfile is JSON with comments and trailing commas (JSONC).
_JSONC_LOCKFILES = frozenset({"bun.lock"})
_BUN_LOCK_VERSIONS = frozenset({0, 1, 2})
_JSONC_LINE_COMMENT_END_RE = re.compile("[\n\r\u2028\u2029]")
_JSONC_WHITESPACE_RE = re.compile(r"\s+")
_URL_PATH_SPLIT_RE = re.compile(r"[/?#&=;:]")
_JSONC_PLAIN_RE = re.compile(r'[^\s"/,\[\]{}]+')
# Bun's binary lockfile (bun.lockb, Bun < 1.2 default). Layout per format:
# semver.Version is 48 bytes in format 2 (u32 major/minor/patch) and 56 bytes in
# format 3 (u64), which sizes the Resolution column of the package table.
_BUN_LOCKB_HEADER = b"#!/usr/bin/env bun\nbun-lockfile-format-v0\n"
_BUN_LOCKB_VERSION_SIZES = {2: 48, 3: 56}
# Package table columns, in serialized order: name String (8), name_hash u64
# (8), Resolution (16 + Version), dependencies slice (8), resolutions slice (8),
# Meta (88), Bin (20), Scripts (49).
_BUN_LOCKB_TAIL_COLUMN_SIZES = (8, 8, 88, 20, 49)
# Buffers after the package table: trees, hoisted deps, resolutions,
# dependencies, extern strings, string bytes (element sizes).
_BUN_LOCKB_BUFFER_SIZES = (20, 4, 4, 26, 16, 1)
_BUN_LOCKB_ANNOTATION_RE = re.compile(
rb"\n<[^>\n]{1,200}> ([0-9]{1,4}) sizeof, ([0-9]{1,2}) alignof\n"
)
_BUN_LOCKB_DECODE_FACTOR = 4
_BUN_LOCKB_DECODE_FLOOR = 1024 * 1024
_BUN_RESOLUTION_NPM = 2
_BUN_RESOLUTION_ROOT = 1
# root, folder, symlink, workspace: local sources that never fetch a release.
_BUN_LOCAL_RESOLUTIONS = frozenset({1, 4, 64, 72})
_BUN_DEPENDENCY_PEER = 1 << 4
_YAML_LINE_BREAK_RE = re.compile(r"\r\n|\r|\n")
_CARGO_PACKAGE_HEADER_RE = re.compile(
r"^[ \t]*\[\[[ \t]*package[ \t]*\]\][ \t]*(?:#.*)?$"
)
_CARGO_TABLE_HEADER_RE = re.compile(
r"^[ \t]*(?:"
r"\[[ \t]*[A-Za-z0-9_-]+(?:[ \t]*\.[ \t]*[A-Za-z0-9_-]+)*[ \t]*\]"
r"|\[\[[ \t]*[A-Za-z0-9_-]+(?:[ \t]*\.[ \t]*[A-Za-z0-9_-]+)*[ \t]*\]\]"
r")[ \t]*(?:#.*)?$"
)
_CARGO_IDENTITY_ASSIGNMENT_RE = re.compile(
r"^[ \t]*(name|version)[ \t]*=[ \t]*(?:\"([^\"\\]*)\"|'([^']*)')"
r"[ \t]*(?:#.*)?$"
)
_CARGO_QUOTED_KEY_RE = re.compile(
r'''^(?:"[^"\n]*"|'[^'\n]*')[ \t]*='''
)
_CARGO_IDENTITY_LIKE_RE = re.compile(
r"^\s*(?:name|version)(?=\s|=)"
)
_CARGO_INVALID_LINE_BREAK_RE = re.compile(
r"[\v\f\x1c-\x1e\x85\u2028\u2029]|\r(?!\n)"
)
_SEMVER_IDENTIFIER = r"(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)"
_EXACT_SEMVER_RE = re.compile(
r"(?:0|[1-9][0-9]*)\."
r"(?:0|[1-9][0-9]*)\."
r"(?:0|[1-9][0-9]*)"
rf"(?:-{_SEMVER_IDENTIFIER}(?:\.{_SEMVER_IDENTIFIER})*)?"
r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?"
)
@dataclass
class IocEntry:
name: str
line_no: int
version_evidence: dict[str, tuple[tuple[str, int], ...]] = field(
default_factory=dict
)
affected_set_complete: dict[str, int] = field(default_factory=dict)
# None: a plain entry, matched in every lockfile. Otherwise a VERSION-only
# entry, matched only in lockfiles of these ecosystems.
scope: frozenset[str] | None = None
@dataclass
class IocHit:
lockfile: Path
ioc: str
lockfile_line_no: int # 1-based; 0 means whole-file aggregate evidence
ioc_line_no: int
versions: tuple[str, ...] = ()
ecosystem: str | None = None
verification: str = "name-only"
version_evidence: dict[str, tuple[tuple[str, int], ...]] = field(
default_factory=dict
)
whole_file_kind: str | None = None
affected_set_complete: dict[str, int] = field(default_factory=dict)
lockfile_text: str | None = field(default=None, repr=False, compare=False)
# The format the file was read as; an included file is `requirements.txt`
# whatever its name. None means "derive it from the path".
lockfile_kind: str | None = None
@dataclass
class _DirectoryListings:
"""Directory listings for the include spelling check, with one budget.
`names[path]` is None for a listing that exceeded the budget; `examined`
counts every entry read so far, across all listings.
"""
names: dict[str, frozenset[str] | None] = field(default_factory=dict)
examined: int = 0
@dataclass(frozen=True)
class RequirementsInclude:
"""One `-r` / `-c` directive in a requirements file and what became of it.
outcome: "followed" (the target was scanned), "note" (non-gating: the
target is a directory, which pip cannot install from), or "refused" (the
target could not be inspected, so coverage is incomplete).
"""
source: Path
line_no: int
target: str # display-safe; a URL keeps only scheme and host
outcome: str
reason: str = ""
@dataclass(frozen=True)
class LockfilePackageVersions:
versions: tuple[str, ...] = ()
mixed_or_untrusted: bool = False
@dataclass
class OsvApiClassification:
status: str # success | failed
vulns: list[dict] = field(default_factory=list)
diagnostic: str = ""
class IocListError(ValueError):
"""The shipped IoC policy could not be read or parsed safely."""
def load_ioc_list(path: Path) -> tuple[dict[str, IocEntry], int | None]:
"""Parse the IoC policy. Returns (ioc_map, stale_days_or_none).
`stale_days` is days since the `LAST_REFRESHED: YYYY-MM-DD` header, or None
if absent/malformed. VERSION records form an exact malicious-release set;
every one must have a corresponding plain package entry. Legacy
AFFECTED_SET_COMPLETE records are validated and retained as provenance but
do not affect classification.
"""
if not path.is_file():
raise IocListError(f"IoC list not found at {path}")
try:
lines = path.read_text(encoding="utf-8", errors="strict").splitlines()
except (OSError, UnicodeError) as exc:
raise IocListError(f"cannot read IoC list {path}: {exc}") from exc
iocs: dict[str, IocEntry] = {}
policy_records: list[tuple[int, str, str, str, str | None]] = []
last_refreshed: str | None = None
for line_no, line in enumerate(lines, start=1):
stripped = line.strip()
if stripped.startswith("LAST_REFRESHED:"):
last_refreshed = stripped.split(":", 1)[1].strip()
continue
if not stripped or stripped.startswith("#"):
continue
if stripped.startswith("VERSION:"):
fields = [
part.strip()
for part in stripped[len("VERSION:"):].split("|")
]
if len(fields) != 3 or any(not field for field in fields):
raise IocListError(f"line {line_no}: malformed VERSION record")
ecosystem, package, version = fields
if ecosystem not in _IOC_VERSION_ECOSYSTEMS:
raise IocListError(
f"line {line_no}: VERSION ecosystem {ecosystem!r} "
"has no trusted exact extractor"
)
if (
not _is_policy_package_identity(package, ecosystem)
or not _is_exact_registry_version(version, ecosystem)
):
raise IocListError(
f"line {line_no}: invalid VERSION package/version"
)
policy_records.append(
(line_no, "version", ecosystem, package, version)
)
continue
if re.match(r"^VERSION(?:\s|$)", stripped):
raise IocListError(
f"line {line_no}: malformed reserved VERSION record"
)
if stripped.startswith("AFFECTED_SET_COMPLETE:"):
fields = [
part.strip()
for part in stripped[len("AFFECTED_SET_COMPLETE:"):].split("|")
]
if len(fields) != 2 or any(not field for field in fields):
raise IocListError(
f"line {line_no}: malformed AFFECTED_SET_COMPLETE record"
)
ecosystem, package = fields
if ecosystem not in _IOC_VERSION_ECOSYSTEMS:
raise IocListError(
f"line {line_no}: AFFECTED_SET_COMPLETE ecosystem "
f"{ecosystem!r} has no trusted exact extractor"
)
if not _is_policy_package_identity(package, ecosystem):
raise IocListError(
f"line {line_no}: invalid AFFECTED_SET_COMPLETE package"
)
policy_records.append(
(line_no, "complete", ecosystem, package, None)
)
continue
if re.match(r"^AFFECTED_SET_COMPLETE(?:\s|$)", stripped):
raise IocListError(
f"line {line_no}: malformed reserved "
"AFFECTED_SET_COMPLETE record"
)
if "|" in stripped:
raise IocListError(
f"line {line_no}: unexpected pipe in IoC policy record"
)
if not _is_plain_policy_identity(stripped):
raise IocListError(
f"line {line_no}: invalid plain package identity"
)
iocs.setdefault(stripped, IocEntry(name=stripped, line_no=line_no))
by_package: dict[str, dict[str, dict[str, int]]] = {}
active_complete: dict[tuple[str, str], int] = {}
# A package with VERSION records but no plain entry of the exact same name is
# ecosystem-scoped: it only matches lockfiles of the ecosystems it names, so a
# compromised PyPI release cannot HALT an unrelated npm/composer namesake.
scoped: dict[str, set[str]] = {}
for line_no, kind, ecosystem, package, version in policy_records:
if package not in iocs:
if kind != "version":
raise IocListError(
f"line {line_no}: AFFECTED_SET_COMPLETE for {package!r} "
"has no earlier distinct VERSION record"
)
iocs[package] = IocEntry(name=package, line_no=line_no)
scoped[package] = set()
if package in scoped:
scoped[package].add(ecosystem)
versions = by_package.setdefault(package, {}).setdefault(ecosystem, {})
key = (package, ecosystem)
if kind == "version":
assert version is not None
if version not in versions:
versions[version] = line_no
active_complete.pop(key, None)
continue
if not versions:
raise IocListError(
f"line {line_no}: AFFECTED_SET_COMPLETE for {package!r} "
"has no earlier distinct VERSION record"
)
active_complete[key] = line_no
for package, ecosystems in by_package.items():
iocs[package].version_evidence = {
ecosystem: tuple(sorted(versions.items(), key=lambda item: item[1]))
for ecosystem, versions in ecosystems.items()
}
for (package, ecosystem), line_no in active_complete.items():
iocs[package].affected_set_complete[ecosystem] = line_no
for package, ecosystems in scoped.items():
iocs[package].scope = frozenset(ecosystems)
stale_days: int | None = None
if last_refreshed:
try:
y, m, d = (int(x) for x in last_refreshed.split("-"))
stale_days = (date.today() - date(y, m, d)).days
except (ValueError, IndexError):
stale_days = None
return iocs, stale_days
def discover_lockfiles(root: Path) -> tuple[list[Path], list[Path], list[Path]]:
"""Discover lockfiles under `root`, skipping installed-artifact dirs and not
following symlinks. Entries are consumed lazily so a single hostile giant
directory cannot be materialized before the global discovery bound applies.
Returns (regular, symlinked, traversal_errors): a lockfile that is itself a
SYMLINK is NOT read (following it could be unsafe/exfil) but is also NOT
silently dropped. Directory traversal errors are likewise retained so the
caller cannot certify an incompletely walked tree clean. (In the hardened
prep flow the clone uses core.symlinks=false; these fail-closed paths also
protect standalone `ioc <dir>` use.)"""
found: list[Path] = []
symlinked: list[Path] = []
traversal_errors: list[Path] = []
entries_seen = 0
def limit_error(kind: str) -> Path:
return root / f".coldclone-{kind}-limit-exceeded"
pending = [root]
while pending:
directory = pending.pop()
try:
iterator_context = os.scandir(directory)
with iterator_context as iterator:
for entry in iterator:
entries_seen += 1
if entries_seen >= _DISCOVERY_ENTRY_LIMIT:
traversal_errors.append(limit_error("entry"))
return sorted(found), sorted(symlinked), sorted(
set(traversal_errors)
)
path = Path(entry.path)
try:
is_symlink = entry.is_symlink()
if is_symlink:
is_directory = entry.is_dir(follow_symlinks=True)
if is_directory and entry.name in _SKIP_DIRS:
continue
if is_directory or _lockfile_kind(path, root) is not None:
if len(found) + len(symlinked) >= _LOCKFILE_COUNT_LIMIT:
traversal_errors.append(limit_error("lockfile"))
return sorted(found), sorted(symlinked), sorted(
set(traversal_errors)
)
symlinked.append(path)
continue
if entry.is_dir(follow_symlinks=False):
if entry.name not in _SKIP_DIRS:
pending.append(path)
continue
if _lockfile_kind(path, root) is None:
continue
if not entry.is_file(follow_symlinks=False):
traversal_errors.append(path)
continue
if len(found) + len(symlinked) >= _LOCKFILE_COUNT_LIMIT:
traversal_errors.append(limit_error("lockfile"))
return sorted(found), sorted(symlinked), sorted(
set(traversal_errors)
)
found.append(path)
except OSError:
traversal_errors.append(path)
except OSError as exc:
traversal_errors.append(
Path(exc.filename) if exc.filename else directory
)
return sorted(found), sorted(symlinked), sorted(set(traversal_errors))
# A package-identifier-shaped run of characters (scope, name, path separators,
# version separator). We extract these tokens per line, then DERIVE candidate
# package identities from each and exact-match them against the IoC set — exact
# membership, not a boundary regex, so there is no substring false-positive tail.
_TOKEN_RE = re.compile(r"[A-Za-z0-9_./@-]+")
_NM_MARKER = "node_modules/"
def _candidates(token: str):
"""Yield candidate package identities from one lockfile token.
Handles the real lockfile encodings across every ecosystem we scan:
- bare `name`, `name@version` (yarn/pnpm/requirements)
- `@scope/name`, `@scope/name@version` (scoped npm)
- npm package-lock v3 keys `node_modules/<name>` and nested
`.../node_modules/@scope/name` (the DEFAULT npm format)
- pnpm `/<name>@ver` keys (leading slash)
- slash-delimited paths, e.g. go.sum `host/owner/<name>`
Scope safety: a scoped `@scope/name` yields ONLY `@scope/name`, never the bare
`name`, so an unscoped IoC cannot false-match a differently-scoped package
(`@other/node-loggers` does NOT trip IoC `node-loggers`). A non-scoped path
DOES split into components, so `node_modules/node-loggers` and
`github.com/x/formstash` resolve to `node-loggers` / `formstash`.
"""
t = token.strip().strip("\"'")
if not t:
return
# Strip a trailing @version. A version `@` is preceded by a NAME char; a SCOPE
# `@` is at index 0 or preceded by `/` (`@scope/n`, `node_modules/@scope/n`),
# so it must NOT be stripped. Find the last `@` whose previous char is not `/`.
for i in range(len(t) - 1, 0, -1):
if t[i] == "@" and t[i - 1] != "/":
t = t[:i]
break
idx = t.rfind(_NM_MARKER) # npm nesting: keep only the part after the LAST node_modules/
if idx != -1:
t = t[idx + len(_NM_MARKER):]
t = t.strip("/")
if not t:
return
yield t # full identity: bare `name` OR `@scope/name`
if not t.startswith("@"):
# Path-y token (go module path, or a registry tarball URL like
# `//registry.npmjs.org/@other/name/-/name-1.0.0.tgz`): each component is
# its own identity, BUT keep an `@scope/name` pair together so an unscoped
# IoC cannot false-match a scoped package's name embedded in a URL/path
# (`@other/node-loggers` must NOT yield bare `node-loggers`).
comps = [c for c in t.split("/") if c]
i = 0
while i < len(comps):
if comps[i].startswith("@") and i + 1 < len(comps):
yield f"{comps[i]}/{comps[i + 1]}"
i += 2
else:
yield comps[i]
i += 1
def _is_exact_registry_version(
version: str, ecosystem: str | None = None
) -> bool:
"""Return true only for a canonical exact registry release.
npm and crates.io both use SemVer release identities. Requiring the full
three-part form prevents a malformed policy typo from silently turning an
identity into a version-scoped allow-by-default rule. PyPI releases are
PEP 440 public versions in their canonical normalized spelling.
"""
if ecosystem == "PyPI":
return (
_pep440_key(version) is not None
and _pep440_canonical(version) == version
)
if ecosystem not in (None, "npm", "crates.io"):
return False
if not version or len(version) > 128:
return False
return _EXACT_SEMVER_RE.fullmatch(version) is not None
def _is_policy_package_identity(
package: str, ecosystem: str | None = None
) -> bool:
"""Validate identity shapes accepted by VERSION records.
PyPI names must already be PEP 503-normalized, so one policy spelling
covers every equivalent lockfile spelling.
"""
if ecosystem == "PyPI":
return (
len(package) <= 128
and re.fullmatch(r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", package)
is not None
and _pep503(package) == package
)
return re.fullmatch(
r"(?:@[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+|[A-Za-z0-9_.-]+)", package
) is not None
# PEP 440 public/local version grammar (the spec's appendix pattern), without
# the surrounding whitespace the spec tolerates: an oddly spaced lockfile
# version is untrusted evidence, never silently accepted.
_PEP440_RE = re.compile(
r"""
v?
(?:(?P<epoch>[0-9]+)!)?
(?P<release>[0-9]+(?:\.[0-9]+)*)
(?P<pre>
[-_.]?(?P<pre_l>alpha|a|beta|b|preview|pre|c|rc)[-_.]?(?P<pre_n>[0-9]+)?
)?
(?P<post>
-(?P<post_n1>[0-9]+)
|[-_.]?(?P<post_l>post|rev|r)[-_.]?(?P<post_n2>[0-9]+)?
)?
(?P<dev>[-_.]?dev[-_.]?(?P<dev_n>[0-9]+)?)?
(?:\+(?P<local>[a-z0-9]+(?:[-_.][a-z0-9]+)*))?
""",
re.VERBOSE | re.IGNORECASE | re.ASCII,
)
_PEP440_PRE_ALIASES = {
"alpha": "a", "a": "a", "beta": "b", "b": "b",
"c": "rc", "pre": "rc", "preview": "rc", "rc": "rc",
}
def _pep440_parts(
version: object,
) -> tuple[int, tuple[int, ...], tuple[str, int] | None, int | None, int | None] | None:
"""Parse a PEP 440 *public* version; None if invalid or local (`+tag`)."""
if (
not isinstance(version, str)
or not version
or len(version) > 128
or not version.isascii()
):
return None
match = _PEP440_RE.fullmatch(version)
if match is None or match.group("local") is not None:
return None
epoch = int(match.group("epoch") or 0)
release = tuple(int(part) for part in match.group("release").split("."))
pre = None
if match.group("pre") is not None:
label = _PEP440_PRE_ALIASES.get(match.group("pre_l").lower())
if label is None:
return None
pre = (label, int(match.group("pre_n") or 0))
post = None
if match.group("post") is not None:
post = int(match.group("post_n1") or match.group("post_n2") or 0)
dev = None
if match.group("dev") is not None:
dev = int(match.group("dev_n") or 0)
return epoch, release, pre, post, dev
def _pep440_key(version: object) -> tuple[object, ...] | None:
"""Equality key for a public PEP 440 version (`1.82.7` == `1.82.7.0`).
Equality only: trailing zero release components are insignificant, while
an absent post/pre/dev segment differs from one numbered 0.
"""
parts = _pep440_parts(version)
if parts is None:
return None
epoch, release, pre, post, dev = parts
while len(release) > 1 and release[-1] == 0:
release = release[:-1]
return epoch, release, pre, post, dev
def _pep440_canonical(version: object) -> str | None:
"""The PEP 440 normalized spelling (as `packaging` prints it), or None."""
parts = _pep440_parts(version)
if parts is None:
return None
epoch, release, pre, post, dev = parts
text = f"{epoch}!" if epoch else ""
text += ".".join(str(part) for part in release)
if pre is not None:
text += f"{pre[0]}{pre[1]}"
if post is not None:
text += f".post{post}"
if dev is not None:
text += f".dev{dev}"
return text
def _is_plain_policy_identity(package: str) -> bool:
"""Validate bounded cross-ecosystem identities accepted as plain records."""
if not package or len(package) > 256:
return False
return re.fullmatch(
r"(?:"
r"@[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+"
r"|[A-Za-z0-9][A-Za-z0-9_.-]*"
r"|[A-Za-z0-9][A-Za-z0-9_.-]*(?:/[A-Za-z0-9][A-Za-z0-9_.@+-]*)+"
r")",
package,
) is not None
def _npm_alias_target(value: object) -> tuple[str, str | None] | None:
"""Return (target, exact-version-or-None) for an npm alias specifier."""
if not isinstance(value, str) or not value.startswith("npm:"):
return None
target_with_range = value[len("npm:"):]
split_at = target_with_range.rfind("@")
if split_at <= 0:
return None
target = target_with_range[:split_at]
version = target_with_range[split_at + 1:]
if not _is_policy_package_identity(target) or not version:
return None
return target, version if _is_exact_registry_version(version) else None
def _extract_package_lock_version_info(
lockfile: Path, package: str, text: str | None = None
) -> LockfilePackageVersions:
duplicate_key = False
def object_pairs(pairs: list[tuple[str, object]]) -> dict[str, object]:
nonlocal duplicate_key
result: dict[str, object] = {}
for key, value in pairs:
if key in result:
duplicate_key = True
result[key] = value
return result
try:
if text is None:
text = lockfile.read_text(encoding="utf-8", errors="strict")
data = json.loads(
text,
object_pairs_hook=object_pairs,
)
except (OSError, UnicodeError, ValueError, RecursionError):
return LockfilePackageVersions(mixed_or_untrusted=True)
versions: set[str] = set()
untrusted = duplicate_key
alias_referenced = False
alias_resolved = False
def consider(
value: object, *, alias_version: str | None = None, alias: bool = False
) -> None:
nonlocal untrusted, alias_resolved
if not isinstance(value, dict):
untrusted = True
return
version = alias_version if alias_version is not None else value.get("version")
if isinstance(version, str) and _is_exact_registry_version(version):
versions.add(version)
if alias or alias_version is not None:
alias_resolved = True
for field_name in ("resolved", "_resolved"):
resolved = value.get(field_name)
if resolved is not None and not (
isinstance(resolved, str)
and _tarball_url_matches(resolved, package, version)
):
# npm downloads `resolved` (or, without it, `_resolved`)
# verbatim, and the attacker also writes `integrity`: it
# must be exactly this release's tarball.
untrusted = True
source = value.get("from")
if source is not None and (
not isinstance(source, str) or _has_fetch_marker(source)
or source.startswith("file:")
):
# Legacy `from` is fetched when `resolved` is absent.
untrusted = True
else:
untrusted = True
def check_foreign(value: object) -> None:
"""A record installing another identity must not fetch the package."""
nonlocal untrusted
if not isinstance(value, dict) or value.get("link") is True:
return
for field_name in ("resolved", "_resolved", "from", "version"):
spec = value.get(field_name)
if (
isinstance(spec, str)
and not _is_local_directory_resolution(spec)
and _mentions_package(spec, package)
):
untrusted = True
def alias_for(value: object) -> str | None:
nonlocal alias_referenced
parsed = _npm_alias_target(value)
if parsed is None or parsed[0] != package:
return None
alias_referenced = True
return parsed[1]
def scan_packages(packages: object) -> None:
nonlocal untrusted, alias_referenced, alias_resolved
if not isinstance(packages, dict):
untrusted = True
return
for key, value in packages.items():
normalized = str(key).replace("\\", "/")
if normalized and posixpath.normpath(normalized) != normalized:
# npm resolves `node_modules/./keyv` or `a/../keyv` to the
# installed location; npm never writes such keys.
untrusted = True
if normalized == f"node_modules/{package}" or normalized.endswith(
f"/node_modules/{package}"
):
installed = value.get("name") if isinstance(value, dict) else None
if isinstance(installed, str) and installed != package:
# An alias location: it installs `name`, not `package`.
check_foreign(value)
continue
consider(value)
continue
if not isinstance(value, dict) or _NM_MARKER not in normalized:
check_foreign(value)
continue
# npm aliases are installed under the alias location, while either
# the record's `name` or its `npm:<target>@<version>` value carries
# the actual registry identity.
owned = False
if value.get("name") == package:
alias_referenced = True
owned = True
consider(value, alias=True)
alias_version = alias_for(value.get("version"))
if alias_version is not None:
owned = True
consider(value, alias_version=alias_version)
if not owned:
check_foreign(value)
def scan_dependencies(dependencies: object) -> None:
nonlocal untrusted
if not isinstance(dependencies, dict):
untrusted = True
return
stack = [dependencies]
while stack:
deps = stack.pop()
if package in deps:
local = deps.get(package)
target = (
_npm_alias_target(local.get("version"))
if isinstance(local, dict) else None
)
if target is not None and target[0] != package:
# An alias local name: it installs `target`, not `package`.
check_foreign(local)
else:
consider(local)
for name, value in deps.items():
if isinstance(value, dict):
alias_version = alias_for(value.get("version"))
if alias_version is not None:
consider(value, alias_version=alias_version)
elif name != package:
check_foreign(value)
if isinstance(value, dict) and isinstance(
value.get("dependencies"), dict
):
stack.append(value["dependencies"])
def scan_alias_references(root: object) -> None:
"""Notice alias declarations even when their install record is absent."""
stack = [root]
while stack:
value = stack.pop()
if isinstance(value, dict):
stack.extend(value.keys())
stack.extend(value.values())
elif isinstance(value, list):
stack.extend(value)
else:
alias_for(value)
if not isinstance(data, dict):
untrusted = True
else:
scan_alias_references(data)
lockfile_version = data.get("lockfileVersion")
if type(lockfile_version) is not int or lockfile_version not in (1, 2, 3):
untrusted = True
elif lockfile_version == 1:
scan_dependencies(data.get("dependencies"))
if "packages" in data:
untrusted = True
elif lockfile_version == 2:
scan_packages(data.get("packages"))
scan_dependencies(data.get("dependencies"))
else: # lockfileVersion == 3
scan_packages(data.get("packages"))
if "dependencies" in data:
untrusted = True
if alias_referenced and not alias_resolved:
untrusted = True
return LockfilePackageVersions(
versions=tuple(sorted(versions)), mixed_or_untrusted=untrusted
)
def _yarn_descriptor_name(descriptor: str) -> str:
descriptor = descriptor.strip().strip("\"'")
if descriptor.startswith("@"):
idx = descriptor.find("@", 1)
return descriptor if idx == -1 else descriptor[:idx]
return descriptor.split("@", 1)[0]