-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·1735 lines (1486 loc) · 75.3 KB
/
main.py
File metadata and controls
executable file
·1735 lines (1486 loc) · 75.3 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
"""
Bomtori - SBOM and SCA Analysis Tool
Performs both SBOM and SCA analysis with a GitHub URL input.
"""
import argparse
import sys
import subprocess
import shutil
import json
import os
import urllib.request
import urllib.error
import ssl
import re
from pathlib import Path
from datetime import datetime, timezone
from typing import Dict, List, Any, Optional, Tuple
# Add SBOM and SCA directories to path
sys.path.insert(0, str(Path(__file__).parent / "SBOM" / "src"))
sys.path.insert(0, str(Path(__file__).parent / "SBOM"))
from analyzer.baseAnalyzer import BaseAnalyzer, ProjectType
from analyzer.golangAnalyzer import GolangAnalyzer
from analyzer.npmAnalyzer import NpmAnalyzer
from sbom.golangCyclonedxGenerator import CycloneDXGenerator
from sbom.npmCycloneDXGenerator import NpmCycloneDXGenerator
from sbom.metadataGenerator import MetadataGenerator
def print_banner():
"""Print Bomtori banner"""
COLOR1 = '\033[38;2;108;93;83m'
COLOR2 = '\033[38;2;159;132;115m'
COLOR3 = '\033[38;2;199;177;153m'
COLOR4 = '\033[38;2;223;211;195m'
RESET = '\033[0m'
banner = f"""
{COLOR4}██████╗ ██████╗ ███╗ ███╗████████╗ ██████╗ ██████╗ ██╗{RESET}
{COLOR3}██╔══██╗██╔═══██╗████╗ ████║╚══██╔══╝██╔═══██╗██╔══██╗██║{RESET}
{COLOR2}██████╔╝██║ ██║██╔████╔██║ ██║ ██║ ██║██████╔╝██║{RESET}
{COLOR2}██╔══██╗██║ ██║██║╚██╔╝██║ ██║ ██║ ██║██╔══██╗██║{RESET}
{COLOR1}██████╔╝╚██████╔╝██║ ╚═╝ ██║ ██║ ╚██████╔╝██║ ██║██║{RESET}
{COLOR1}╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝{RESET}
"""
print(banner)
print(f"{COLOR2}SBOM & SCA Analysis Tool{RESET}")
print()
def clone_repository(git_url, target_dir):
"""Clone Git repository to target directory"""
try:
print(f"Cloning repository: {git_url}")
# Remove target directory if it exists
if Path(target_dir).exists():
shutil.rmtree(target_dir)
subprocess.run(
["git", "clone", git_url, str(target_dir)],
check=True,
capture_output=True
)
# Extract repository name from URL
repo_name = git_url.split('/')[-1].replace('.git', '')
print(f"Repository cloned successfully: {repo_name}")
return repo_name
except subprocess.CalledProcessError as e:
print(f"Failed to clone repository: {e}")
return None
def run_sbom_analysis(source_dir, output_dir, project_type, git_url=None, repo_name=None):
"""Run SBOM analysis based on project type"""
print("\n" + "=" * 60)
print("Starting SBOM Analysis")
print("=" * 60)
if project_type == ProjectType.GOLANG:
return analyze_go_sbom(source_dir, output_dir, git_url)
elif project_type == ProjectType.NPM:
return analyze_npm_sbom(source_dir, output_dir, git_url, repo_name)
else:
print(f"Unsupported project type: {project_type.value}")
return None
def analyze_go_sbom(source_dir, output_dir, git_url=None):
"""Analyze Go project and generate SBOM"""
print(f"Analyzing Go project SBOM: {source_dir}")
try:
# Initialize Go analyzer
analyzer = GolangAnalyzer()
# Analyze the project
analysis_result = analyzer.analyze(str(source_dir), git_url)
print(f"Analysis completed: {len(analysis_result['packages'])} packages found")
# Generate CycloneDX SBOM
print("Generating CycloneDX SBOM...")
sbom_generator = CycloneDXGenerator()
author_info = {"name": "Bomtori"}
sbom = sbom_generator.generate_sbom(
analysis_result, str(source_dir), author_info, git_url, "golang"
)
# Generate metadata JSON
print("Generating metadata...")
metadata_generator = MetadataGenerator()
metadata = metadata_generator.generate_metadata(analysis_result, str(source_dir))
# Save files
repo_name = Path(source_dir).name
safe_repo_name = repo_name.replace('@', '_').replace('/', '_')
sbom_file = output_dir / f"{safe_repo_name}-sbom.cdx.json"
metadata_file = output_dir / f"{safe_repo_name}-metadata.json"
# Save SBOM
with open(sbom_file, 'w', encoding='utf-8') as f:
json.dump(sbom, f, indent=2, ensure_ascii=False)
# Save metadata
metadata_generator.save_metadata(metadata, str(metadata_file))
print(f"SBOM generated: {sbom_file.name}")
print(f"Metadata generated: {metadata_file.name}")
print(f" - Total components: {metadata['summary']['total_components']}")
print(f" - Direct dependencies: {metadata['summary']['direct_dependencies_count']}")
print(f" - Indirect dependencies: {metadata['summary']['indirect_dependencies_count']}")
return {
'sbom_file': sbom_file,
'metadata_file': metadata_file,
'analysis_result': analysis_result
}
except Exception as e:
print(f"SBOM analysis failed: {e}")
import traceback
traceback.print_exc()
return None
def analyze_npm_sbom(source_dir, output_dir, git_url=None, repo_name=None):
"""Analyze NPM project and generate SBOM"""
print(f"Analyzing NPM project SBOM: {source_dir}")
try:
# Initialize NPM analyzer
analyzer = NpmAnalyzer(str(source_dir))
# Analyze the project
analysis_result = analyzer.analyze()
print(f"Analysis completed: {len(analysis_result['packages'])} packages found")
# Generate CycloneDX SBOM
print("Generating CycloneDX SBOM...")
sbom_generator = NpmCycloneDXGenerator()
# Use provided repo_name if available, otherwise extract from source_dir
if not repo_name:
repo_name = Path(source_dir).name
success = sbom_generator.generate_sbom(
analysis_result=analysis_result,
output_dir=output_dir,
git_url=git_url,
repo_name=repo_name
)
if not success:
print("Failed to generate SBOM")
return None
# Generate metadata JSON
print("Generating metadata...")
metadata_generator = MetadataGenerator()
metadata = metadata_generator.generate_metadata(analysis_result, str(source_dir))
# Save metadata - use repo_name directly
metadata_file = output_dir / f"{repo_name}-metadata.json"
metadata_generator.save_metadata(metadata, str(metadata_file))
print(f"Metadata generated: {metadata_file.name}")
print(f" - Total components: {metadata['summary']['total_components']}")
print(f" - Direct dependencies: {metadata['summary']['direct_dependencies_count']}")
print(f" - Indirect dependencies: {metadata['summary']['indirect_dependencies_count']}")
return {
'metadata_file': metadata_file,
'analysis_result': analysis_result
}
except Exception as e:
print(f"SBOM analysis failed: {e}")
import traceback
traceback.print_exc()
return None
def run_sca_analysis(source_dir, output_dir, project_type, repo_name=None):
"""Run SCA analysis based on project type"""
print("\n" + "=" * 60)
print("Starting SCA Analysis")
print("=" * 60)
print("SCA includes: Call Graph Analysis")
if project_type == ProjectType.GOLANG:
print("\n[1/2] Call Graph Analysis")
callgraph_result = analyze_go_callgraph(source_dir, output_dir, repo_name)
return callgraph_result
elif project_type == ProjectType.NPM:
print("\n[1/2] Call Graph Analysis")
callgraph_result = analyze_npm_callgraph(source_dir, output_dir, repo_name)
return callgraph_result
else:
print(f"Unsupported project type: {project_type.value}")
return None
def analyze_go_callgraph(source_dir, output_dir, repo_name=None):
"""Analyze Go call graph"""
print(f"Analyzing Go Call Graph: {source_dir}")
try:
# Go call graph analysis script path
callgraph_script = Path(__file__).parent / "SCA" / "callGraph" / "golang" / "goCallGraph.go"
if not callgraph_script.exists():
print(f"Call Graph script not found: {callgraph_script}")
return None
# Execute Go call graph
print("Running Go SSA Call Graph analysis...")
# Use repo_name if provided, otherwise use directory name
if not repo_name:
repo_name = Path(source_dir).name
safe_name = repo_name.replace('@', '_').replace('/', '_').replace(' ', '_')
# Pass OUTPUT_DIR and REPO_NAME as environment variables
env = os.environ.copy()
env['OUTPUT_DIR'] = str(output_dir.resolve()) # Use absolute path
if repo_name:
env['REPO_NAME'] = repo_name
result = subprocess.run(
["go", "run", str(callgraph_script), str(source_dir)],
cwd=callgraph_script.parent,
capture_output=True,
text=True,
env=env
)
# Always print output to see what's happening
if result.stdout:
print(result.stdout)
if result.stderr:
print("Errors:", result.stderr)
if result.returncode != 0:
print(f"Warning: Call Graph analysis encountered issues (continuing)")
# Output file is now directly in output_dir
output_file = output_dir / f"{safe_name}-callGraph.json"
if output_file.exists():
print(f"Call Graph generated: {output_file.name}")
# Print statistics
with open(output_file, 'r', encoding='utf-8') as f:
callgraph_data = json.load(f)
print(f" - Packages: {callgraph_data.get('packages', 0)}")
print(f" - Functions: {callgraph_data.get('functions', 0)}")
print(f" - Edges: {callgraph_data.get('edges', 0)}")
return {'callgraph_file': output_file, 'data': callgraph_data}
else:
print("Warning: Call Graph output file not found")
return None
except FileNotFoundError:
print("Go command not found. Please ensure Go is installed.")
return None
except Exception as e:
print(f"Call Graph analysis failed: {e}")
import traceback
traceback.print_exc()
return None
def analyze_npm_callgraph(source_dir, output_dir, repo_name=None):
"""Analyze NPM call graph"""
print(f"Analyzing TypeScript/JavaScript Call Graph: {source_dir}")
try:
# Detect package manager (pnpm or npm)
source_dir_path = Path(source_dir)
node_modules_path = source_dir_path / "node_modules"
package_json_path = source_dir_path / "package.json"
pnpm_lock_path = source_dir_path / "pnpm-lock.yaml"
is_pnpm = pnpm_lock_path.exists()
if package_json_path.exists() and not node_modules_path.exists():
if is_pnpm:
print("Detected pnpm project (pnpm-lock.yaml found)")
print("node_modules not found, running pnpm install...")
try:
install_result = subprocess.run(
["pnpm", "install", "--ignore-scripts", "--no-frozen-lockfile"],
cwd=str(source_dir_path),
capture_output=True,
text=True,
timeout=300
)
if install_result.returncode == 0:
print("pnpm install completed successfully")
else:
print(f"Warning: pnpm install had issues (continuing anyway)")
if install_result.stderr:
print(f" stderr: {install_result.stderr[:200]}")
except subprocess.TimeoutExpired:
print("Warning: pnpm install timed out (continuing anyway)")
except FileNotFoundError:
print("Warning: pnpm not found. Please run 'pnpm install' manually")
except Exception as e:
print(f"Warning: Failed to run pnpm install: {e}")
else:
print("node_modules not found, running npm install...")
try:
install_result = subprocess.run(
["npm", "install"],
cwd=str(source_dir_path),
capture_output=True,
text=True,
timeout=300
)
if install_result.returncode == 0:
print("npm install completed successfully")
else:
print(f"Warning: npm install had issues (continuing anyway)")
if install_result.stderr:
print(f" stderr: {install_result.stderr[:200]}")
except subprocess.TimeoutExpired:
print("Warning: npm install timed out (continuing anyway)")
except FileNotFoundError:
print("Warning: npm not found. Please run 'npm install' manually")
except Exception as e:
print(f"Warning: Failed to run npm install: {e}")
# TypeScript call graph script path
callgraph_script = Path(__file__).parent / "SCA" / "callGraph" / "npm" / "tsCallGraph.ts"
if not callgraph_script.exists():
print(f"Call Graph script not found: {callgraph_script}")
return None
# Check package.json
package_json_path = callgraph_script.parent / "package.json"
if not package_json_path.exists():
print(f"package.json not found: {package_json_path}")
return None
# Execute TypeScript call graph
print("Running TypeScript Call Graph analysis...")
# Use repo_name if provided, otherwise use package.json name
if repo_name:
safe_name = repo_name
else:
with open(Path(source_dir) / "package.json", 'r', encoding='utf-8') as f:
pkg_data = json.load(f)
project_name = pkg_data.get('name', Path(source_dir).name)
# Extract last segment from @org/package-name
safe_name = project_name.replace('@', '').replace('/', '-')
if '/' in project_name:
safe_name = project_name.split('/')[-1]
# Run tsx with cwd set to Bomtori root
# Pass repo_name and output_dir as environment variables
env = os.environ.copy()
if repo_name:
env['REPO_NAME'] = repo_name
env['OUTPUT_DIR'] = str(output_dir.resolve()) # Use absolute path
result = subprocess.run(
["npx", "tsx", str(callgraph_script), str(source_dir), "--analyze-node-modules"],
cwd=str(Path(__file__).parent), # Use Bomtori root as cwd
capture_output=True,
text=True,
env=env
)
if result.returncode != 0:
print(f"Warning: Call Graph analysis encountered issues (continuing)")
print(f" stderr: {result.stderr[:500]}")
# Output file is now in output_dir (passed via OUTPUT_DIR env var)
output_file = output_dir / f"{safe_name}-callGraph.json"
if output_file.exists():
print(f"Call Graph generated: {output_file.name}")
# Print statistics
with open(output_file, 'r', encoding='utf-8') as f:
callgraph_data = json.load(f)
print(f" - Files: {callgraph_data.get('files', 0)}")
print(f" - Functions: {callgraph_data.get('functions', 0)}")
print(f" - Edges: {callgraph_data.get('edges', 0)}")
return {'callgraph_file': output_file, 'data': callgraph_data}
else:
print("Warning: Call Graph output file not found")
return None
except FileNotFoundError:
print("npx or tsx not found. Please ensure Node.js is installed.")
return None
except Exception as e:
print(f"Call Graph analysis failed: {e}")
import traceback
traceback.print_exc()
return None
def run_vulnerability_analysis(source_dir, output_dir, repo_name, project_type):
"""Run vulnerability reachability analysis"""
print("\n[2/2] Vulnerability Reachability Analysis")
try:
# Import vulnerability analysis module based on project type
sys.path.insert(0, str(Path(__file__).parent / "SCA" / "vuln"))
# Convert to Path objects
output_dir = Path(output_dir)
source_dir = Path(source_dir)
# Find call graph file
safe_name = repo_name.replace('@', '_').replace('/', '_').replace(' ', '_')
callgraph_file = output_dir / f"{safe_name}-callGraph.json"
if not callgraph_file.exists():
print(f"Warning: Call Graph file not found: {callgraph_file}")
print("Skipping vulnerability analysis")
return None
# Import and run appropriate analyzer based on project type
if project_type == ProjectType.GOLANG:
from golang.analyzer import run_vulnerability_analysis as run_go_vuln_analysis
result = run_go_vuln_analysis(
callgraph_file=str(callgraph_file),
project_path=str(source_dir),
output_file=str(output_dir / f"{safe_name}-reachability.json")
)
elif project_type == ProjectType.NPM:
from npm.analyzer import run_vulnerability_analysis as run_npm_vuln_analysis
# For npm/pnpm, we also need audit.json
# Check in source_dir first, then try to generate it
audit_file = Path(source_dir) / "audit.json"
# Detect package manager (pnpm or npm)
pnpm_lock_path = Path(source_dir) / "pnpm-lock.yaml"
is_pnpm = pnpm_lock_path.exists()
if not audit_file.exists():
# Try to generate audit.json
print(f"audit.json not found, attempting to generate it...")
import subprocess
try:
# Use pnpm audit for pnpm projects, npm audit for npm projects
if is_pnpm:
print("Detected pnpm project, running pnpm audit...")
audit_command = ['pnpm', 'audit', '--json']
package_manager = 'pnpm'
else:
print("Running npm audit...")
audit_command = ['npm', 'audit', '--json']
package_manager = 'npm'
# Change to source directory and run audit
print(f" Executing: {' '.join(audit_command)} in {source_dir}")
result = subprocess.run(
audit_command,
cwd=str(source_dir),
capture_output=True,
text=True,
timeout=120 # Increase timeout for large projects
)
# Log stdout and stderr for debugging
if result.stdout:
print(f" Audit stdout length: {len(result.stdout)} bytes")
if result.stderr:
print(f" Audit stderr: {result.stderr[:200]}")
print(f" Audit exit code: {result.returncode}")
if result.returncode == 0 or (result.returncode != 0 and result.stdout):
# audit can return non-zero exit code even with valid JSON output
# Check if output is valid JSON
try:
import json
audit_data = json.loads(result.stdout)
# Check if audit_data is a dict or list
if isinstance(audit_data, list):
# pnpm audit sometimes returns a list directly
print(f" Warning: pnpm audit returned a list, not a dict. This format is not fully supported.")
vuln_count = len(audit_data) if audit_data else 0
print(f" Found {vuln_count} items in pnpm audit list format")
elif isinstance(audit_data, dict):
# Check if audit has vulnerabilities
if 'vulnerabilities' in audit_data:
vuln_count = len(audit_data['vulnerabilities'])
print(f" Found {vuln_count} vulnerable packages in audit.json")
elif 'actions' in audit_data:
# pnpm format
# pnpm audit 구조: {"actions": [{"action": "update", "module": "package", "resolves": [{"id": 123, ...}]}]}
actions = audit_data.get('actions', [])
vuln_count = 0
for action in actions:
if isinstance(action, dict):
# resolves는 리스트 (딕셔너리가 아님!)
resolves = action.get('resolves', [])
if isinstance(resolves, list):
# resolves 리스트의 각 항목이 하나의 취약점
vuln_count += len(resolves)
print(f" Found {vuln_count} vulnerabilities in pnpm audit format")
else:
print(f" Warning: No vulnerabilities field found in audit output")
else:
print(f" Warning: Unexpected audit data type: {type(audit_data)}")
# Valid JSON, save it to both source_dir and output_dir
audit_file.write_text(result.stdout, encoding='utf-8')
print(f" Generated audit.json: {audit_file}")
# Also save to output_dir for inspection
output_audit_file = output_dir / f"{safe_name}-audit.json"
output_audit_file.write_text(result.stdout, encoding='utf-8')
print(f" Saved audit.json to output directory: {output_audit_file}")
except json.JSONDecodeError as e:
print(f" Warning: {package_manager} audit output is not valid JSON: {e}")
print(f" Output preview: {result.stdout[:200]}")
print("Skipping vulnerability analysis")
return None
else:
print(f" Warning: Failed to run {package_manager} audit (exit code: {result.returncode})")
if result.stderr:
print(f" Error: {result.stderr[:500]}")
print(f" Run '{package_manager} audit --json > audit.json' in the project directory")
print("Skipping vulnerability analysis")
return None
except FileNotFoundError:
print(f"Warning: {package_manager} not found. Please install Node.js and {package_manager}")
print(f"Or run '{package_manager} audit --json > audit.json' in the project directory")
print("Skipping vulnerability analysis")
return None
except Exception as e:
print(f"Warning: Failed to generate audit.json: {e}")
print(f"Run '{package_manager} audit --json > audit.json' in the project directory")
print("Skipping vulnerability analysis")
return None
result = run_npm_vuln_analysis(
callgraph_file=str(callgraph_file),
audit_file=str(audit_file),
project_path=str(source_dir),
output_file=str(output_dir / f"{safe_name}-reachability.json")
)
else:
print(f"Warning: Vulnerability analysis not supported for project type: {project_type.value}")
return None
return result
except ImportError as e:
print(f"Warning: Could not import vulnerability analysis module: {e}")
print("Skipping vulnerability analysis")
return None
except Exception as e:
print(f"Warning: Vulnerability analysis failed: {e}")
import traceback
traceback.print_exc()
return None
def generate_summary_report(output_dir, repo_name, sbom_result, sca_result, vuln_result=None):
"""Generate summary report"""
print("\n" + "=" * 60)
print("Analysis Summary Report")
print("=" * 60)
summary = {
"repository": repo_name,
"analysis_timestamp": datetime.now(timezone.utc).isoformat(),
"sbom": {},
"sca": {},
"vulnerability": {}
}
# Add SBOM information
if sbom_result and 'analysis_result' in sbom_result:
analysis = sbom_result['analysis_result']
summary['sbom'] = {
"packages_found": len(analysis.get('packages', [])),
"status": "Success"
}
else:
summary['sbom']['status'] = "Failed"
# Add SCA information
if sca_result and 'data' in sca_result:
sca_data = sca_result['data']
summary['sca'] = {
"functions": sca_data.get('functions', 0),
"edges": sca_data.get('edges', 0),
"status": "Success"
}
else:
summary['sca']['status'] = "Failed"
# Add Vulnerability information
if vuln_result:
vuln_summary = vuln_result.get('summary', {})
vulnerabilities = vuln_result.get('vulnerabilities', [])
# Calculate statistics from vulnerabilities array
# Check both 'reachable' field and 'reaching_entry_points' existence
total_reachable_funcs = 0
total_unreachable_funcs = 0
reachable_vulns = 0
unreachable_vulns = 0
total_funcs = 0
for vuln in vulnerabilities:
has_reachable = False
for func_result in vuln.get('vulnerable_functions', []):
total_funcs += 1
# Check if function is reachable
# Either 'reachable' is True OR 'reaching_entry_points' exists
is_reachable = func_result.get('reachable', False)
reaching_entries = func_result.get('reaching_entry_points', [])
if is_reachable or reaching_entries:
total_reachable_funcs += 1
has_reachable = True
else:
total_unreachable_funcs += 1
if has_reachable:
reachable_vulns += 1
else:
unreachable_vulns += 1
# If total_funcs is 0, try to get from summary (fallback for golang analyzer format)
if total_funcs == 0:
total_funcs = vuln_summary.get('total_vulnerable_functions', 0)
total_reachable_funcs = vuln_summary.get('reachable_functions', 0)
total_unreachable_funcs = vuln_summary.get('unreachable_functions', 0)
# Calculate rates
total_vulns = vuln_summary.get('total_vulnerabilities', len(vulnerabilities))
if total_vulns > 0:
vuln_rate = f"{(reachable_vulns / total_vulns * 100):.1f}%"
else:
vuln_rate = "0%"
if total_funcs > 0:
func_rate = f"{(total_reachable_funcs / total_funcs * 100):.1f}%"
else:
func_rate = "0%"
summary['vulnerability'] = {
# Overall vulnerability statistics
"total_vulnerabilities": total_vulns,
"reachable_vulnerabilities": reachable_vulns,
"unreachable_vulnerabilities": unreachable_vulns,
"vulnerability_reachability_rate": vuln_rate,
# Vulnerable function statistics
"total_vulnerable_functions": total_funcs,
"reachable_functions": total_reachable_funcs,
"unreachable_functions": total_unreachable_funcs,
"function_reachability_rate": func_rate,
"status": "Success"
}
else:
summary['vulnerability']['status'] = "Skipped or Failed"
# Save summary report
summary_file = output_dir / f"{repo_name}-summary.json"
with open(summary_file, 'w', encoding='utf-8') as f:
json.dump(summary, f, indent=2, ensure_ascii=False)
print(f"Summary report generated: {summary_file.name}")
print(f"\n" + "=" * 60)
print("Analysis Results")
print("=" * 60)
# SBOM
print(f"\nSBOM:")
print(f" Status: {summary['sbom'].get('status', 'Unknown')}")
if summary['sbom'].get('status') == 'Success':
print(f" Packages: {summary['sbom']['packages_found']}")
# SCA (includes Call Graph and Vulnerability)
print(f"\nSCA:")
print(f" Status: {summary['sca'].get('status', 'Unknown')}")
# Call Graph (within SCA)
if summary['sca'].get('status') == 'Success':
print(f" Call Graph:")
print(f" - Functions: {summary['sca']['functions']}")
print(f" - Edges: {summary['sca']['edges']}")
# Vulnerability Analysis (within SCA)
if summary.get('vulnerability') and summary['vulnerability'].get('status') != 'N/A':
print(f" Vulnerability Analysis:")
print(f" Status: {summary['vulnerability'].get('status', 'Unknown')}")
if summary['vulnerability'].get('status') == 'Success':
vuln = summary['vulnerability']
print(f" Vulnerabilities:")
print(f" - Total: {vuln.get('total_vulnerabilities', 0)}")
print(f" - Reachable: {vuln.get('reachable_vulnerabilities', 0)}")
print(f" - Unreachable: {vuln.get('unreachable_vulnerabilities', 0)}")
print(f" - Reachability rate: {vuln.get('vulnerability_reachability_rate', '0%')}")
print(f" Vulnerable Functions:")
print(f" - Total: {vuln.get('total_vulnerable_functions', 0)}")
print(f" - Reachable: {vuln.get('reachable_functions', 0)}")
print(f" - Unreachable: {vuln.get('unreachable_functions', 0)}")
print(f" - Reachability rate: {vuln.get('function_reachability_rate', '0%')}")
else:
print(f" Vulnerability Analysis: N/A (not supported for this project type)")
def _fetch_nvd_details(cve_id: str) -> Dict[str, Any]:
"""Fetch CVSS/Severity information from NVD as a fallback."""
details = {'cvss': None, 'severity': None}
if not cve_id:
return details
try:
nvd_url = f"https://services.nvd.nist.gov/rest/json/cves/2.0?cveId={cve_id}"
req = urllib.request.Request(nvd_url)
req.add_header('User-Agent', 'Bomtori-dashboard')
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
with urllib.request.urlopen(req, context=ssl_context, timeout=10) as response:
data = json.loads(response.read().decode('utf-8'))
vulnerabilities = data.get('vulnerabilities', [])
if not vulnerabilities:
return details
cve_info = vulnerabilities[0].get('cve', {})
metrics = cve_info.get('metrics', {})
for metric_key in ('cvssMetricV40', 'cvssMetricV31', 'cvssMetricV30', 'cvssMetricV2'):
metric_list = metrics.get(metric_key)
if not metric_list:
continue
metric = metric_list[0]
cvss_data = metric.get('cvssData', {})
score = cvss_data.get('baseScore')
severity = cvss_data.get('baseSeverity')
if score is not None:
try:
details['cvss'] = round(float(score), 1)
except (TypeError, ValueError):
pass
if severity:
details['severity'] = str(severity).upper()
# Use first available metric
break
except Exception:
pass
return details
def _fetch_advisory_details(advisory_id: str) -> Dict[str, Any]:
"""
Fetch CVE, CVSS, and detailed description from OSV.dev API
Args:
advisory_id: GHSA ID or CVE ID
Returns:
Dictionary with CVE, CVSS, description, and fixed versions
"""
details = {
'cve': None,
'cvss': None,
'severity': None,
'description': None,
'fixed_version': None,
'all_fixed_versions': []
}
try:
osv_url = f"https://api.osv.dev/v1/vulns/{advisory_id}"
req = urllib.request.Request(osv_url)
req.add_header('Content-Type', 'application/json')
req.add_header('User-Agent', 'Bomtori-dashboard')
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
with urllib.request.urlopen(req, context=ssl_context, timeout=10) as response:
data = json.loads(response.read().decode('utf-8'))
# Extract CVE
aliases = data.get('aliases', [])
for alias in aliases:
if alias.startswith('CVE-'):
details['cve'] = alias
break
# Extract CVSS
database_specific = data.get('database_specific', {}) or {}
cvss_score = None
severity_label = None
# Database-specific CVSS score
if 'cvss_score' in database_specific:
try:
cvss_score = float(database_specific['cvss_score'])
except (TypeError, ValueError):
pass
# Database-specific severity label
db_severity = database_specific.get('severity')
if isinstance(db_severity, str):
severity_label = db_severity.upper()
elif isinstance(db_severity, (int, float)) and cvss_score is None:
cvss_score = float(db_severity)
# OSV severity array
severity_entries = data.get('severity')
if severity_entries:
if isinstance(severity_entries, list):
for entry in severity_entries:
if isinstance(entry, dict):
score_val = entry.get('score')
if score_val is not None:
if isinstance(score_val, (int, float)):
score_numeric = float(score_val)
if cvss_score is None or score_numeric > cvss_score:
cvss_score = score_numeric
else:
score_str = str(score_val).strip()
try:
score_numeric = float(score_str)
if cvss_score is None or score_numeric > cvss_score:
cvss_score = score_numeric
except ValueError:
# Leave severity unchanged; CVSS vector handled later
pass
if not severity_label:
severity_text = entry.get('severity') or entry.get('type')
if isinstance(severity_text, str):
severity_label = severity_text.upper()
else:
if not severity_label:
severity_label = str(entry).upper()
else:
if not severity_label:
severity_label = str(severity_entries).upper()
# Apply extracted scores
if cvss_score is not None:
details['cvss'] = round(float(cvss_score), 1)
if severity_label:
details['severity'] = severity_label
# Extract description (prefer details over summary)
details['description'] = data.get('details', '') or data.get('summary', '')
# Extract fixed versions from affected ranges (may have multiple)
affected = data.get('affected', [])
fixed_versions = []
for aff in affected:
ranges = aff.get('ranges', [])
for range_info in ranges:
events = range_info.get('events', [])
for event in events:
if 'fixed' in event:
fixed_ver = event['fixed']
if fixed_ver and fixed_ver not in fixed_versions:
fixed_versions.append(fixed_ver)
# Use the highest version as fixed_version (or first if can't compare)
if fixed_versions:
# Try to sort versions (simple string comparison for now)
fixed_versions.sort(reverse=True)
details['fixed_version'] = fixed_versions[0]
details['all_fixed_versions'] = fixed_versions
# Fallback to NVD if CVE exists but OSV lacks CVSS/Severity
severity_value = details.get('severity')
needs_severity = severity_value is None or (isinstance(severity_value, str) and severity_value.upper().startswith('CVSS:'))
if details['cve'] and (details['cvss'] is None or needs_severity):
nvd_details = _fetch_nvd_details(details['cve'])
if details['cvss'] is None and nvd_details.get('cvss') is not None:
details['cvss'] = nvd_details['cvss']
if needs_severity and nvd_details.get('severity'):
details['severity'] = nvd_details['severity']
except Exception as e:
# API 호출 실패 시 무시 (기존 정보만 사용)
pass
return details
def _build_dependency_type_map(
sbom_data: Optional[Dict[str, Any]],
repo_name: str,
project_type: str = 'npm'
) -> Dict[str, Dict[Any, str]]:
"""
Build a mapping of component name -> dependency_type ('direct' or 'transitive')
using CycloneDX dependencies section.
"""
if not sbom_data:
return {'by_ref': {}, 'by_name_version': {}}
components = sbom_data.get('components', [])
dependencies = sbom_data.get('dependencies', [])
if not components or not dependencies:
return {'by_ref': {}, 'by_name_version': {}}
name_by_ref: Dict[str, str] = {}
for comp in components:
ref = comp.get('bom-ref')
name = comp.get('name')
if ref and name:
name_by_ref[ref] = name
# Determine root dependency entry (matches repo name if possible)
root_entry = None
repo_lower = repo_name.lower()
for entry in dependencies:
ref = entry.get('ref', '')
comp_name = name_by_ref.get(ref, '')
if comp_name and repo_lower in comp_name.lower():
root_entry = entry
break
direct_refs: set[str] = set()
if root_entry:
direct_refs.update(root_entry.get('dependsOn', []) or [])
else:
# Fallback: components whose dependency entry has no parent
child_refs = set()
for entry in dependencies:
child_refs.update(entry.get('dependsOn', []) or [])
for entry in dependencies:
ref = entry.get('ref')
if ref and ref not in child_refs:
direct_refs.add(ref)
dep_type_by_ref: Dict[str, str] = {}
dep_type_by_name_version: Dict[tuple[str, str], str] = {}
for comp in components:
ref = comp.get('bom-ref')
name = comp.get('name')
if not name or not ref:
continue
version = comp.get('version', '')
key = (name.lower(), version)
dep_type = 'direct' if ref in direct_refs else 'transitive'
if project_type == 'golang' and name in {'go', 'toolchain'}:
dep_type = 'stdlib'
dep_type_by_ref[ref] = dep_type
dep_type_by_name_version[key] = dep_type
if project_type == 'golang':
for comp in components:
name = comp.get('name', '')
if name and name.startswith('stdlib'):