forked from unslothai/unsloth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscan_packages.py
More file actions
3290 lines (2932 loc) · 127 KB
/
Copy pathscan_packages.py
File metadata and controls
3290 lines (2932 loc) · 127 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
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
#
# .github/workflows/security-audit.yml's pip-scan-packages job depends
# on this file existing at scripts/scan_packages.py.
"""
scan_packages.py -- Standalone pre-install package scanner.
Downloads PyPI packages WITHOUT installing them and inspects archive
contents for malicious patterns: weaponized .pth files, credential
stealers, obfuscated payloads, install-time droppers.
Motivated by the litellm 1.82.7/1.82.8 supply chain attack (March 2026).
Single file, stdlib only, Python 3.10+.
Examples:
# Scan specific packages
python scan_packages.py requests==2.32.5
python scan_packages.py fastapi uvicorn pydantic
# Scan requirements files
python scan_packages.py -r requirements.txt
python scan_packages.py -r base.txt -r extras.txt
# Auto-discover requirements files in a project
python scan_packages.py -d ./my-project/
# Scan with full transitive dependency tree
python scan_packages.py --with-deps unsloth unsloth-zoo
# Scan + auto-fix CRITICAL findings in requirements files
python scan_packages.py --fix -r requirements.txt
python scan_packages.py --fix --max-search 20 -r requirements.txt
# Triage to a baseline once, then gate on anything NEW
python scan_packages.py -r requirements.txt --write-baseline scripts/scan_packages_baseline.json
python scan_packages.py -r requirements.txt # auto-loads the baseline, exits 0 if only baselined findings remain
False positives:
.py files are scanned code-only: comments and bare docstrings/doctests are
blanked before pattern matching (line numbers preserved), so prose, usage
examples and `>>>` doctests cannot trip a finding. Residual findings that
are genuine library behavior (a HTTP client reading HF_TOKEN, a vendored
test fixture) are suppressed via a reviewed baseline allowlist, matched on
(package, package-relative file, check, evidence hash). A new check, or
changed flagged code under the same check, reopens the finding; version
bumps and line shifts do not. This mirrors the Hugging Face Hub approach
(ClamAV/picklescan: low-FP, signature/structural, surface status).
Exit codes:
0 -- no non-baselined CRITICAL or HIGH findings (or --write-baseline)
1 -- non-baselined CRITICAL or HIGH findings detected
2 -- no packages specified, or scan incomplete (pip download failure)
"""
import argparse
import atexit
import bisect
import hashlib
import io
import json
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import tokenize
import urllib.parse
import urllib.request
import zipfile
from dataclasses import dataclass, field
from pathlib import Path
# Severity
CRITICAL = "CRITICAL"
HIGH = "HIGH"
MEDIUM = "MEDIUM"
SEVERITY_ORDER = {CRITICAL: 0, HIGH: 1, MEDIUM: 2}
# Hard pin-blocks for confirmed malicious PyPI versions (Socket.dev 2026-05-12
# Mini Shai-Hulud wave; earlier Semgrep/Endor reports for `lightning`).
BLOCKED_PYPI_VERSIONS: dict[str, set[str]] = {
"guardrails-ai": {"0.10.1"},
"mistralai": {"2.4.6"},
"lightning": {"2.6.2", "2.6.3"},
}
# Pattern definitions
# Subprocess / OS exec patterns
RE_SUBPROCESS = re.compile(
r"\bsubprocess\s*\.\s*(Popen|call|run|check_call|check_output)\b"
r"|\bos\s*\.\s*(system|popen|exec[lv]p?e?)\b",
)
# Encoding / obfuscation
RE_BASE64 = re.compile(
r"\bbase64\s*\.\s*(b64decode|decodebytes|b32decode|b16decode)\b|\bcodecs\s*\.\s*decode\b",
)
# exec / eval
RE_EXEC_EVAL = re.compile(r"\b(exec|eval)\s*\(")
# Network APIs (excludes urllib.parse which is pure string manipulation)
RE_NETWORK = re.compile(
r"\burllib\.request\b"
r"|\burlopen\s*\("
r"|\brequests\s*\.\s*(get|post|put|patch|delete|head|Session)\b"
r"|\bhttpx\s*\.\s*(get|post|put|patch|delete|Client|AsyncClient)\b"
r"|\bsocket\s*\.\s*(socket|create_connection)\b"
r"|\bhttp\.client\b"
r"|\bhttp\.server\b",
)
# Large base64 blob (>200 chars of contiguous base64 alphabet)
RE_LARGE_BLOB = re.compile(r"[A-Za-z0-9+/=]{200,}")
# Credential path access (requires file-access context, not just string mentions)
RE_CRED_ACCESS = re.compile(
r"(?:open|Path|read_text|read_bytes)\s*\([^)]*?"
r"(?:\.ssh[/\\]|\.aws[/\\]|\.kube[/\\]|\.gnupg[/\\]|\.docker[/\\]"
r"|\.azure[/\\]|\.gcp[/\\]"
r"|credentials\.json|\.git-credentials|\.npmrc|\.pypirc|wallet\.dat"
r"|/etc/shadow|/etc/passwd"
r"|id_rsa|id_ed25519|id_ecdsa"
r"|kubeconfig|service-account-token)"
r"|os\.path\.(?:join|expanduser)\([^)]*?"
r"(?:\.ssh|\.aws|\.kube|\.gnupg|\.docker|\.azure|\.gcp|credentials)"
r"|(?:open|Path)\(\s*['\"]\.env['\"]\s*[,)]",
re.DOTALL,
)
# Chained / advanced obfuscation (marshal, compile, zlib, nested decode)
RE_OBFUSCATION = re.compile(
r"\bmarshal\s*\.\s*(loads|load)\b"
r"|\bcompile\s*\([^)]*['\"]exec['\"]\s*\)"
r"|\bzlib\s*\.\s*decompress\b"
r"|\blzma\s*\.\s*decompress\b"
r"|\bbz2\s*\.\s*decompress\b"
r"|\bbytearray\s*\(\s*\[.*?\]\s*\)" # bytearray([104,101,...])
r"|\bchr\s*\(\s*\d+\s*\).*chr\s*\(\s*\d+\s*\)" # chr() obfuscation chains
r"|\b__import__\s*\(" # dynamic import
r"|\bgetattr\s*\(\s*__builtins__" # getattr(__builtins__, ...)
r"|\brotate\s*=.*\blambda\b.*\bchr\b" # rotation ciphers
r"|\b(?:b64decode|decodebytes)\s*\(.*(?:b64decode|decodebytes)\s*\(", # double base64
re.DOTALL,
)
# Embedded cryptographic keys (PEM-encoded)
RE_EMBEDDED_KEYS = re.compile(
r"-----BEGIN\s+(?:RSA\s+)?(?:PUBLIC|PRIVATE|ENCRYPTED|EC|DSA|OPENSSH)\s+KEY-----"
r"|\bRSA\s+PUBLIC\s+KEY\b.*[A-Za-z0-9+/=]{64,}"
r"|\bMII[A-Za-z0-9+/]{20,}", # DER-encoded key prefix (base64)
re.DOTALL,
)
# Full PEM block (BEGIN..END), used to pin a multiline key body in evidence.
RE_PEM_BLOCK = re.compile(r"-----BEGIN[^\n]*KEY-----.*?-----END[^\n]*KEY-----", re.DOTALL)
# Cloud metadata / IMDS endpoints
RE_CLOUD_METADATA = re.compile(
r"169\.254\.169\.254" # AWS/Azure/GCP IMDS
r"|metadata\.google\.internal" # GCP metadata
r"|169\.254\.170\.2" # AWS ECS task metadata
r"|100\.100\.100\.200" # Alibaba Cloud metadata
r"|/latest/meta-data" # AWS IMDS path
r"|/metadata/instance" # GCP metadata path
r"|/metadata/identity" # Azure managed identity
r"|\bIMDSv[12]\b",
)
# Persistence mechanisms (systemd, cron, launchd, registry, startup dirs)
RE_PERSISTENCE = re.compile(
r"/etc/systemd/"
r"|systemctl\s+(enable|start|daemon-reload)"
r"|\.service\b.*\[Service\]" # systemd unit content
r"|/etc/cron"
r"|crontab\s"
r"|/etc/init\.d/"
r"|/Library/LaunchDaemons"
r"|/Library/LaunchAgents"
r"|~/\.config/autostart"
r"|~/.local/share/systemd"
r"|~/\.config/systemd/user/" # user-level systemd
r"|HKEY_LOCAL_MACHINE.*\\\\Run" # Windows registry autorun
r"|HKEY_CURRENT_USER.*\\\\Run"
r"|\\\\Start Menu\\\\Programs\\\\Startup"
r"|schtasks\s", # Windows scheduled tasks
re.IGNORECASE,
)
# Container / orchestration abuse
RE_CONTAINER_ABUSE = re.compile(
r"/var/run/docker\.sock"
r"|\bdocker\s+(run|exec|cp|build)\b"
r"|\bkubectl\s+(apply|create|exec|run|cp)\b"
r"|\bkubernetes\.client\b"
r"|\bfrom_incluster_config\b"
r"|\blist_namespaced_secret\b"
r"|\bcreate_namespaced_pod\b"
r"|\bcreate_namespaced_daemon_set\b"
r"|\bcreate_namespaced_secret\b"
r"|\bkube-system\b"
r"|\bhostPID\s*:\s*true"
r"|\bprivileged\s*:\s*true"
r"|\bhostNetwork\s*:\s*true"
r"|\bhostPath\b.*\bpath\s*:\s*/", # k8s hostPath mounts
re.IGNORECASE,
)
# Environment variable harvesting (bulk access or known secret vars)
RE_ENV_HARVEST = re.compile(
r"\bos\.environ\s*\.\s*copy\s*\(" # full env copy
r"|\bdict\s*\(\s*os\.environ\s*\)"
r"|\bjson\.dumps\s*\(\s*(?:dict\s*\(\s*)?os\.environ"
r"|\bfor\s+\w+\s*,\s*\w+\s+in\s+os\.environ\.items\(\)" # iterating all env vars
r"|\bos\.environ\b.*(?:SECRET|TOKEN|KEY|PASSWORD|CREDENTIAL|API_KEY|PRIVATE)"
r"|\b(?:SECRET|TOKEN|PASSWORD|API_KEY|PRIVATE_KEY)\b.*os\.environ",
re.IGNORECASE,
)
# Archive staging / exfiltration prep (create archive + network send)
RE_ARCHIVE_STAGING = re.compile(
r"\btarfile\s*\.\s*open\s*\("
r"|\bzipfile\s*\.\s*ZipFile\s*\([^)]*['\"]w['\"]\s*\)"
r"|\bshutil\s*\.\s*make_archive\b"
r"|\b\.add\s*\([^)]*(?:\.ssh|\.aws|\.env|\.kube|credentials|\.gnupg|\.docker)"
r"|\b\.write\s*\([^)]*(?:\.ssh|\.aws|\.env|\.kube|credentials|\.gnupg|\.docker)",
re.DOTALL,
)
# Anti-analysis / sandbox evasion / debugger detection
# NB: deliberately does NOT include a bare ``platform.system() ... Linux/Windows
# /Darwin`` branch. Under re.DOTALL that matched across the whole file -- any
# cross-platform library (typer, packaging, pandas, pymupdf, ...) trips it -- so
# it had ~zero precision and only generated false positives. OS detection alone
# is not an anti-analysis signal; the debugger/VM/long-sleep signals below are.
RE_ANTI_ANALYSIS = re.compile(
r"\bptrace\b"
r"|\bsys\s*\.\s*gettrace\s*\("
r"|\bsys\s*\.\s*settrace\b"
r"|\bTracerPid\b"
# /proc/self/status is read to scrape TracerPid for anti-debug. A leading
# \b here is unsatisfiable (\b never holds between a non-word boundary and
# "/"), so the old pattern was dead; a lookbehind that only forbids a
# preceding word char or path separator lets `open("/proc/self/status")`
# and `cat /proc/self/status` match while avoiding mid-path partials.
r"|(?<![\w/])/proc/self/status\b"
r"|\bIsDebuggerPresent\b"
r"|\bvirtualbox\b.*\bhardware\b"
r"|\bvmware\b.*\bdetect\b"
r"|\btime\.sleep\s*\(\s*(?:[3-9]\d{2,}|[1-9]\d{3,})\s*\)", # long sleep (anti-sandbox)
re.IGNORECASE | re.DOTALL,
)
# DNS exfiltration / tunneling
RE_DNS_EXFIL = re.compile(
r"\bdns\.resolver\b"
r"|\bsocket\.getaddrinfo\s*\([^)]*\+[^)]*\)" # dynamic hostname construction
r"|\bdnspython\b"
r"|\bTXT\b.*\bresolver\b"
r"|\bresolver\b.*\bTXT\b"
r"|\bnslookup\b"
r"|\bdig\s+",
)
# File system enumeration / bulk file theft
RE_FS_ENUM = re.compile(
r"\bos\.walk\s*\(\s*['\"](?:/|~|/home|/root|/Users|C:\\\\)"
r"|\bglob\s*\.\s*glob\s*\([^)]*(?:\*\*|\*\.pem|\*\.key|\*\.cer|\*\.pfx|\*\.p12)"
r"|\bos\.listdir\s*\(\s*['\"](?:/home|/root|/Users|/etc)"
r"|\bPath\s*\(\s*['\"]~['\"]\s*\)\s*\.\s*glob\b"
r"|\bhistory\b.*\bread\b" # reading shell history
r"|\b\.bash_history\b"
r"|\b\.zsh_history\b"
r"|/etc/shadow"
r"|/etc/passwd",
re.DOTALL,
)
# Reverse shell / bind shell patterns
RE_REVERSE_SHELL = re.compile(
r"\bsocket\b.*\bconnect\b.*\bsubprocess\b"
r"|\bsocket\b.*\bconnect\b.*\b(?:sh|bash|cmd)\b"
r"|\b/bin/(?:sh|bash)\b.*\bsocket\b"
r"|\bpty\s*\.\s*spawn\b"
r"|\bos\s*\.\s*dup2\s*\("
r"|\bwebbrowser\s*\.\s*open\b.*\bdata:\b", # data: URI abuse
re.DOTALL,
)
# Process injection / code loading from remote
RE_REMOTE_CODE = re.compile(
r"\bexec\s*\(\s*(?:urllib|requests|httpx|urlopen)" # exec(requests.get(...))
r"|\bexec\s*\([^)]*\.(?:text|content|read)\s*\("
r"|\beval\s*\([^)]*\.(?:text|content|read)\s*\("
r"|\bimportlib\s*\.\s*import_module\s*\([^)]*\+" # dynamic import with concatenation
r"|\b__import__\s*\([^)]*\+", # __import__ with concatenation
re.DOTALL,
)
# Crypto wallet / cryptocurrency theft
RE_CRYPTO_THEFT = re.compile(
r"\bwallet\.dat\b"
r"|\b\.bitcoin[/\\]"
r"|\b\.ethereum[/\\]"
r"|\b\.solana[/\\]"
r"|\b\.monero[/\\]"
r"|\b\.litecoin[/\\]"
r"|\b\.config/solana[/\\]"
r"|\bkeystore[/\\]UTC--"
r"|\bseed\s*phrase\b"
r"|\bmnemonic\b.*\b(?:word|phrase|recover|restore)\b"
r"|\b(?:xprv|xpub|bc1|0x[a-fA-F0-9]{40})\b",
re.IGNORECASE,
)
# Import line in .pth (Python site.py only exec()s lines starting with "import")
RE_PTH_IMPORT = re.compile(r"^\s*import\s+", re.MULTILINE)
# openssl CLI invocations via subprocess (encrypted exfiltration)
RE_OPENSSL_CLI = re.compile(r"\bopenssl\s+(enc|rand|rsautl|pkeyutl|genrsa|dgst|s_client)\b")
# Write to /tmp then execute (staged dropper)
RE_TEMP_EXEC = re.compile(
r"/tmp/\S+.*(?:subprocess|os\.system|os\.popen|Popen|chmod.*\+x)",
re.DOTALL,
)
# C2 polling / beaconing loop
RE_C2_POLLING = re.compile(
r"while\s+True.*(?:time\.sleep|sleep)\s*\(.*(?:urlopen|requests\.|httpx\.)",
re.DOTALL,
)
# Developer-tool persistence hooks. Lightning 2.6.x planted SessionStart hooks
# into Claude Code / VS Code / Cursor so the payload re-attached on editor open.
RE_DEV_TOOL_HIJACK = re.compile(
r"\.claude/settings\.json"
r"|\.cursor/.*hooks"
r"|\.vscode/(?:tasks|settings|launch)\.json"
r"|SessionStart|folderOpen|onCommand:.*runTask"
r"|/etc/profile\.d/"
r"|\b\.bashrc\b|\b\.zshrc\b|\b\.profile\b"
r"|\bautomator\b.*\.workflow\b",
)
# Hard-coded credential / API-token regexes embedded in source. Packages that
# ship regexes for OTHER people's secrets are nearly always stealers.
RE_TOKEN_REGEX = re.compile(
r"\bgh[psoru]_[A-Za-z0-9_]{20,}" # GitHub PAT/OAuth/etc.
r"|\bgithub_pat_[A-Za-z0-9_]{20,}"
r"|\bnpm_[A-Za-z0-9]{30,}" # npm token
r"|\bsk-[A-Za-z0-9]{20,}" # OpenAI / Anthropic
r"|\bxox[bpaesr]-" # Slack
r"|\bAIza[0-9A-Za-z_-]{20,}" # Google API key
r"|\bAKIA[0-9A-Z]{16}" # AWS access key id
r"|\bASIA[0-9A-Z]{16}" # AWS STS
r"|\bgithub.com/login/oauth/access_token"
r"|\bglpat-[0-9A-Za-z_-]{20,}", # GitLab PAT
)
# Mini Shai-Hulud May-12 2026 wave indicators. `transformers.pyz` dropper name
# is high-confidence; the host + slogans are CRITICAL.
RE_MAY12_IOC = re.compile(
r"(git-tanstack\.com|/tmp/transformers\.pyz|transformers\.pyz"
r"|With Love TeamPCP|We've been online over 2 hours)",
re.IGNORECASE,
)
# JavaScript-side obfuscation. A bundle full of `_0x1f2e3d` hex-var identifiers
# is a near-universal tell for a malicious npm payload, rare in legit wheels.
RE_JS_OBFUSCATION = re.compile(
r"_0x[a-f0-9]{4,6}\s*=\s*function"
r"|var\s+_0x[a-f0-9]{4,6}\b"
r"|(?:\\x[0-9a-f]{2}){10,}" # \x-escape strings
r"|String\.fromCharCode\s*\(\s*\d+\s*(?:,\s*\d+\s*){10,}\)",
)
# Web3 / wallet-hijack pattern. The Qix npm phish overrode fetch/XMLHttpRequest
# and swapped recipient addresses via a `window.ethereum` listener.
RE_WEB3_HIJACK = re.compile(
r"\bwindow\.ethereum\b"
r"|\bweb3\.eth\.\w+\s*\("
r"|XMLHttpRequest\.prototype\.(?:open|send)\s*="
r"|(?:^|\s)fetch\s*=\s*\(?\s*async"
r"|TronWeb|solanaWeb3",
)
# Self-propagating worms (Shai-Hulud, ForceMemo) plant their own GitHub workflow
# in every repo they reach and use trufflehog/gitleaks for credential discovery.
# Any of these strings in a package payload is strong repo-takeover evidence.
RE_WORKFLOW_INJECT = re.compile(
r"\.github/workflows/[^\"\']*\.ya?ml"
r"|\btrufflehog\b|\bgitleaks\b"
r"|/user/repos\?affiliation=.*owner.*collaborator"
r"|\bshai-hulud\b|EveryBoiWeBuildIsAWormyBoi"
r"|\bgit\s+push\s+--force\b.*--no-verify",
re.IGNORECASE | re.DOTALL,
)
# install.sh / postinstall scripts piping remote code into a shell.
# `curl ... | sh` is the canonical npm postinstall dropper.
RE_SHELL_DROPPER = re.compile(
r"\bcurl\b[^\n|]*\|\s*(?:sh|bash|zsh)\b"
r"|\bwget\b[^\n|]*-O-\s*\|\s*(?:sh|bash|zsh)\b"
r"|\bnpx\b\s+-y\s+[^\s]+@latest\s*\|"
r"|\beval\s+\$\(\s*curl\b"
r"|\bbash\s+<\(\s*curl\b",
)
@dataclass
class Finding:
severity: str
package: str
filename: str
check: str
evidence: str = ""
# Checkers
def check_pth_file(content: str, filename: str, package: str) -> list[Finding]:
"""Run all .pth-specific checks.
Executable .pth files run on every Python startup, so any suspicious
pattern in a .pth is treated as CRITICAL.
"""
findings = []
# Only .pth files with import lines are executable
import_lines = [line for line in content.splitlines() if RE_PTH_IMPORT.match(line)]
if not import_lines:
return findings # Pure path entries, inert
# All patterns are CRITICAL inside executable .pth files
_pth_checks = [
(RE_SUBPROCESS, ".pth has subprocess/os exec calls"),
(RE_BASE64, ".pth has base64/encoding obfuscation"),
(RE_EXEC_EVAL, ".pth has exec()/eval()"),
(RE_NETWORK, ".pth has network API calls"),
(
RE_OBFUSCATION,
".pth has advanced obfuscation (marshal/compile/zlib/__import__)",
),
(RE_EMBEDDED_KEYS, ".pth has embedded cryptographic key material"),
(RE_CLOUD_METADATA, ".pth accesses cloud metadata / IMDS endpoints"),
(RE_PERSISTENCE, ".pth installs persistence (systemd/cron/launchd/registry)"),
(RE_CONTAINER_ABUSE, ".pth interacts with container/orchestration runtime"),
(RE_ENV_HARVEST, ".pth harvests environment variables / secrets"),
(RE_ARCHIVE_STAGING, ".pth stages archive for exfiltration"),
(RE_ANTI_ANALYSIS, ".pth has anti-analysis / sandbox evasion"),
(RE_DNS_EXFIL, ".pth has DNS exfiltration / tunneling patterns"),
(RE_FS_ENUM, ".pth enumerates filesystem / steals files"),
(RE_REVERSE_SHELL, ".pth has reverse/bind shell patterns"),
(RE_REMOTE_CODE, ".pth loads and executes remote code"),
(RE_CRYPTO_THEFT, ".pth targets cryptocurrency wallets / keys"),
(RE_CRED_ACCESS, ".pth accesses credential files"),
(RE_OPENSSL_CLI, ".pth invokes openssl CLI (encrypted exfil pattern)"),
(RE_TEMP_EXEC, ".pth writes to /tmp and executes (staged dropper)"),
(RE_C2_POLLING, ".pth has C2 polling/beaconing loop"),
]
for pattern, description in _pth_checks:
if pattern.search(content):
findings.append(
Finding(
CRITICAL,
package,
filename,
description,
_extract_evidence(content, pattern),
)
)
# Large base64 blob
if RE_LARGE_BLOB.search(content):
# Digest every blob (not just the first 120 chars, and not just the
# first blob), so a later payload that keeps the prefix or appends a
# second encoded blob reopens.
blob, digest = _blob_digest(content)
findings.append(
Finding(
CRITICAL,
package,
filename,
f".pth has large base64-like blob ({len(blob)} chars)",
f"{blob[:120]}... sha256:{digest}",
)
)
# Catch-all: any import line in .pth if nothing else triggered. Bind every
# line through a digest so an appended/swapped import reopens the key, but cap
# the displayed text so a large .pth of benign-looking imports cannot dump up
# to the archive member cap into the logs or baseline JSON.
if not findings and import_lines:
evidence = _cap_line("\n".join(import_lines))
findings.append(
Finding(
HIGH,
package,
filename,
f".pth has {len(import_lines)} executable import line(s)",
evidence,
)
)
# Unusually large executable .pth (litellm's was 34 KB; legit ones are <100 bytes)
size = len(content)
if size > 500 and import_lines:
# Pin the content so a different payload of the same size/import count reopens.
digest = hashlib.sha256(content.encode("utf-8", "replace")).hexdigest()
findings.append(
Finding(
HIGH,
package,
filename,
f"Unusually large executable .pth ({size} bytes)",
f"{len(import_lines)} import line(s) in {size}-byte .pth file sha256:{digest}",
)
)
return findings
# A STRING after one of these tokens (and before a NEWLINE) is a bare
# docstring/doctest/prose statement -- the dominant FP source -- so we blank it.
# A string after `=` or `(` is real code and is never blanked.
_LINE_START_TOKENS = frozenset({tokenize.NEWLINE, tokenize.NL, tokenize.INDENT, tokenize.DEDENT})
def _is_fstring(tok_string: str) -> bool:
"""True if a STRING token is an f-string (3.10/3.11 emit one STRING token).
A bare f-string statement evaluates its expressions at import, so unlike an
inert docstring it must never be blanked.
"""
q = min((tok_string.find(c) for c in "'\"" if c in tok_string), default = -1)
return q > 0 and "f" in tok_string[:q].lower()
def _strip_noncode(content: str, blank_comments: bool = True) -> str:
"""Blank comments and bare docstrings so IOC patterns see code only.
Removed regions become spaces (newlines kept) so line numbers stay exact for
_extract_evidence. Fails open on tokenizer errors (the raw text is still
fully scanned, so a real detection is never lost). ``blank_comments=False``
keeps comments (only strings/docstrings blanked) to isolate the span that
exec() could actually run.
"""
try:
toks = list(tokenize.generate_tokens(io.StringIO(content).readline))
except (tokenize.TokenError, IndentationError, SyntaxError, ValueError):
return content
spans: list[tuple[int, int, int, int]] = [] # (srow, scol, erow, ecol)
prev_significant = tokenize.NEWLINE # start-of-file behaves like a new line
n = len(toks)
for i, tok in enumerate(toks):
ttype = tok.type
if ttype == tokenize.COMMENT:
if blank_comments:
spans.append((*tok.start, *tok.end))
continue # transparent; never advances prev_significant
if (
ttype == tokenize.STRING
and prev_significant in _LINE_START_TOKENS
and not _is_fstring(tok.string) # f-strings execute; never blank them
):
# Bare string only if it is the whole statement: next significant
# token must close the logical line.
j = i + 1
while j < n and toks[j].type in (tokenize.COMMENT, tokenize.NL):
j += 1
if j < n and toks[j].type == tokenize.NEWLINE:
spans.append((*tok.start, *tok.end))
prev_significant = ttype
continue
if ttype in (
tokenize.NL,
tokenize.NEWLINE,
tokenize.INDENT,
tokenize.DEDENT,
tokenize.ENCODING,
):
prev_significant = ttype
continue
prev_significant = ttype
if not spans:
return content
buf = content.splitlines(keepends = True)
for srow, scol, erow, ecol in spans:
for row in range(srow, erow + 1):
line = buf[row - 1]
if line.endswith("\n"):
body, nl = line[:-1], "\n"
elif line.endswith("\r"):
body, nl = line[:-1], "\r"
else:
body, nl = line, ""
start = scol if row == srow else 0
end = ecol if row == erow else len(body)
end = min(end, len(body))
if start < end:
body = body[:start] + (" " * (end - start)) + body[end:]
buf[row - 1] = body + nl
return "".join(buf)
# Payload carriers that are suspicious when hidden in a blanked region (a
# docstring/string) of a file that can dynamically execute strings.
_HIDDEN_PAYLOAD_PATTERNS = (
(RE_LARGE_BLOB, "large base64 blob"),
(RE_EMBEDDED_KEYS, "embedded key material"),
(RE_MAY12_IOC, "Shai-Hulud IOC string"),
(RE_OBFUSCATION, "marshal/compile/obfuscation"),
)
def _hidden_payload_findings(
original: str, stripped: str, filename: str, package: str
) -> list[Finding]:
"""Flag payloads that live only in the blanked (docstring/string) region of
a file that contains exec/eval. Such a string is invisible to code-only
scanning yet ``exec(__doc__)`` / ``exec(<str>)`` could still run it."""
if not RE_EXEC_EVAL.search(stripped):
return []
# Only docstrings/strings run via exec(__doc__)/exec(<str>); comments cannot.
# Isolate that span: keep comments as real code, take what string-blanking
# removed (length-preserved, so offsets stay exact for _extract_evidence).
code = _strip_noncode(original, blank_comments = False)
removed = "".join(o if o != s else " " for o, s in zip(original, code))
out = []
# The visible exec/eval line is what makes the hidden string executable, so
# bind it into every finding's evidence: otherwise a reviewed false positive
# that keeps the same hidden text but flips a harmless `eval("1+1")` to
# `exec(__doc__)` (now running the payload) keeps the same key and stays
# suppressed. Taken from `stripped` (real code), where the exec/eval lives.
trigger = _extract_evidence(stripped, RE_EXEC_EVAL)
def _hidden(pat):
# Carrier present in a blanked region but NOT in real code. A carrier in
# real code is already caught by the normal check, so restricting to
# blanked-only avoids re-flagging legitimate in-code constants.
return bool(pat.search(removed)) and not pat.search(stripped)
for pat, label in _HIDDEN_PAYLOAD_PATTERNS:
if _hidden(pat):
out.append(
Finding(
HIGH,
package,
filename,
"exec/eval with payload hidden in a docstring/string",
f"exec: {trigger}\n{label}: {_extract_evidence(removed, pat)}",
)
)
# Fetch-then-run dropper: a network call AND an os/subprocess exec that both
# live in the blanked region. Search the removed span directly (not "absent
# from real code") so a benign visible network/subprocess call cannot mask
# the docstring payload.
if RE_NETWORK.search(removed) and RE_SUBPROCESS.search(removed):
out.append(
Finding(
HIGH,
package,
filename,
"exec/eval with hidden network+exec payload",
f"exec: {trigger}\n"
f"network+exec: {_extract_evidence(removed, RE_NETWORK)} | "
f"{_extract_evidence(removed, RE_SUBPROCESS)}",
)
)
return out
def check_py_file(content: str, filename: str, package: str) -> list[Finding]:
"""Run all .py-specific checks."""
# Code-only scanning: strip comments/docstrings up front so prose, doctests
# and usage examples cannot manufacture false positives. Aligns with the
# Hugging Face Hub model (ClamAV/picklescan: low-FP, signature/structural).
original = content
content = _strip_noncode(content)
findings = _hidden_payload_findings(original, content, filename, package)
basename = os.path.basename(filename)
is_setup = basename in ("setup.py", "setup.cfg")
is_init = basename == "__init__.py"
# Pre-compute pattern matches
has_network = bool(RE_NETWORK.search(content))
has_subprocess = bool(RE_SUBPROCESS.search(content))
has_base64 = bool(RE_BASE64.search(content))
has_exec_eval = bool(RE_EXEC_EVAL.search(content))
has_creds = bool(RE_CRED_ACCESS.search(content))
has_blob = bool(RE_LARGE_BLOB.search(content))
has_obfuscation = bool(RE_OBFUSCATION.search(content))
has_keys = bool(RE_EMBEDDED_KEYS.search(content))
has_cloud_meta = bool(RE_CLOUD_METADATA.search(content))
has_persistence = bool(RE_PERSISTENCE.search(content))
has_container = bool(RE_CONTAINER_ABUSE.search(content))
has_env_harvest = bool(RE_ENV_HARVEST.search(content))
has_archive = bool(RE_ARCHIVE_STAGING.search(content))
has_anti = bool(RE_ANTI_ANALYSIS.search(content))
has_dns_exfil = bool(RE_DNS_EXFIL.search(content))
has_fs_enum = bool(RE_FS_ENUM.search(content))
has_rev_shell = bool(RE_REVERSE_SHELL.search(content))
has_remote_code = bool(RE_REMOTE_CODE.search(content))
has_crypto_theft = bool(RE_CRYPTO_THEFT.search(content))
has_openssl_cli = bool(RE_OPENSSL_CLI.search(content))
has_temp_exec = bool(RE_TEMP_EXEC.search(content))
has_c2_polling = bool(RE_C2_POLLING.search(content))
has_may12_ioc = bool(RE_MAY12_IOC.search(content))
# CRITICAL: combination patterns that strongly indicate malice
# base64 decode + subprocess execution (staged payload)
if has_base64 and has_subprocess:
findings.append(
Finding(
CRITICAL,
package,
filename,
"base64 decode + subprocess execution (staged payload)",
f"Base64: {_extract_evidence(content, RE_BASE64)}\n"
f"Subprocess: {_extract_evidence(content, RE_SUBPROCESS)}",
)
)
# openssl encryption + network/key material (encrypted exfiltration)
if has_openssl_cli and (has_network or has_keys):
# Bind whichever side(s) co-occur so a changed endpoint or key reopens.
evidence = [f"OpenSSL: {_extract_evidence(content, RE_OPENSSL_CLI)}"]
if has_network:
evidence.append(f"Network: {_extract_evidence(content, RE_NETWORK)}")
if has_keys:
evidence.append(f"Key: {_embedded_key_evidence(content)}")
findings.append(
Finding(
CRITICAL,
package,
filename,
"openssl encryption + network/key material (encrypted exfiltration)",
"\n".join(evidence),
)
)
# Writes to /tmp and executes (staged dropper)
if has_temp_exec:
findings.append(
Finding(
CRITICAL,
package,
filename,
"Writes to /tmp and executes (staged dropper)",
_extract_evidence(content, RE_TEMP_EXEC),
)
)
# May-12 Shai-Hulud IOC string in Python source.
if has_may12_ioc:
findings.append(
Finding(
CRITICAL,
package,
filename,
"May-12 Shai-Hulud IOC string present in Python file",
_extract_evidence(content, RE_MAY12_IOC),
)
)
# C2 polling/beaconing loop
if has_c2_polling:
findings.append(
Finding(
CRITICAL,
package,
filename,
"C2 polling/beaconing loop detected",
_extract_evidence(content, RE_C2_POLLING),
)
)
# Credential stealer: reads cred paths AND phones home
if has_creds and has_network:
findings.append(
Finding(
CRITICAL,
package,
filename,
"Reads credential paths AND makes network calls",
f"Creds: {_extract_evidence(content, RE_CRED_ACCESS)}\n"
f"Network: {_extract_evidence(content, RE_NETWORK)}",
)
)
# Reverse / bind shell
if has_rev_shell:
findings.append(
Finding(
CRITICAL,
package,
filename,
"Reverse shell / bind shell pattern",
_extract_evidence(content, RE_REVERSE_SHELL),
)
)
# Remote code execution: exec/eval on HTTP response
if has_remote_code:
findings.append(
Finding(
CRITICAL,
package,
filename,
"Downloads and executes remote code",
_extract_evidence(content, RE_REMOTE_CODE),
)
)
# Env harvest + network exfil
if has_env_harvest and has_network:
findings.append(
Finding(
CRITICAL,
package,
filename,
"Harvests environment variables/secrets AND makes network calls",
f"Env: {_extract_evidence(content, RE_ENV_HARVEST)}\n"
f"Network: {_extract_evidence(content, RE_NETWORK)}",
)
)
# Filesystem enum + network exfil
if has_fs_enum and has_network:
findings.append(
Finding(
CRITICAL,
package,
filename,
"Enumerates filesystem AND makes network calls",
f"FS: {_extract_evidence(content, RE_FS_ENUM)}\n"
f"Network: {_extract_evidence(content, RE_NETWORK)}",
)
)
# Cloud metadata access + network (exfil IMDS tokens)
if has_cloud_meta and has_network:
findings.append(
Finding(
CRITICAL,
package,
filename,
"Accesses cloud metadata/IMDS AND makes network calls",
f"IMDS: {_extract_evidence(content, RE_CLOUD_METADATA)}\n"
f"Network: {_extract_evidence(content, RE_NETWORK)}",
)
)
# Crypto wallet theft + network
if has_crypto_theft and has_network:
findings.append(
Finding(
CRITICAL,
package,
filename,
"Targets cryptocurrency wallets AND makes network calls",
f"Crypto: {_extract_evidence(content, RE_CRYPTO_THEFT)}\n"
f"Network: {_extract_evidence(content, RE_NETWORK)}",
)
)
# Archive staging with credential content + network
if has_archive and has_network:
findings.append(
Finding(
CRITICAL,
package,
filename,
"Creates archive with sensitive data AND makes network calls",
f"Archive: {_extract_evidence(content, RE_ARCHIVE_STAGING)}\n"
f"Network: {_extract_evidence(content, RE_NETWORK)}",
)
)
# Persistence + network (dropper that persists)
if has_persistence and has_network:
findings.append(
Finding(
CRITICAL,
package,
filename,
"Installs persistence AND makes network calls (backdoor pattern)",
f"Persist: {_extract_evidence(content, RE_PERSISTENCE)}\n"
f"Network: {_extract_evidence(content, RE_NETWORK)}",
)
)
# Container/k8s abuse + network
if has_container and has_network:
findings.append(
Finding(
CRITICAL,
package,
filename,
"Container/orchestration abuse AND makes network calls",
f"Container: {_extract_evidence(content, RE_CONTAINER_ABUSE)}\n"
f"Network: {_extract_evidence(content, RE_NETWORK)}",
)
)
# HIGH: single strong signals or weaker combinations
# Obfuscated payload: base64 + exec/eval + large blob
if has_base64 and has_exec_eval and has_blob:
# Digest every blob too: a payload may sit on a separate line from the
# decode call, and a second encoded blob may be appended later, so
# binding only the base64/exec lines or the first blob would miss it.
_, blob_digest = _blob_digest(content)
findings.append(
Finding(
HIGH,
package,
filename,
"base64 decode + exec/eval + large encoded blob",
f"Base64: {_extract_evidence(content, RE_BASE64)}\n"
f"Exec: {_extract_evidence(content, RE_EXEC_EVAL)}\n"
f"Blob: sha256:{blob_digest}",
)
)
# Advanced obfuscation + exec/eval
if has_obfuscation and has_exec_eval:
findings.append(
Finding(
HIGH,
package,
filename,
"Advanced obfuscation (marshal/compile/zlib) + exec/eval",
f"Obfusc: {_extract_evidence(content, RE_OBFUSCATION)}\n"
f"Exec: {_extract_evidence(content, RE_EXEC_EVAL)}",
)
)
# Embedded crypto key + network (hardcoded key for encrypted exfil)
if has_keys and has_network:
findings.append(
Finding(
HIGH,
package,
filename,
"Embedded cryptographic key + network calls (encrypted exfil pattern)",
f"Key: {_embedded_key_evidence(content)}\n"
f"Network: {_extract_evidence(content, RE_NETWORK)}",
)
)
# Anti-analysis + any other suspicious pattern
if has_anti and (has_network or has_subprocess or has_exec_eval):
# Bind the suspicious side too so a changed payload reopens.
evidence = [f"Anti: {_extract_evidence(content, RE_ANTI_ANALYSIS)}"]
if has_network:
evidence.append(f"Network: {_extract_evidence(content, RE_NETWORK)}")
if has_subprocess:
evidence.append(f"Subprocess: {_extract_evidence(content, RE_SUBPROCESS)}")
if has_exec_eval:
evidence.append(f"Exec: {_extract_evidence(content, RE_EXEC_EVAL)}")
findings.append(
Finding(
HIGH,
package,
filename,
"Anti-analysis/sandbox evasion + suspicious behavior",
"\n".join(evidence),
)
)
# DNS exfiltration with dynamic hostnames
if has_dns_exfil and (has_base64 or has_network or has_creds):
# Bind the co-occurring side so a changed exfil channel reopens.
evidence = [f"DNS: {_extract_evidence(content, RE_DNS_EXFIL)}"]
if has_base64:
evidence.append(f"Base64: {_extract_evidence(content, RE_BASE64)}")
if has_network:
evidence.append(f"Network: {_extract_evidence(content, RE_NETWORK)}")
if has_creds:
evidence.append(f"Creds: {_extract_evidence(content, RE_CRED_ACCESS)}")
findings.append(
Finding(
HIGH,
package,