-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathexploit-check.sh
More file actions
1484 lines (1308 loc) · 54.1 KB
/
exploit-check.sh
File metadata and controls
1484 lines (1308 loc) · 54.1 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 bash
set -o errexit
set -o pipefail
set -o nounset
CSV_FILE="epss_scores-current.csv"
EPSS_URL="https://epss.cyentia.com/epss_scores-current.csv.gz"
EPSS_FILE="epss_scores-current.csv.gz"
KEV_URL="https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json"
KEV_FILE="known_exploited_vulnerabilities.json"
# ExploitDB CSV (index maintained in the ExploitDB repo)
EXPLOITDB_URL="https://gitlab.com/exploit-database/exploitdb/-/raw/main/files_exploits.csv"
EXPLOITDB_FILE="exploitdb_exploits.csv"
FULL_OUTPUT=0
PACKAGE_INFO=0
# ANSI colors
BOLD_PURPLE="\033[1;35m"
RESET="\033[0m"
# Severity colors
DARK_GREEN="\033[0;32m"
BOLD_DARK_GREEN="\033[1;32m"
YELLOW="\033[0;93m"
BOLD_YELLOW="\033[1;93m"
BOLD_ORANGE="\033[1;38;5;208m"
BOLD_RED="\033[1;31m"
# Extra colors
PINK="\033[1;35m"
BLUE="\033[1;34m"
# Helper: safe curl
curl_get() {
local url="$1"
local out="$2"
if ! curl -sSL --fail -o "$out" "$url"; then
return 1
fi
}
update_epss() {
echo -e "${BLUE}[*] Checking for updated EPSS data...${RESET}"
if [ ! -f "$EPSS_FILE" ]; then
echo "[+] No local EPSS file found. ❌ Downloading..."
curl_get "$EPSS_URL" "$EPSS_FILE" || {
echo "[!] Failed to download EPSS data"
return 1
}
else
echo -e "${BLUE}[*] File exists. Checking freshness...${RESET}"
# -z option uses timestamp to download only if remote is newer
if ! curl -sSL --fail -z "$EPSS_FILE" -o "$EPSS_FILE" "$EPSS_URL"; then
echo "[!] Failed to update EPSS data"
return 1
fi
fi
echo -e "${BLUE}[*] Extracting CSV...${RESET}"
if ! gunzip -c "$EPSS_FILE" > "$CSV_FILE"; then
echo "[!] Extraction failed. Redownloading..."
rm -f "$EPSS_FILE"
curl_get "$EPSS_URL" "$EPSS_FILE" || {
echo "[!] Failed to download EPSS data"
return 1
}
gunzip -c "$EPSS_FILE" > "$CSV_FILE"
fi
}
update_kev() {
echo -e "${BLUE}[*] Updating KEV feed...${RESET}"
curl_get "$KEV_URL" "$KEV_FILE" || {
echo "[!] Failed to download KEV feed"
return 1
}
}
update_opa() {
echo -e "${BLUE}[*] Updating OPA Gatakeeper...${RESET}"
kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/release-3.13/deploy/gatekeeper.yaml || {
echo "[!] Failed to install or Update OPA Gatakeeper"
return 1
}
}
# Helper: check for kubectl
require_kubectl() {
if ! command -v kubectl >/dev/null 2>&1; then
echo "[!] kubectl is not installed or not in PATH. Please install kubectl and try again."
exit 2
fi
}
# Enforce Gatekeeper ConstraintTemplate + Constraint (apply)
opa_enforce() {
require_kubectl
echo -e "${BLUE}[*] Applying Gatekeeper ConstraintTemplate...${RESET}"
kubectl apply -f "https://raw.githubusercontent.com/ndouglas-cloudsmith/docker-testing/refs/heads/main/constrainttemplate.yaml" || {
echo "[!] Failed to apply constrainttemplate.yaml"
return 1
}
echo -e "${BLUE}[*] Applying Gatekeeper Constraint...${RESET}"
kubectl apply -f "https://raw.githubusercontent.com/ndouglas-cloudsmith/docker-testing/refs/heads/main/constraint.yaml" || {
echo "[!] Failed to apply constraint.yaml"
return 1
}
echo -e "${BLUE}[+] OPA enforcement resources applied.${RESET}"
return 0
}
# Disable (delete) Gatekeeper ConstraintTemplate + Constraint
opa_disable() {
require_kubectl
echo -e "${BLUE}[*] Deleting Gatekeeper Constraint...${RESET}"
kubectl delete -f "https://raw.githubusercontent.com/ndouglas-cloudsmith/docker-testing/refs/heads/main/constraint.yaml" --ignore-not-found || {
echo "[!] Failed to delete constraint.yaml (or returned non-zero)"
# continue to attempt template removal
}
echo -e "${BLUE}[*] Deleting Gatekeeper ConstraintTemplate...${RESET}"
kubectl delete -f "https://raw.githubusercontent.com/ndouglas-cloudsmith/docker-testing/refs/heads/main/constrainttemplate.yaml" --ignore-not-found || {
echo "[!] Failed to delete constrainttemplate.yaml (or returned non-zero)"
return 1
}
echo -e "${BLUE}[+] OPA enforcement resources removed (or were not present).${RESET}"
return 0
}
update_exploitdb() {
echo -e "${BLUE}[*] Downloading ExploitDB index (this is fairly large-ish)...${RESET}"
if ! curl_get "$EXPLOITDB_URL" "$EXPLOITDB_FILE"; then
echo "[!] Failed to download ExploitDB index"
return 1
fi
}
# Normalize, validate and return a comma-separated uppercase severity list.
# Usage: normalize_and_validate "low,High"
normalize_and_validate() {
local input="$1"
# drop spaces, uppercase
input=$(echo "$input" | tr -d ' ' | tr '[:lower:]' '[:upper:]')
# Allowed tokens
local allowed="LOW MEDIUM HIGH CRITICAL"
IFS=',' read -ra toks <<< "$input"
local out=""
for t in "${toks[@]}"; do
if [ -z "$t" ]; then
continue
fi
if ! echo "$allowed" | grep -w -q "$t"; then
echo "[!] Invalid severity: $t. Allowed values: LOW,MEDIUM,HIGH,CRITICAL"
exit 1
fi
# avoid duplicates keeping order
if ! echo "$out" | grep -w -q "$t"; then
if [ -z "$out" ]; then
out="$t"
else
out="${out},$t"
fi
fi
done
if [ -z "$out" ]; then
echo "[!] No valid severities provided"
exit 1
fi
echo "$out"
}
# Helper: check for grype
require_grype() {
if ! command -v grype >/dev/null 2>&1; then
echo "[!] grype is not installed or not in PATH. Please install grype (https://github.com/anchore/grype) and try again."
exit 2
fi
}
# Input: comma-separated uppercase severities (e.g. "HIGH,CRITICAL")
# Output: single severity string suitable for grype's --fail-on: CRITICAL|HIGH|MEDIUM|LOW
pick_grype_fail_on() {
local sev_list="$1"
# ensure uppercase, remove spaces
sev_list=$(echo "$sev_list" | tr -d ' ' | tr '[:lower:]' '[:upper:]')
# priority: CRITICAL > HIGH > MEDIUM > LOW
if echo "$sev_list" | grep -q "CRITICAL"; then
echo "CRITICAL"
elif echo "$sev_list" | grep -q "HIGH"; then
echo "HIGH"
elif echo "$sev_list" | grep -q "MEDIUM"; then
echo "MEDIUM"
else
echo "LOW"
fi
}
scan_image_grype() {
local image_ref="$1"
local severity_list="${2:-HIGH,CRITICAL}"
# Normalize & validate severity using your existing function
severity_list=$(normalize_and_validate "$severity_list") || exit 1
# determine grype --fail-on severity (single token)
local grype_fail_on
grype_fail_on=$(pick_grype_fail_on "$severity_list")
echo -e "${BLUE}[*] Scanning image with grype:${RESET} $image_ref (fail-on=$grype_fail_on)"
require_grype
grype "$image_ref" --fail-on "$grype_fail_on" --scope squashed
}
scan_image_trivy() {
local image_ref="$1"
local severity_list="${2:-HIGH,CRITICAL}" # default same as your kubernetes default
# Normalize & validate severity via existing function
severity_list=$(normalize_and_validate "$severity_list") || exit 1
echo -e "${BLUE}[*] Scanning image with trivy:${RESET} $image_ref (severity=$severity_list)"
trivy image --scanners vuln --severity "$severity_list" "$image_ref"
}
scan_namespace_polaris() {
local namespace="$1"
echo -e "${BLUE}[*] Running Polaris audit in namespace:${RESET} $namespace"
if ! command -v polaris >/dev/null 2>&1; then
echo "[!] polaris CLI not found. Please install Polaris: https://www.fairwinds.com/polaris"
exit 1
fi
polaris audit --namespace="$namespace" --format=pretty
}
# Helper: check for trivy
require_trivy() {
if ! command -v trivy >/dev/null 2>&1; then
echo "[!] trivy is not installed or not in PATH. Please install trivy (https://github.com/aquasecurity/trivy) and try again."
exit 2
fi
}
# OSV: Fallback check against the OSSF malicious packages repo on GitHub.
# This can find records for malicious packages that have been removed
# and may no longer be returned by the OSV API's /query endpoint.
check_malicious_history_github() {
local ecosystem="$1"
local pkg_name="$2"
if ! command -v jq >/dev/null 2>&1; then
echo "[!] jq is required for the fallback check. Please install jq."
return 1
fi
local lower_eco
lower_eco=$(echo "$ecosystem" | tr '[:upper:]' '[:lower:]')
echo
echo -e "${BLUE}[*] Performing fallback check for historical malicious package records...${RESET}"
local github_url="https://api.github.com/repos/ossf/malicious-packages/contents/osv/malicious/${lower_eco}/${pkg_name}"
local resp_file
resp_file=$(mktemp)
local http_code
# Ensure curl doesn't fail the script if it returns non-zero
http_code=$(curl -sS -o "$resp_file" -w "%{http_code}" "$github_url" || true)
if [ "$http_code" = "200" ]; then
local gh_resp
gh_resp=$(<"$resp_file")
rm "$resp_file" # Clean up early
if echo "$gh_resp" | jq -e '. | type == "array" and length > 0' >/dev/null 2>&1; then
local mal_filename
mal_filename=$(echo "$gh_resp" | jq -r '.[0].name // empty')
if [[ "$mal_filename" == *.json ]]; then
local mal_id
mal_id="${mal_filename%.json}"
echo -e "${BOLD_PURPLE}Found historical malicious package record:${RESET} ${BOLD_RED}$mal_id${RESET}"
echo "[+] Querying details from OSV..."
query_mal "$mal_id"
return 0 # Success: record found and displayed
else
echo -e "${BOLD_PURPLE}Fallback Check:${RESET} Found a directory, but no valid malicious package JSON file."
fi
else
echo -e "${BOLD_PURPLE}Fallback Check:${RESET} Directory found on GitHub, but it's empty or response is not an array."
fi
elif [ "$http_code" = "404" ]; then
echo -e "${BOLD_PURPLE}Fallback Check:${RESET} No historical malicious package record found. ✅"
elif [ "$http_code" = "403" ]; then
echo -e "${BOLD_PURPLE}Fallback Check:${RESET} ${BOLD_YELLOW}GitHub API rate limit hit. Cannot perform fallback check. ❌${RESET}"
else
echo -e "${BOLD_PURPLE}Fallback Check:${RESET} ${BOLD_YELLOW}Failed to query GitHub API (HTTP status: ${http_code}). ❌${RESET}"
fi
# Ensure temp file is removed on all error paths
if [ -f "$resp_file" ]; then
rm "$resp_file"
fi
return 1 # Failure: no record found
}
# OSV: Query a malicious package ID (OSSF-MAL- or MAL-...)
query_mal() {
local MAL_ID="$1"
local resp
echo -e "${BLUE}[*] Querying OSV for Malicious Package ID:${RESET} $MAL_ID ..."
# Use curl_get logic directly here to ensure response is captured
if resp=$(curl -sS "https://api.osv.dev/v1/vulns/$MAL_ID" || true); then
if echo "$resp" | jq -e '.' >/dev/null 2>&1; then
if echo "$resp" | jq -e 'has("error")' >/dev/null 2>&1; then
echo -e "${BOLD_PURPLE}OSV/Malicious:${RESET} Not found or API error. ❌"
return 1
fi
# --- Robustly extract data ---
local summary
summary=$(echo "$resp" | jq -r '.summary // empty') || true
local details
details=$(echo "$resp" | jq -r '.details // empty' | sed 's/\n/ /g' | sed 's/ */ /g') || true
# 1. Try to extract from the top-level database_specific object (standard for new records)
local malware_type
malware_type=$(echo "$resp" | jq -r '.database_specific.malware_type // empty') || true
local confidence
confidence=$(echo "$resp" | jq -r '.database_specific.confidence // empty') || true
# 2. If not found at the top level, search for the deeply nested structure (common in older MAL- records)
if [ -z "$malware_type" ]; then
malware_type=$(echo "$resp" | jq -r '.database_specific["malicious-packages-origins"][]?.malicious_package_version_info?.malicious_package_type // empty' | head -n1)
fi
if [ -z "$confidence" ]; then
confidence=$(echo "$resp" | jq -r '.database_specific["malicious-packages-origins"][]?.malicious_package_version_info?.confidence // empty' | head -n1)
fi
# 3. If type is still missing, try to infer it from the details text
if [ -z "$malware_type" ] || [ "$malware_type" = "null" ]; then
local details_text
# Lowercase for easier matching
details_text=$(echo "$resp" | jq -r '.details // empty' | tr '[:upper:]' '[:lower:]')
if [[ "$details_text" == *"communicates with a domain"* || "$details_text" == *"network traffic"* || "$details_text" == *"exfiltrates data"* ]]; then
malware_type="NETWORK_ACTIVITY"
elif [[ "$details_text" == *"typosquat"* ]]; then
malware_type="TYPOSQUATTING"
elif [[ "$details_text" == *"dependency confusion"* ]]; then
malware_type="DEPENDENCY_CONFUSION"
elif [[ "$details_text" == *"downloads and executes"* || "$details_text" == *"remote code execution"* ]]; then
malware_type="EXECUTES_CODE"
else
# If no specific pattern matches, set a default
malware_type="UNDEFINED"
fi
fi
# Sanitize and set fallback for display
malware_type=$(echo "$malware_type" | tr '[:lower:]' '[:upper:]')
malware_type=${malware_type:-N/A}
local type_color="$RESET"
case "$malware_type" in
TYPOSQUATTING|DEPENDENCY_CONFUSION|BACKDOOR|INSTALLER_MALWARE|NETWORK_ACTIVITY) type_color="$BOLD_RED" ;;
*) type_color="$YELLOW" ;;
esac
echo -e "${BOLD_PURPLE}MALICIOUS PACKAGE ID:${RESET} $MAL_ID"
echo -e "${BOLD_PURPLE}Type:${RESET} ${type_color}$malware_type${RESET}"
if [ -n "$summary" ]; then
echo -e "${BOLD_PURPLE}Summary:${RESET} $summary"
fi
if [ -n "$details" ]; then
echo -e "${BOLD_PURPLE}Details:${RESET} $details"
fi
# Affected packages
echo
echo -e "${PINK}Affected packages:${RESET}"
# Capture the package name and ecosystem for the first affected package to check NPM/PyPI info
local ECOSYSTEM
ECOSYSTEM=$(echo "$resp" | jq -r '.affected[0].package.ecosystem // empty')
local PKG_NAME
PKG_NAME=$(echo "$resp" | jq -r '.affected[0].package.name // empty')
echo "$resp" | jq -r '
.affected[]? |
" - Ecosystem: \(.package.ecosystem // "N/A")",
" Package: \(.package.name // "N/A")",
""
' || true
if [ "$(echo "$ECOSYSTEM" | tr '[:upper:]' '[:lower:]')" = "npm" ]; then
npm_print_info "$PKG_NAME" || true
elif [ "$(echo "$ECOSYSTEM" | tr '[:upper:]' '[:lower:]')" = "pypi" ]; then
pypi_print_info "$PKG_NAME" || true
fi
# References
if echo "$resp" | jq -e '.references | length > 0' >/dev/null 2>&1; then
echo -e "${PINK}References:${RESET}"
echo "$resp" | jq -r '.references[] | " - \(.type // "N/A"): \(.url // "N/A")"' || true
fi
return 0
fi
fi
echo -e "${BOLD_PURPLE}OSV/Malicious:${RESET} Query failed or no JSON. ❌"
return 1
}
# OSV: no download — use the API live when querying
query_osv() {
local CVE_OR_ID="$1"
local resp
if resp=$(curl -sS "https://api.osv.dev/v1/vulns/$CVE_OR_ID" || true); then
if echo "$resp" | jq -e '.' >/dev/null 2>&1; then
if echo "$resp" | jq -e 'has("error")' >/dev/null 2>&1; then
return 1
fi
echo -e "${BOLD_PURPLE}OSV:${RESET} Found — package ecosystem details (if any):"
echo "$resp" | jq -r '
.affected[]? |
" - Ecosystem: \(.package.ecosystem // "N/A")",
" Package: \(.package.name // "N/A")",
" Ranges: \((.ranges // []) | tostring)",
" Fixed: \((.versions // []) | tostring)",
""
'
local summary
summary=$(echo "$resp" | jq -r '.summary // empty') || true
if [ -n "$summary" ]; then
echo -e " Summary: $summary"
fi
return 0
fi
fi
return 1
}
# Print PyPI package metadata nicely
pypi_print_info() {
local pkg="$1"
# require jq
if ! command -v jq >/dev/null 2>&1; then
echo "[!] jq is required to display PyPI package info. Install jq and retry."
return 1
fi
local resp
resp=$(curl -sS "https://pypi.org/pypi/${pkg}/json" || true)
if [ -z "$resp" ]; then
echo "[!] Failed to fetch PyPI metadata for: $pkg (network error)"
return 1
fi
if echo "$resp" | jq -e '.message == "Not Found"' >/dev/null 2>&1; then
echo
echo -e "${BOLD_PURPLE}PyPI Package Info:${RESET}"
echo -e "${BOLD_RED}Package does not exist${RESET}"
echo
return 0
fi
if ! echo "$resp" | jq -e '.' >/dev/null 2>&1; then
echo "[!] PyPI response for ${pkg} was not valid JSON."
return 1
fi
local name author home
name=$(echo "$resp" | jq -r '.info.name // empty' | sed -e 's/^/ /')
author=$(echo "$resp" | jq -r '.info.author // empty' | sed -e 's/^/ /')
home=$(echo "$resp" | jq -r '.info.home_page // empty' | sed -e 's/^/ /')
echo
echo -e "${BOLD_PURPLE}PyPI Package Info:${RESET}"
echo -e "${BOLD_PURPLE}Package Name: ${RESET}${name:-N/A}"
echo -e "${BOLD_PURPLE}Package Author: ${RESET}${author:-N/A}"
echo -e "${BOLD_PURPLE}Package Homepage: ${RESET}${home:-N/A}"
echo
echo -e "${BOLD_PURPLE}Supporting Links: ${RESET}"
if echo "$resp" | jq -e '.info.project_urls != null and (.info.project_urls | length > 0)' >/dev/null 2>&1; then
echo "$resp" | jq -r '.info.project_urls | to_entries | sort_by(.key)[] | " \(.key): \(.value)"' || true
else
local homepage_url package_url project_url
homepage_url=$(echo "$resp" | jq -r '.info.home_page // empty')
package_url=$(echo "$resp" | jq -r '.info.package_url // empty')
project_url=$(echo "$resp" | jq -r '.info.project_url // empty')
[ -n "$homepage_url" ] && echo " Home: $homepage_url"
[ -n "$project_url" ] && echo " Project: $project_url"
[ -n "$package_url" ] && echo " PyPI: $package_url"
if [ -z "$homepage_url" ] && [ -z "$project_url" ] && [ -z "$package_url" ]; then
echo "$resp" | jq -r '..|strings' | grep -E '\.com|\.io|\.org' | sed 's/[[:space:]]*$//' | sort -u | sed 's/^/ /' | head -n 20
fi
fi
echo
local signed
signed=$(echo "$resp" | jq '[.releases[][]?.filename | select(endswith(".asc"))] | length')
if [ "$signed" -gt 0 ]; then
echo -e "signed: ${BOLD_DARK_GREEN}true${RESET}"
else
echo -e "signed: ${BOLD_RED}false${RESET}"
fi
echo
return 0
}
# Print NPM package metadata nicely
npm_print_info() {
local pkg="$1"
if ! command -v jq >/dev/null 2>&1; then
echo "[!] jq is required to display NPM package info. Install jq and retry."
return 1
fi
local resp
resp=$(curl -sS "https://registry.npmjs.org/${pkg}" || true)
if [ -z "$resp" ]; then
echo "[!] Failed to fetch NPM metadata for: $pkg (network error)"
return 1
fi
if echo "$resp" | jq -e '.error == "Not found"' >/dev/null 2>&1; then
echo
echo -e "${BOLD_PURPLE}NPM Package Info:${RESET}"
echo -e "${BOLD_RED}Package does not exist${RESET}"
echo
return 0
fi
if ! echo "$resp" | jq -e '.' >/dev/null 2>&1; then
echo "[!] NPM response for ${pkg} was not valid JSON."
return 1
fi
local latest_version
latest_version=$(echo "$resp" | jq -r '."dist-tags".latest // empty')
local latest_info
if [ -n "$latest_version" ]; then
latest_info=$(echo "$resp" | jq -c --arg v "$latest_version" '.versions[$v] // {}')
else
latest_info="{}"
fi
local name description author_name homepage license
name=$(echo "$resp" | jq -r '.name // empty' | sed -e 's/^/ /')
description=$(echo "$latest_info" | jq -r '.description // empty' | sed -e 's/^/ /')
author_name=$(echo "$latest_info" | jq -r '(.author.name // .author // empty)' | sed -e 's/^/ /')
homepage=$(echo "$latest_info" | jq -r '.homepage // empty' | sed -e 's/^/ /')
license=$(echo "$latest_info" | jq -r '.license // empty' | sed -e 's/^/ /')
echo
echo -e "${BOLD_PURPLE}NPM Package Info:${RESET}"
echo -e "${BOLD_PURPLE}Package Name: ${RESET}${name:-N/A}"
echo -e "${BOLD_PURPLE}Latest Version: ${RESET}${latest_version:-N/A}"
echo -e "${BOLD_PURPLE}Author/Publisher: ${RESET}${author_name:-N/A}"
echo -e "${BOLD_PURPLE}License: ${RESET}${license:-N/A}"
echo -e "${BOLD_PURPLE}Homepage: ${RESET}${homepage:-N/A}"
echo -e "${BOLD_PURPLE}Description: ${RESET}${description:-N/A}"
echo
return 0
}
# Print Maven Central package metadata
maven_print_info() {
local pkg="$1"
if ! command -v jq >/dev/null 2>&1; then
echo "[!] jq is required. Please install jq."
return 1
fi
local url="https://search.maven.org/solrsearch/select?q=a%3A%22${pkg}%22&rows=1&wt=json"
local resp
resp=$(curl -sS "$url" || true)
if [ -z "$resp" ]; then
echo "[!] Failed to fetch Maven Central metadata for: $pkg (network error)"
return 1
fi
local num_found
num_found=$(echo "$resp" | jq -r '.response.numFound // 0')
echo
echo -e "${BOLD_PURPLE}Maven Central Package Info:${RESET}"
if [ "$num_found" -eq 0 ]; then
echo -e "${BOLD_RED}Package does not exist (by artifact ID '${pkg}')${RESET}"
else
echo "$resp" | jq -r '
.response.docs[0] as $doc |
" Package ID: \($doc.id)\n" +
" Latest Version: \($doc.latestVersion)\n" +
" Repository ID: \($doc.repositoryId)"
'
fi
echo
return 0
}
# Print RubyGems package metadata
rubygems_print_info() {
local pkg="$1"
if ! command -v jq >/dev/null 2>&1; then
echo "[!] jq is required. Please install jq."
return 1
fi
local url="https://rubygems.org/api/v1/gems/${pkg}.json"
local resp
resp=$(curl -sS "$url" || true)
echo
echo -e "${BOLD_PURPLE}RubyGems Package Info:${RESET}"
if ! echo "$resp" | jq -e '.' >/dev/null 2>&1; then
echo -e "${BOLD_RED}Package does not exist${RESET}"
else
echo "$resp" | jq -r '
" Name: \(.name // "N/A")\n" +
" Latest Version: \(.version // "N/A")\n" +
" Info: \(.info // "N/A")\n" +
" Authors: \(.authors // "N/A")\n" +
" Homepage: \(.homepage_uri // "N/A")"
'
fi
echo
return 0
}
# Print Pub (Dart) package metadata
pub_print_info() {
local pkg="$1"
if ! command -v jq >/dev/null 2>&1; then
echo "[!] jq is required. Please install jq."
return 1
fi
local url="https://pub.dev/api/packages/${pkg}"
local resp
resp=$(curl -sS "$url" || true)
echo
echo -e "${BOLD_PURPLE}Pub (Dart) Package Info:${RESET}"
if echo "$resp" | jq -e '.error' >/dev/null 2>&1; then
echo -e "${BOLD_RED}Package does not exist${RESET}"
else
echo "$resp" | jq -r '
" Name: \(.name // "N/A")\n" +
" Latest Version: \(.latest.version // "N/A")\n" +
" Description: \(.latest.pubspec.description // "N/A")\n" +
" Homepage: \(.latest.pubspec.homepage // "N/A")"
'
fi
echo
return 0
}
# Print Debian package metadata
debian_print_info() {
local pkg="$1"
local http_code
local url="https://sources.debian.org/api/src/${pkg}/"
http_code=$(curl -sS -o /dev/null -w "%{http_code}" "$url" || true)
echo
echo -e "${BOLD_PURPLE}Debian Package Info:${RESET}"
if [ "$http_code" = "404" ]; then
echo -e "${BOLD_RED}Package does not exist in Debian sources${RESET}"
echo
return 0
elif [ "$http_code" != "200" ]; then
echo "[!] Failed to query Debian API for ${pkg} (HTTP status: ${http_code})"
return 1
fi
local resp
resp=$(curl -sS "$url" || true)
echo " Package: $(echo "$resp" | jq -r '.package // "N/A"')"
echo " Latest Version: $(echo "$resp" | jq -r '.versions[0].version // "N/A"')"
echo
return 0
}
# Check ConanCenter for package existence
conancenter_print_info() {
local pkg="$1"
local http_code
local url="https://conan.io/center/recipes/${pkg}"
http_code=$(curl -sS -o /dev/null -w "%{http_code}" "$url" || true)
echo
echo -e "${BOLD_PURPLE}Conan Center Package Info:${RESET}"
if [ "$http_code" = "404" ]; then
echo -e "${BOLD_RED}Package does not exist${RESET}"
elif [[ "$http_code" =~ ^[23] ]]; then # 2xx or 3xx status
echo " Package: ${pkg}"
echo " Status: Found (HTTP ${http_code})"
echo " URL: ${url}"
else
echo -e "${BOLD_RED}Failed to query Conan Center (HTTP ${http_code})${RESET}"
fi
echo
return 0
}
# Print Hex package metadata
hex_print_info() {
local pkg="$1"
if ! command -v jq >/dev/null 2>&1; then
echo "[!] jq is required. Please install jq."
return 1
fi
local url="https://hex.pm/api/packages/${pkg}"
local http_code
local resp_file
resp_file=$(mktemp)
http_code=$(curl -sS -o "$resp_file" -w "%{http_code}" "$url" || true)
echo
echo -e "${BOLD_PURPLE}Hex Package Info:${RESET}"
if [ "$http_code" = "404" ]; then
echo -e "${BOLD_RED}Package does not exist${RESET}"
elif [ "$http_code" = "200" ]; then
jq -r '
" Name: \(.name // "N/A")\n" +
" Latest Version: \(.releases[0].version // "N/A")\n" +
" Description: \(.meta.description // "N/A")\n" +
" Homepage: \((.meta.links | .Homepage) // "N/A")"
' "$resp_file"
else
echo -e "${BOLD_RED}Failed to query Hex API (HTTP ${http_code})${RESET}"
fi
rm "$resp_file"
echo
return 0
}
# Print Alpine Linux package metadata
alpine_print_info() {
local pkg="$1"
local eco_spec="$2"
local branch
if [[ "$eco_spec" == *":"* ]]; then
branch="${eco_spec#*:}"
else
branch="edge"
fi
if ! command -v jq >/dev/null 2>&1; then
echo "[!] jq is required. Please install jq."
return 1
fi
local url="https://pkgs.alpinelinux.org/packages?name=${pkg}&branch=${branch}&_api=json"
local resp
resp=$(curl -sS "$url" || true)
local result_count
result_count=$(echo "$resp" | jq 'length')
echo
echo -e "${BOLD_PURPLE}Alpine Linux Package Info (Branch: ${branch}):${RESET}"
if [ "$result_count" -eq 0 ]; then
echo -e "${BOLD_RED}Package does not exist${RESET}"
else
echo "$resp" | jq -r '
.[0] as $pkg |
" Name: \($pkg.package)\n" +
" Version: \($pkg.version)\n" +
" Repo: \($pkg.repo)\n" +
" Architecture: \($pkg.arch)"
'
fi
echo
return 0
}
query_exploitdb() {
local CVE="$1"
if [ ! -f "$EXPLOITDB_FILE" ]; then
echo "[!] ExploitDB index missing. Run update first."
return 2
fi
local matches
matches=$(grep -i "$CVE" "$EXPLOITDB_FILE" || true)
if [ -n "$matches" ]; then
echo -e "${BOLD_PURPLE}ExploitDB:${RESET} Public exploit(s) / entries found:"
echo "$matches" | head -n 20 | awk -F',' '{
id=$1; desc=$2;
gsub(/^"|"$/, "", desc);
print " - ID:" id " | Link: https://www.exploit-db.com/exploits/" id " | Path: " desc
}'
if [ "$(echo "$matches" | wc -l)" -gt 20 ]; then
echo " ... (truncated)"
fi
return 0
else
echo -e "${BOLD_PURPLE}ExploitDB:${RESET} No public exploit entries found ❌"
return 1
fi
}
query_package() {
local eco_spec="$1"
local pkg_name="$2"
local follow_cves="${3:-0}"
if [ -z "$eco_spec" ] || [ -z "$pkg_name" ]; then
echo "[!] query_package requires an ecosystem/source (or source:version) and a package name"
return 2
fi
local ecosystem_token
if [[ "$eco_spec" == *":"* ]]; then
ecosystem_token="${eco_spec%%:*}"
else
ecosystem_token="$eco_spec"
fi
echo -e "${BLUE}[*]Querying OSV for package:${RESET} ecosystem/source=$eco_spec package=$pkg_name ..."
local payload
payload=$(cat <<EOF
{
"package": {
"ecosystem": "$(echo "$ecosystem_token" | tr '[:upper:]' '[:lower:]')",
"name": "$pkg_name"
}
}
EOF
)
local resp
resp=$(curl -sS -X POST -H "Content-Type: application/json" \
-d "$payload" "https://api.osv.dev/v1/query" || true)
if [ -z "$resp" ] || ! echo "$resp" | jq -e '.' >/dev/null 2>&1; then
echo "[!] OSV query failed or returned invalid JSON."
# Attempt fallback even if the primary query fails, as it might be a non-existent malicious pkg
if check_malicious_history_github "$ecosystem_token" "$pkg_name"; then
return 0 # Found and displayed by fallback
fi
return 1
fi
local vuln_count
vuln_count=$(echo "$resp" | jq -r '.vulns | length // 0')
if [ "$vuln_count" -eq 0 ]; then
echo -e "${BOLD_PURPLE}OSV:${RESET} No active vulnerabilities found for $eco_spec/$pkg_name"
# If no vulns found via API, try the fallback for historical malicious packages
if check_malicious_history_github "$ecosystem_token" "$pkg_name"; then
return 0 # Found and displayed by fallback, so we are done.
fi
# If fallback also finds nothing, continue to the normal "not found" output
else
echo -e "${BOLD_PURPLE}OSV:${RESET} Found $vuln_count vulnerability(ies) for $eco_spec/$pkg_name"
echo "$resp" | jq -r '.vulns[] | "- ID: " + (.id // "N/A") + " | Summary: " + ((.summary // "") | gsub("\n"; " ")) + " | Aliases: " + ((.aliases // []) | join(", "))' || true
fi
local ids
ids=$(echo "$resp" | jq -r '.vulns[]? | [(.id // "") ] + (.aliases // []) | .[]' | sort -u || true)
if [ -n "$ids" ]; then
echo
echo -e "${BOLD_PURPLE}Mapped IDs:${RESET}"
echo "$ids" | sed 's/^/ - /'
else
echo
echo -e "${BOLD_PURPLE}Mapped IDs:${RESET} None found in OSV aliases for these records."
fi
if [ -f "$EXPLOITDB_FILE" ]; then
echo
echo -e "${BOLD_PURPLE}ExploitDB:${RESET} ${BLUE}Searching local index for package name / ecosystem / common name...${RESET}"
local safe_pkg
safe_pkg=$(printf '%s' "$pkg_name" | sed 's/[]\\$*.^|[]/\\&/g')
grep -i -E "$safe_pkg" "$EXPLOITDB_FILE" | head -n 20 || true
else
echo "[!] ExploitDB index missing. Run update first to search ExploitDB locally."
fi
if [ "$follow_cves" -eq 1 ] && [ -n "$ids" ]; then
echo
echo -e "${BLUE}[*] Fetching detailed info for discovered CVEs (if any)...${RESET}"
local old_package_info old_full_output
old_package_info="$PACKAGE_INFO"
old_full_output="$FULL_OUTPUT"
PACKAGE_INFO=0
FULL_OUTPUT=0
while IFS= read -r id; do
if [[ "$id" =~ ^CVE- ]]; then
echo
echo "=========================================="
query_cve "$id" || true
else
echo -e "Note: ${PINK}Non-CVE identifier:${RESET} $id"
fi
done <<< "$ids"
PACKAGE_INFO="$old_package_info"
FULL_OUTPUT="$old_full_output"
fi
}
query_ghsa() {
local GHSA="$1"
echo -e "${BLUE}[*] Querying OSV for GHSA:${RESET} $GHSA ..."
local resp
resp=$(curl -sS "https://api.osv.dev/v1/vulns/$GHSA" || true)
if [ -z "$resp" ] || ! echo "$resp" | jq -e '.' >/dev/null 2>&1; then
echo "[!] OSV query failed or returned no JSON for $GHSA"
return 1
fi
if echo "$resp" | jq -e 'has("error")' >/dev/null 2>&1; then
echo -e "${BOLD_PURPLE}OSV:${RESET} Not found for $GHSA"
return 1
fi
echo -e "${BOLD_PURPLE}OSV:${RESET} Found advisory for $GHSA"
local summary
summary=$(echo "$resp" | jq -r '.summary // empty' || true)
if [ -n "$summary" ]; then
echo -e "${PINK}Summary:${RESET} $summary"
fi
echo
echo -e "${PINK}Affected packages:${RESET}"
echo "$resp" | jq -r '
.affected[]? |
" - Ecosystem: \(.package.ecosystem // "N/A")",
" Package: \(.package.name // "N/A")",
" Ranges: \((.ranges // []) | tostring)",
" Fixed: \((.versions // []) | tostring)",
""
' || true
local ids
ids=$(echo "$resp" | jq -r '.aliases[]? // empty' | sort -u || true)
if [ -n "$ids" ]; then
echo
echo -e "${PINK}Mapped identifiers:${RESET}"
echo "$ids" | sed 's/^/ - /'
local cve_alias
cve_alias=$(echo "$ids" | grep -E '^CVE-' | head -n1 || true)
if [ -n "$cve_alias" ]; then
echo
echo "[*] GHSA maps to CVE: $cve_alias — running standard CVE query (EPSS/KEV/NVD/ExploitDB)"
query_cve "$cve_alias"
return 0
else
echo -e "${BLUE}[*]${RESET} No CVE alias present for this GHSA. ❌"
return 0
fi
else
echo -e "${BLUE}[*]${RESET} No aliases present for this GHSA. ❌"
return 0
fi
}
# Helper to print a single table row with color for the severity column
print_row() {
local color="$1"
local severity="$2"
local cvss="$3"
local epss="$4"
local interp="$5"
local action="$6"
local ok="$7"
printf "%b%-10s%b │ %-9s │ %-9s │ %-50s │ %-35s │ %-50s\n" \
"$color" "$severity" "$RESET" "$cvss" "$epss" "$interp" "$action" "$ok"
}
print_table() {
echo