-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathsunshine.py
More file actions
2421 lines (1981 loc) · 103 KB
/
sunshine.py
File metadata and controls
2421 lines (1981 loc) · 103 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
# This file is part of CycloneDX Sunshine
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) OWASP Foundation. All Rights Reserved.
__all__ = [
# This module does not export any symbols; all sumbols are private/internal.
]
import json
import argparse
import os
import html
import copy
import re
if __name__ != "__web__":
import requests
import csv
from decimal import Decimal
if __name__ == "__web__":
from js import writeToLog, fetchDataSync
NAME = "Sunshine"
PREFERRED_VULNERABILITY_RATING_METHODS_ORDER = ["CVSSv4",
"CVSSv31",
"CVSSv3",
"CVSSv2",
"OWASP",
"SSVC",
"other"]
VALID_SEVERITIES = {"critical": 4,
"high": 3,
"medium": 2,
"low": 1,
"info": 0,
"information": 0,
"unknown": -1,
"clean": -2}
GREY = '#bcbcbc'
GREEN = '#7dd491'
YELLOW = '#fccd58'
ORANGE = '#ff9335'
RED = '#ff4633'
DARK_RED = '#a10a0a'
LIGHT_BLUE = '#9fc5e8'
BASIC_STYLE = { "color": GREY, "borderWidth": 2 }
INFORMATION_STYLE = { "color": GREEN, "borderWidth": 2 }
LOW_STYLE = { "color": YELLOW, "borderWidth": 2 }
MEDIUM_STYLE = { "color": ORANGE, "borderWidth": 2 }
HIGH_STYLE = { "color": RED, "borderWidth": 2 }
CRITICAL_STYLE = { "color": DARK_RED, "borderWidth": 2 }
TRANSITIVE_VULN_STYLE = { "color": LIGHT_BLUE, "borderWidth": 2 }
STYLES = {"critical": CRITICAL_STYLE,
"high": HIGH_STYLE,
"medium": MEDIUM_STYLE,
"low": LOW_STYLE,
"information": INFORMATION_STYLE,
"clean": BASIC_STYLE,
"unknown": INFORMATION_STYLE}
REMAINING_WEB_LOGS = 200
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sunshine - SBOM visualization tool</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css">
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.8/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.8/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://fastly.jsdelivr.net/npm/echarts@5.5.1/dist/echarts.min.js"></script>
<style>
body {
margin: 20px;
height: 100vh;
background: linear-gradient(to right, #032c57, #1C538E);
}
#output {
white-space: pre-line;
background-color: #ffffff;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
margin-top: 10px;
font-family: "Courier New", "Lucida Console", monospace;
}
#chart-container {
background-color: #ffffff;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
position: relative;
}
#chart-container-inner, #chart-container-only-vulnerable-inner {
background-color: #ffffff;
padding: 10px;
position: relative;
height: 90vh;
overflow: hidden;
}
#chart-container-placeholder {
background-color: #fffffF;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
}
#table-container, #info-table-container, #vulnerabilities-table-container {
background-color: #fffffF;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
overflow-x:auto;
max-width:100%;
}
#table-container-placeholder, #info-table-container-placeholder, #vulnerabilities-table-container-placeholder {
background-color: #fffffF;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
}
#upload-file-container {
background-color: #fffffF;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
}
#file-input {
margin: 20px;
}
.dataTables_filter {
display: none;
}
th input {
width: 100%;
box-sizing: border-box;
}
.dataTables_length {
padding-bottom: 10px !important;
}
.light-text {
color: #baccde;
}
.dt-buttons {
float: right;
}
.active>.page-link, .page-link.active {
background-color: #1C538E !important;
color: white !important;
}
.page-link {
color: #1C538E;
}
#components-table_paginate, #vulnerabilities-table_paginate {
float: right;
margin-top: -33px;
}
.bg-dark-red {
background-color: #a10a0a;
color: white;
}
.bg-orange {
background-color: #ff9335;
color: white;
}
.bg-yellow {
background-color: #fccd58;
color: white;
}
.bg-light-blue {
background-color: #9fc5e8;
color: black;
}
#footer {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
background-color: #032c57;
color: #baccde;
text-align: center;
z-index: 100000;
}
#footer a {
color: #baccde;
}
#info-table_paginate, #info-table_length, #info-table_info {
display: none;
}
.opaque {
opacity: 0.5;
}
@media print {
body {
background-color: transparent !important;
background-image: none !important;
}
}
.loading-overlay {
position: fixed;
width: 100%;
height: 100vh;
background: #032c57;
top: 0;
left: 0;
z-index: 1000;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
color: #baccde;
text-transform: uppercase;
letter-spacing: 0.3rem;
font-weight: bold;
}
.spinner {
border: 4px solid #baccde;
border-top: 4px solid #3498db;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 2s linear infinite;
margin-bottom: 10px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
</head>
<body>
<div id="loadingOverlay" class="loading-overlay">
<div class="spinner"></div>
<div class="loading-text">Loading Sunshine SBOM...</div>
</div>
<h1 class="light-text">Sunshine - SBOM visualization tool</h1>
<br>
<div id="upload-file-container">
<span>Analyzed CycloneDX JSON file: <i><FILE_NAME_HERE></i></span>
</div>
<br>
<h3 class="light-text">Summary</h3>
<div id="info-table-container">
<table id="info-table" class="table table-striped table-bordered" style="width:100%"><METADATA_TABLE_HERE></table>
</div>
<br><br>
<h3 class="light-text">Components chart</h3>
<div id="chart-container">
This chart visualizes components and their dependencies, with each segment representing a single component. The chart provides a hierarchical view of the dependency structure, with relationships radiating outward from the core components.<br>
<ul>
<li><b>Innermost circle:</b> represents components that are independent and not dependencies for any other components.</li>
<li><b>Outer circles:</b> each segment represents a dependency of the corresponding segment in the circle immediately inside it. The farther a segment is from the center, the deeper the dependency level.</li>
</ul>
<i>Note: If there is only one circle, it means that no dependency relationships are defined in the input file.</i>
<br><br>
The colors of the segments indicate the vulnerability status of the components:
<ul>
<li><b>Dark red:</b> affected by at least one critical severity vulnerability.</li>
<li><b>Red:</b> affected by at least one high severity vulnerability.</li>
<li><b>Orange:</b> affected by at least one medium severity vulnerability.</li>
<li><b>Yellow:</b> affected by at least one low severity vulnerability.</li>
<li><b>Green:</b> affected by at least one informational severity vulnerability.</li>
<li><b>Light blue:</b> not directly affected by vulnerabilities but has at least one vulnerable dependency.</li>
<li><b>Grey:</b> neither the component nor its dependencies are affected by any vulnerabilities.</li>
</ul>
The chart is interactive:
<ul>
<li><b>Hovering:</b> displays details about a component, including its name, version, and list of vulnerabilities.</li>
<li><b>Clicking:</b> refocuses the chart. The clicked segment becomes the center (second innermost circle), showing only that component and its dependencies. In this view, the innermost circle is always blue. Clicking the blue circle navigates back up one level in the dependency hierarchy.</li>
</ul>
<hr>
<div class="form-check" id="sunburst-selector-all">
<input class="form-check-input" type="radio" name="showComponentsSwitch" id="allComponents" value="allComponents" checked onchange="handleShowComponentsSwitchChange(this)">
<label class="form-check-label" for="allComponents">
Show all components
</label>
</div>
<div class="form-check" id="sunburst-selector-vulnerable">
<input class="form-check-input" type="radio" name="showComponentsSwitch" id="vulnerableComponents" value="vulnerableComponents" onchange="handleShowComponentsSwitchChange(this)">
<label class="form-check-label" for="vulnerableComponents">
Show only components with direct or transitive vulnerabilities
</label>
</div>
<hr>
<div id="chart-container-inner" style="display: block"></div>
<div id="chart-container-only-vulnerable-inner" style="display: none"></div>
</div>
<br>
<h3 class="light-text">Components table</h3>
<div id="table-container">
This table visualizes components, their dependencies, vulnerabilities and licenses.<br>
The colors of the elements in columns "Component", "Depends on" and "Dependency of" indicate the vulnerability status of the components:
<ul>
<li><b>Dark red:</b> affected by at least one critical severity vulnerability.</li>
<li><b>Red:</b> affected by at least one high severity vulnerability.</li>
<li><b>Orange:</b> affected by at least one medium severity vulnerability.</li>
<li><b>Yellow:</b> affected by at least one low severity vulnerability.</li>
<li><b>Green:</b> affected by at least one informational severity vulnerability.</li>
<li><b>Light blue:</b> not directly affected by vulnerabilities but has at least one vulnerable dependency.</li>
<li><b>Grey:</b> neither the component nor its dependencies are affected by any vulnerabilities.</li>
</ul>
<br>
The colors of the elements in columns "Direct vulnerabilities" and "Transitive vulnerabilities" indicate the severity of the vulnerabilities:
<ul>
<li><b>Dark red:</b> critical.</li>
<li><b>Red:</b> high.</li>
<li><b>Orange:</b> medium.</li>
<li><b>Yellow:</b>low.</li>
<li><b>Green:</b>informational.</li>
</ul>
<br>
The "Depth" column indicates a component's position in the dependency graph:
<ul>
<li>A <b>"root"</b> value means it is a root component, meaning it resides in the innermost circle of the chart.</li>
<li>An <b>integer</b> value represents the component's depth level within the dependency chain.</li>
</ul>
<i>Note: since a single component may be a dependency for multiple components in different places in the dependency graph, it may be associated with multiple depths.</i>
<hr><br>
<div id="table-container-inner">
<table id="components-table" class="table table-striped table-bordered" style="width:100%"><COMPONENTS_TABLE_HERE></table>
</div>
</div>
<br>
<h3 class="light-text">Vulnerabilities table</h3>
<div id="vulnerabilities-table-container">
This table focuses on vulnerabilities and shows the components that are affected either directly or transitively.<br>
The colors of the elements in column "Vulnerability" indicate the severity of the vulnerabilities:
<ul>
<li><b>Dark red:</b> critical.</li>
<li><b>Red:</b> high.</li>
<li><b>Orange:</b> medium.</li>
<li><b>Yellow:</b>low.</li>
<li><b>Green:</b>informational.</li>
</ul>
<br>
The colors of the elements in columns "Directly vulnerable components" and "Transitively vulnerable components" indicate the vulnerability status of the components:
<ul>
<li><b>Dark red:</b> affected by at least one critical severity vulnerability.</li>
<li><b>Red:</b> affected by at least one high severity vulnerability.</li>
<li><b>Orange:</b> affected by at least one medium severity vulnerability.</li>
<li><b>Yellow:</b> affected by at least one low severity vulnerability.</li>
<li><b>Green:</b> affected by at least one informational severity vulnerability.</li>
<li><b>Light blue:</b> not directly affected by vulnerabilities but has at least one vulnerable dependency.</li>
</ul>
<hr><br>
<table id="vulnerabilities-table" class="table table-striped table-bordered" style="width:100%"><VULNERABILITIES_TABLE_HERE></table>
</div>
<script type="text/javascript">
window.addEventListener('load', function() {
const loadingOverlay = document.getElementById('loadingOverlay');
loadingOverlay.style.opacity = '0';
loadingOverlay.style.transition = 'opacity 0.5s ease';
setTimeout(() => {
loadingOverlay.style.display = 'none';
}, 500);
});
function showDiv(divId) {
var div = document.getElementById(divId);
if (div.style.display === "none") {
div.style.display = "block";
}
}
function hideDiv(divId) {
var div = document.getElementById(divId);
if (div.style.display === "block") {
div.style.display = "none";
}
}
function handleShowComponentsSwitchChange(radio) {
if (radio.value == "allComponents") {
hideDiv("chart-container-only-vulnerable-inner");
showDiv("chart-container-inner");
var shownChart = echarts.getInstanceByDom(document.getElementById("chart-container-inner"));
shownChart.resize();
}
else if (radio.value == "vulnerableComponents") {
hideDiv("chart-container-inner");
showDiv("chart-container-only-vulnerable-inner");
var shownChart = echarts.getInstanceByDom(document.getElementById("chart-container-only-vulnerable-inner"));
shownChart.resize();
}
}
var dom = document.getElementById('chart-container-inner');
var myChart = echarts.init(dom, null, {
renderer: 'canvas',
useDirtyRect: false
});
var app = {};
var option;
const data = <CHART_DATA_HERE>;
option = {
tooltip: {
formatter: function(params) {
return `${params.name}`;
},
},
series: {
radius: ['15%', '100%'],
type: 'sunburst',
sort: undefined,
emphasis: {
focus: 'ancestor'
},
data: data,
label: {
rotate: 'radial',
show: false
},
levels: []
}
};
if (option && typeof option === 'object') {
myChart.setOption(option);
}
window.addEventListener('resize', myChart.resize);
var domVuln = document.getElementById('chart-container-only-vulnerable-inner');
var myChartVuln = echarts.init(domVuln, null, {
renderer: 'canvas',
useDirtyRect: false
});
var optionVuln;
const dataVuln = <CHART_DATA_VULN_HERE>;
optionVuln = {
tooltip: {
formatter: function(params) {
return `${params.name}`;
},
},
series: {
radius: ['15%', '100%'],
type: 'sunburst',
sort: undefined,
emphasis: {
focus: 'ancestor'
},
data: dataVuln,
label: {
rotate: 'radial',
show: false
},
levels: []
}
};
if (optionVuln && typeof optionVuln === 'object') {
myChartVuln.setOption(optionVuln);
}
window.addEventListener('resize', myChartVuln.resize);
let table = $('#components-table').DataTable({
"order": [[ 1, "asc" ]],
pageLength: 10,
dom: 'Blfrtip',
lengthMenu: [
[10, 25, 50, -1],
[10, 25, 50, 'All']
],
buttons: [
{ extend: 'copy', className: 'btn btn-dark mb-3 btn-sm' },
{ extend: 'csv', className: 'btn btn-secondary mb-3 btn-sm' },
{ extend: 'excel', className: 'btn btn-success mb-3 btn-sm' },
{ extend: 'print', className: 'btn btn-danger mb-3 btn-sm',
customize: function (win) {
$(win.document.body).css('font-size', '10pt');
$(win.document.body).find('table').addClass('compact').css('font-size', 'inherit');
// Add landscape mode
var css = '@page { size: landscape; }',
head = win.document.head || win.document.getElementsByTagName('head')[0],
style = win.document.createElement('style');
style.type = 'text/css';
style.media = 'print';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(win.document.createTextNode(css));
}
head.appendChild(style);
}
}
],
orderCellsTop: true,
"autoWidth": true
});
$('#components-table thead input').on('keyup change', function () {
let columnIndex = $(this).parent().index();
table.column(columnIndex).search(this.value).draw();
});
let summaryTable = $('#info-table').DataTable({
"order": [[ 1, "asc" ]],
pageLength: 10,
dom: 'Blfrtip',
lengthMenu: [
[10, 25, 50, -1],
[10, 25, 50, 'All']
],
buttons: [
{ extend: 'copy', className: 'btn btn-dark mb-3 btn-sm' },
{ extend: 'csv', className: 'btn btn-secondary mb-3 btn-sm' },
{ extend: 'excel', className: 'btn btn-success mb-3 btn-sm' },
{ extend: 'print', className: 'btn btn-danger mb-3 btn-sm',
customize: function (win) {
$(win.document.body).css('font-size', '10pt');
$(win.document.body).find('table').addClass('compact').css('font-size', 'inherit');
// Add landscape mode
var css = '@page { size: landscape; }',
head = win.document.head || win.document.getElementsByTagName('head')[0],
style = win.document.createElement('style');
style.type = 'text/css';
style.media = 'print';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(win.document.createTextNode(css));
}
head.appendChild(style);
}
}
],
orderCellsTop: true,
"autoWidth": true
});
let vulnerabilitiesTable = $('#vulnerabilities-table').DataTable({
"order": [[ 1, "asc" ]],
pageLength: 10,
dom: 'Blfrtip',
lengthMenu: [
[10, 25, 50, -1],
[10, 25, 50, 'All']
],
buttons: [
{ extend: 'copy', className: 'btn btn-dark mb-3 btn-sm' },
{ extend: 'csv', className: 'btn btn-secondary mb-3 btn-sm' },
{ extend: 'excel', className: 'btn btn-success mb-3 btn-sm' },
{ extend: 'print', className: 'btn btn-danger mb-3 btn-sm',
customize: function (win) {
$(win.document.body).css('font-size', '10pt');
$(win.document.body).find('table').addClass('compact').css('font-size', 'inherit');
// Add landscape mode
var css = '@page { size: landscape; }',
head = win.document.head || win.document.getElementsByTagName('head')[0],
style = win.document.createElement('style');
style.type = 'text/css';
style.media = 'print';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(win.document.createTextNode(css));
}
head.appendChild(style);
}
}
],
orderCellsTop: true,
"autoWidth": true
});
$('#vulnerabilities-table thead input').on('keyup change', function () {
let columnIndex = $(this).parent().index();
vulnerabilitiesTable.column(columnIndex).search(this.value).draw();
});
function countSegments(node) {
let count = 1;
if (node.children) {
node.children.forEach(child => {
count += countSegments(child);
});
}
return count;
}
function turnChartIntoImageIfTooManySegments(chartContainerId) {
var chartContainerInnerDiv = document.getElementById(chartContainerId);
var echartsInstance = echarts.getInstanceByDom(chartContainerInnerDiv);
var echartsInstanceData = echartsInstance.getOption().series[0].data;
let totalSegments = echartsInstanceData.reduce((sum, node) => sum + countSegments(node), 0);
if (totalSegments > 10000) {
var chartContainerInnerDivOnlyVuln = document.getElementById("chart-container-only-vulnerable-inner");
echarts.getInstanceByDom(chartContainerInnerDivOnlyVuln).dispose();
chartContainerInnerDivOnlyVuln.remove();
document.getElementById("sunburst-selector-all").innerHTML = '<div class="alert alert-warning" role="alert">WARNING: the chart is not displayed in interactive mode because there are too many dependency relationships. You can still explore components and relationships in the components table.</div>';
document.getElementById("sunburst-selector-vulnerable").remove();
chartContainerInnerDiv.style.display = "block";
echartsInstance.resize();
var imgData = echartsInstance.getDataURL({
type: 'png',
pixelRatio: 2, // Adjust as needed for resolution
backgroundColor: '#fff' // Optional: set background color
});
echartsInstance.dispose();
var img = document.createElement('img');
img.src = imgData;
img.style.width = '100%';
img.style.height = 'auto';
chartContainerInnerDiv.innerHTML = '';
chartContainerInnerDiv.appendChild(img);
chartContainerInnerDiv.style.height = 'auto';
}
}
function showWarningIfChartWasNotCreated(chartContainerId) {
var chartContainerInnerDiv = document.getElementById(chartContainerId);
var chartContainerInnerDivOnlyVuln = document.getElementById("chart-container-only-vulnerable-inner");
echarts.getInstanceByDom(chartContainerInnerDivOnlyVuln).dispose();
chartContainerInnerDivOnlyVuln.remove();
document.getElementById("sunburst-selector-all").innerHTML = '<div class="alert alert-danger" role="alert">WARNING: the chart is not displayed because there are too many dependency relationships. You can still explore components and relationships in the components table.</div>';
document.getElementById("sunburst-selector-vulnerable").remove();
chartContainerInnerDiv.style.display = "block";
chartContainerInnerDiv.innerHTML = '';
chartContainerInnerDiv.style.height = 'auto';
}
turnChartIntoImageIfTooManySegments("chart-container-inner");
<SHOW_WARNING_IF_CHART_WAS_NOT_CREATED>
</script>
<br><br>
<div id="footer">Sunshine - SBOM visualization tool | Made by <a href="https://www.linkedin.com/in/lucacapacci/">Luca Capacci</a> | Contributor <a href="https://www.linkedin.com/in/mattiafierro/">Mattia Fierro</a> | <a href="https://github.com/CycloneDX/Sunshine/">GitHub repository</a> | <a href="https://github.com/CycloneDX/Sunshine/blob/main/LICENSE">License</a></div>
</body>
</html>
"""
def custom_print(text):
if __name__ == "__web__":
global REMAINING_WEB_LOGS
if REMAINING_WEB_LOGS > 0:
REMAINING_WEB_LOGS -= 1
writeToLog(text)
if REMAINING_WEB_LOGS == 0:
writeToLog("WARNING: Messages were truncated because there are too many to be displayed here, use the CLI version to view all the messages")
else:
print(text)
class SetEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, set):
return list(obj)
return super().default(obj)
def create_fake_component(bom_ref):
return {"name": bom_ref,
"version": "-",
"type": "-",
"license": set(),
"depends_on": set(),
"dependency_of": set(),
"vulnerabilities": [],
"transitive_vulnerabilities": [],
"max_vulnerability_severity": "clean",
"has_transitive_vulnerabilities": False,
"visited": False}
def create_base_component(component):
new_component = {"name": component["name"],
"version": component["version"] if "version" in component else "-",
"type": component["type"] if "type" in component else "-",
"license": parse_licenses(component),
"depends_on": set(),
"dependency_of": set(),
"vulnerabilities": [],
"transitive_vulnerabilities": [],
"max_vulnerability_severity": "clean",
"has_transitive_vulnerabilities": False,
"visited": False}
return new_component
def get_severity_by_score(score):
score = float(score)
if score >= 9:
return "critical"
elif score >= 7:
return "high"
elif score >= 4:
return "medium"
elif score > 0:
return "low"
else:
return "information"
def get_preferred_vuln_source(source_1, source_2):
source_1 = source_1.upper()
source_2 = source_2.upper()
if source_1 == "NVD":
source_1_order = 0
elif source_1 in ["-", "EPSS"]:
source_1_order = 2
else:
source_1_order = 1
if source_2 == "NVD":
source_2_order = 0
elif source_2 in ["-", "EPSS"]:
source_2_order = 2
else:
source_2_order = 1
if source_1_order < source_2_order:
return source_1
else:
return source_2
def parse_vulnerability_data(vulnerability):
vuln_id = vulnerability["id"]
vuln_severity = None
vuln_score = 0.0
vuln_vector = "-"
vuln_source = "-"
found_at_least_one = False
if "ratings" in vulnerability:
for preferred_rating_method in PREFERRED_VULNERABILITY_RATING_METHODS_ORDER:
if found_at_least_one is True:
break
for rating in vulnerability["ratings"]:
if "method" not in rating:
continue
if rating["method"] == preferred_rating_method:
found_at_least_one = True
current_vuln_score = 0.0
current_vuln_vector = "-"
current_vuln_source = "-"
if "severity" in rating and rating["severity"].lower() in VALID_SEVERITIES:
current_vuln_severity = rating["severity"]
if current_vuln_severity.lower() == "info":
current_vuln_severity = "information"
current_vuln_severity = current_vuln_severity.lower()
if "score" in rating:
current_vuln_score = float(rating["score"])
if "vector" in rating:
current_vuln_vector = rating["vector"]
if "source" in rating:
if "name" in rating["source"]:
current_vuln_source = rating["source"]["name"]
elif "score" in rating:
current_vuln_severity = get_severity_by_score(rating["score"])
current_vuln_score = float(rating["score"])
if "vector" in rating:
current_vuln_vector = rating["vector"]
if "source" in rating:
if "name" in rating["source"]:
current_vuln_source = rating["source"]["name"]
if get_preferred_vuln_source(vuln_source, current_vuln_source) == current_vuln_source.upper():
vuln_severity = current_vuln_severity
vuln_score = current_vuln_score
vuln_vector = current_vuln_vector
vuln_source = current_vuln_source
if vuln_severity is None:
if "ratings" not in vulnerability:
custom_print(f"WARNING: vulnerability with id '{vulnerability['id']}' does not have a 'ratings' field. I'll set a default 'INFORMATION' severity...")
vuln_severity = get_severity_by_score(0)
elif len(vulnerability["ratings"]) == 0:
custom_print(f"WARNING: vulnerability with id '{vulnerability['id']}' does have an empty 'ratings' field. I'll set a default 'INFORMATION' severity...")
vuln_severity = get_severity_by_score(0)
else:
for rating in vulnerability["ratings"]:
if "severity" in rating:
rating_vuln_severity = rating["severity"]
if rating_vuln_severity.lower() in VALID_SEVERITIES:
vuln_severity = rating_vuln_severity.lower()
if "score" in rating:
vuln_score = float(rating["score"])
if "vector" in rating:
vuln_vector = rating["vector"]
break
if "score" in rating:
vuln_severity = get_severity_by_score(rating["score"])
vuln_score = float(rating["score"])
if "vector" in rating:
vuln_vector = rating["vector"]
break
if vuln_severity is None:
custom_print(f"WARNING: could not detect severity of vulnerability with id '{vulnerability['id']}'. I'll set a default 'INFORMATION' severity...")
vuln_severity = get_severity_by_score(0)
return vuln_id, vuln_severity, vuln_score, vuln_vector
bom_ref_cache = {}
def get_bom_ref(component_json, all_bom_refs):
global bom_ref_cache
if "bom-ref" in component_json:
bom_ref = component_json["bom-ref"]
return bom_ref
else:
if 'version' not in component_json:
component_json['version'] = ""
bom_ref_cache_key = f"{component_json['name']} - {component_json['version']}"
if bom_ref_cache_key in bom_ref_cache:
return bom_ref_cache[f"{component_json['name']} - {component_json['version']}"]
custom_print(f"WARNING: component with name '{component_json['name']}' and version '{component_json['version']}' does not have a 'bom-ref'. I'll search for a match...")
for potential_bom_ref in all_bom_refs:
guessed_name_01 = f'{component_json["name"]}@{component_json["version"]}'
guessed_name_02 = f'{component_json["name"]}::{component_json["version"]}'
guessed_name_03 = f'{component_json["name"]}:{component_json["version"]}'
for test in [guessed_name_01, guessed_name_02, guessed_name_03]:
if potential_bom_ref.endswith(f"/{test}"):
custom_print(f"Match found: {potential_bom_ref}")
bom_ref_cache[bom_ref_cache_key] = potential_bom_ref
return potential_bom_ref
if potential_bom_ref.endswith(f"/{test}:"):
custom_print(f"Match found: {potential_bom_ref}")
bom_ref_cache[bom_ref_cache_key] = potential_bom_ref
return potential_bom_ref
if potential_bom_ref.endswith(f":{test}"):
bom_ref_cache[bom_ref_cache_key] = potential_bom_ref
custom_print(f"Match found: {potential_bom_ref}")
return potential_bom_ref
if potential_bom_ref.endswith(f":{test}:"):
bom_ref_cache[bom_ref_cache_key] = potential_bom_ref
custom_print(f"Match found: {potential_bom_ref}")
return potential_bom_ref
# another try with version not in the end of the string
number_of_results = 0
result = None
for potential_bom_ref in all_bom_refs:
guessed_name_01 = f'{component_json["name"]}@{component_json["version"]}'
guessed_name_02 = f'{component_json["name"]}::{component_json["version"]}'
guessed_name_03 = f'{component_json["name"]}:{component_json["version"]}'
for test in [guessed_name_01, guessed_name_02, guessed_name_03]:
if f"/{test}:" in potential_bom_ref:
number_of_results += 1
result = potential_bom_ref
elif f":{test}:" in potential_bom_ref:
number_of_results += 1
result = potential_bom_ref
if number_of_results == 1: # I want just one result, otherwise it means the sbom is ambiguous and I can't make any educated guess
bom_ref_cache[bom_ref_cache_key] = result
return result
custom_print(f"Match not found. I'll create a fake one.")
bom_ref = f"{hash(json.dumps(component_json, sort_keys=True, cls=SetEncoder))}"
bom_ref_cache[bom_ref_cache_key] = bom_ref
return bom_ref
def create_or_update_bom_ref_entry(bom_refs, component):
if component["bom-ref"] not in bom_refs:
bom_refs[component["bom-ref"]] = {"name": component["name"] if "name" in component else "-",
"version": component["version"] if "version" in component else "-"}
else:
if bom_refs[component["bom-ref"]]["name"] == "-" and "name" in component:
bom_refs[component["bom-ref"]]["name"] = component["name"]
if bom_refs[component["bom-ref"]]["version"] == "-" and "version" in component:
bom_refs[component["bom-ref"]]["version"] = component["version"]
def normalize_bom_ref(bom_refs, bom_ref, only_valid_components=True):
for component_bom_ref, component_data in bom_refs.items():
if only_valid_components is False:
if bom_ref == component_bom_ref:
return bom_ref
else:
if bom_ref == component_bom_ref and component_data["name"] != "-" and component_data["version"] != "-":
return bom_ref
for component_bom_ref, component_data in bom_refs.items():
# look with version
guessed_name_01 = f'{component_data["name"]}@{component_data["version"]}'
guessed_name_02 = f'{component_data["name"]}::{component_data["version"]}'
guessed_name_03 = f'{component_data["name"]}:{component_data["version"]}'
for test in [guessed_name_01, guessed_name_02, guessed_name_03]:
if bom_ref.endswith(f"/{test}"):
return bom_ref
if bom_ref.endswith(f"/{test}:"):
return bom_ref
if bom_ref.endswith(f":{test}"):
return bom_ref
if bom_ref.endswith(f":{test}:"):
return bom_ref
# another try with version not in the end of the string
number_of_results = 0
result = None
for component_bom_ref, component_data in bom_refs.items():
guessed_name_01 = f'{component_data["name"]}@{component_data["version"]}'
guessed_name_02 = f'{component_data["name"]}::{component_data["version"]}'
guessed_name_03 = f'{component_data["name"]}:{component_data["version"]}'
for test in [guessed_name_01, guessed_name_02, guessed_name_03]:
if f"/{test}:" in bom_ref:
number_of_results += 1
result = component_bom_ref
elif f":{test}:" in bom_ref: