-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdetect_rescan.sh
1584 lines (1483 loc) · 50.1 KB
/
detect_rescan.sh
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
#!/bin/bash
# Script to wrapper detect.sh to only upload changed bom files
#
# Description:
# 1. Processes supplied Synpsys Detect options to determine if a post-action is required
# 2. Downloads and runs Detect (detect.sh) offline with supplied options to perform a scan
# 3. Identifies the BOM and Signature scan files from offline run (note the script should only be used for projects where 1 signature scan has been mapped)
# 4. Looks for previous scan data (see below for location of this data)
# 5. Compares scanned BOM files and upload files if different/new to previous scan
# 6. Checks last date/time for signature scan and uploads if more than specified period (24 hours by default) or new scan
# 7. If post-action or report required:
# - Waits for server-side scan and BOM completion
# - Runs Detect to perform post-action with no rescan
# 8. If --report or --markdown specified, produce summary reports (--markdown writes the file blackduck.md in MD format)
#
# Arguments:
# --quiet - Hide Synopsys Detect standard output and other non-essential script notifications.
# --report - Use to extract summary values after the scan completions including number of policy violations and counts of component vulnerability, license and operational risks identified.
# --markdown - Write a project summary report to the blackduck.md file created in the project folder.
# --reset - Force a scan irrespective of the previous scan data/time and then update the scan data.
# --testxml - Produce output vulns.xml and policies.xml files containing test results in Junit format.
# --curlopts - Add an option to curl (usually -k) to support insecure connections to a BD server without authorised certificate (alternatively set CURLOPTS env var)
# --detectscript=mydetect.sh
# - Use a local specified copy of the detect.sh script as opposed to downloading dynamically from https://detect.synopsys.com/detect.sh.
# --sigtime=XXXX - Specify the time (in seconds) used to determine whether a Signature scan should be uploaded (default 86400 = 24 hours).# Same as detect.sh
#
output() {
echo "detect_rescan: $*"
}
output "Starting Detect Rescan wrapper v1.22"
DETECT_TMP=$(mktemp -u)
TEMPFILE=$(mktemp -u)
TEMPFILE2=$(mktemp -u)
LOGFILE=$(mktemp -u)
# ACTION_ARGS=--blackduck.timeout=*|--detect.force.success=*|--detect.notices.report=*|--detect.policy.check.fail.on.severities=*|--detect.risk.report.pdf=*|--detect.wait.for.results=*
# UNSUPPORTED_ARGS='--detect.blackduck.signature.scanner.snippet.matching=*|--detect.blackduck.signature.scanner.upload.source.mode=*|--detect.blackduck.signature.scanner.copyright.search=*|--detect.blackduck.signature.scanner.license.search=*|--detect.binary.scan.*'
API_TOKEN=$BLACKDUCK_API_TOKEN
BD_URL=$BLACKDUCK_URL
YML=
DETARGS=
SCANLOC=.
RUNDIR=
PROJECT=
VERSION=
SIGFOLDER=
DETECT_ACTION=0
DETECT_PROJECT=0
DETECT_VERSION=0
MODE_QUIET=0
MODE_REPORT=0
MODE_PREVFILE=0
MODE_TESTXML=0
SIGTIME=86400
DETECT_TIMEOUT=4800
POLLTIME=30
PREVSCANDATA=
PROJEXISTS=0
DETECT_SCRIPT=
MODE_RESET=0
JQTEMPDIR=
JQ=
COLUMN=column
UNSUPPORTED=0
BOM_FILES=()
BOM_HASHES=()
PREV_FILES=()
PREV_HASHES=()
UNMATCHED_BOMS=()
error() {
echo "detect_rescan: ERROR: $*" >$LOGFILE
cat $LOGFILE
end 1
}
error2() {
echo "detect_rescan: ERROR: $*" >$LOGFILE
cat $LOGFILE
end 2
}
end() {
rm -f $TEMPFILE $TEMPFILE2 $DETECT_TMP $LOGFILE
if [ ! -z "$JQTEMPDIR" ]
then
rm -f $JQTEMPDIR/jq
rmdir $JQTEMPDIR
fi
exit $1
}
debug() {
if [ ! -z "$DEBUG" ]
then
echo "detect_rescan: DEBUG - $*" >&2
fi
}
msg() {
if [ $MODE_QUIET -eq 0 ]
then
output "$*"
fi
}
encode_url() {
if [ ! -z "$1" ]
then
echo ${*} | sed -e 's:/:%2F:g' -e 's/ /%20/g' -e 's/\[/%5B/g' -e 's/\]/%5D/g' -e 's/{/%7B/g' -e 's/}/%7D/g' -e 's/(/%28/g' -e 's/)/%29/g' -e 's/"//g'
else
cat - | sed -e 's:/:%2F:g' -e 's/ /%20/g' -e 's/\[/%5B/g' -e 's/\]/%5D/g' -e 's/{/%7B/g' -e 's/}/%7D/g' -e 's/(/%28/g' -e 's/)/%29/g' -e 's/\"//g'
fi
}
escape_string() {
if [ ! -z "$1" ]
then
echo ${*} | sed -e 's/ /\\ /g' -e 's/"//g'
else
cat - | sed -e 's/ /\\ /g' -e 's/"//g'
fi
}
install_jq() {
JQPATH=$(mktemp -d)
PLATFORM=$(uname -a 2>/dev/null| cut -f1 -d' ')
debug "install_jq(): PLATFORM = $PLATFORM"
if [ "$PLATFORM" == "Linux" ]
then
JQURL=https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64
elif [ "$PLATFORM" == "Darwin" ]
then
JQURL=https://github.com/stedolan/jq/releases/download/jq-1.6/jq-osx-amd64
else
return 1
fi
curl -s -L $JQURL -o $JQPATH/jq >/dev/null 2>&1
if [ $? -ne 0 ] || [ ! -r $JQPATH/jq ]
then
return 1
fi
chmod +x $JQPATH/jq
echo $JQPATH/jq
debug "install_jq(): jq downloaded from $JQURL and installed to $JQPATH/jq"
JQTEMPDIR=$JQPATH
return 0
}
prereqs() {
local ret=0
hash jq >/dev/null 2>&1
if [ $? -ne 0 ]
then
JQ=$(install_jq)
if [ $? -ne 0 ]
then
output "ERROR: jq not available and unable to install"
ret=1
fi
else
JQ=jq
fi
debug "prereqs(): JQ set to $JQ"
for prog in cksum curl java
do
hash $prog >/dev/null 2>&1
if [ $? -ne 0 ]
then
output "ERROR: $prog program required"
ret=1
fi
done
hash $COLUMN >/dev/null 2>&1
if [ $? -ne 0 ]
then
COLUMN=''
debug "prereqs(): column program missing"
fi
debug "prereqs(): Returning $ret"
return $ret
}
check_env() {
#
# Check Environment variables
if [ "$DETECT_BLACKDUCK_SIGNATURE_SCANNER_SNIPPET_MATCHING" == "true" ]
then
debug "process_args(): UNSUPPORTED OPTION detect.blackduck.signature.scanner.snippet.matching option identified from environment variable"
UNSUPPORTED=1
fi
if [ "$DETECT_BLACKDUCK_SIGNATURE_SCANNER_UPLOAD_SOURCE_MODE" == "true" ]
then
debug "process_args(): UNSUPPORTED OPTION detect.blackduck.signature.scanner.upload.source.mode option identified from environment variable"
UNSUPPORTED=1
fi
if [ "$DETECT_BLACKDUCK_SIGNATURE_SCANNER_COPYRIGHT_SEARCH" == "true" ]
then
debug "process_args(): UNSUPPORTED OPTION detect.blackduck.signature.scanner.copyright.search option identified from environment variable"
UNSUPPORTED=1
fi
if [ "$DETECT_BLACKDUCK_SIGNATURE_SCANNER_LICENSE_SEARCH" == "true" ]
then
debug "process_args(): UNSUPPORTED OPTION detect.blackduck.signature.scanner.license.search option identified from environment variable"
UNSUPPORTED=1
fi
if [ ! -z "$DETECT_BINARY_SCAN_FILE_PATH" ]
then
debug "process_args(): UNSUPPORTED OPTION detect.binary.scan.file.path identified from environment variable"
UNSUPPORTED=1
fi
if [ ! -z "$DETECT_BINARY_SCAN_FILE_NAME_PATTERNS" ]
then
debug "process_args(): UNSUPPORTED OPTION detect.binary.scan.file.name.patterns identified from environment variable"
UNSUPPORTED=1
fi
if [ ! -z "$DETECT_SOURCE_PATH" ] && [ -d "$DETECT_SOURCE_PATH" ]
then
debug "process_args(): detect.source.path '$DETECT_SOURCE_PATH' identified from environment variable"
SCANLOC=$(cd "$DETECT_SOURCE_PATH"; pwd)
fi
#
# Check YML properties file
if [ ! -z "$YML" ]
then
debug "process_args(): YML file $YML identified"
local API=$(grep '^blackduck.api.token:' $YML| cut -f2 -d' ')
if [ ! -z "API" ]
then
API_TOKEN=$API
debug "process_args(): BLACKDUCK_API_TOKEN identified from $YML file"
fi
local URL=$(grep '^blackduck.url:' $YML | cut -f2 -d' ')
if [ ! -z "URL" ]
then
BD_URL=$URL
debug "process_args(): BLACKDUCK_URL identified from $YML file"
fi
local RES=$(grep '^detect.blackduck.signature.scanner.snippet.matching:' $YML| cut -f2 -d' ')
if [ "$RES" == "true" ]
then
debug "process_args(): UNSUPPORTED OPTION detect.blackduck.signature.scanner.snippet.matching option identified from $YML"
UNSUPPORTED=1
fi
local RES=$(grep '^detect.blackduck.signature.scanner.upload.source.mode:' $YML| cut -f2 -d' ')
if [ "$RES" == "true" ]
then
debug "process_args(): UNSUPPORTED OPTION detect.blackduck.signature.scanner.upload.source.mode option identified from $YML"
UNSUPPORTED=1
fi
local RES=$(grep '^detect.blackduck.signature.scanner.copyright.search:' $YML| cut -f2 -d' ')
if [ "$RES" == "true" ]
then
debug "process_args(): UNSUPPORTED OPTION detect.blackduck.signature.scanner.copyright.search option identified from $YML"
UNSUPPORTED=1
fi
local RES=$(grep '^detect.blackduck.signature.scanner.license.search:' $YML| cut -f2 -d' ')
if [ "$RES" == "true" ]
then
debug "process_args(): UNSUPPORTED OPTION detect.blackduck.signature.scanner.license.search option identified from $YML"
UNSUPPORTED=1
fi
local RES=$(grep '^detect.binary.scan.' $YML| cut -f2 -d' ')
if [ "$RES" == "true" ]
then
debug "process_args(): UNSUPPORTED OPTION detect.binary.scan.* identified from $YML"
UNSUPPORTED=1
fi
local RES=$(grep '^detect.source.path:' $YML| cut -f2 -d' ' | sed -e 's/"//g' -e "s/'//g")
if [ ! -z "$RES" ] && [ -d "$RES" ]
then
debug "process_args(): detect.source.path '$RES' identified from $YML"
SCANLOC=$(cd "$RES"; pwd)
fi
fi
if [ $UNSUPPORTED -eq 1 ]
then
error "Unsupported Detect options specified (Snippet or Binary)"
fi
}
get_token() {
rm -f $TEMPFILE
curl $CURLOPTS -s -X POST --header "Authorization: token ${API_TOKEN}" --header "Accept:application/json" ${BD_URL}/api/tokens/authenticate >$TEMPFILE 2>/dev/null
if [ $? -ne 0 ] || [ ! -r "$TEMPFILE" ]
then
error "Cannot obtain auth token from BD Server"
fi
local TOKEN=$($JQ -r '.bearerToken' $TEMPFILE 2>/dev/null)
if [ -z "$TOKEN" ]
then
error "Cannot obtain auth token from BD Server"
fi
debug "get_token(): Auth token obtained correctly"
echo $TOKEN
}
run_detect_offline() {
if [ -z "$DETECT_SCRIPT" ]
then
curl $CURLOPTS -s -L https://detect.synopsys.com/detect.sh > $DETECT_TMP 2>/dev/null
if [ ! -r $DETECT_TMP ]
then
error "Unable to download detect.sh from https://detect.synopsys.com - use --detect=PATH_TO_DETECT.sh"
fi
chmod +x $DETECT_TMP
DETECT_SCRIPT=$DETECT_TMP
debug "run_detect_offline(): Detect script downloaded to $DETECT_SCRIPT"
else
debug "run_detect_offline(): Detect script $DETECT_SCRIPT will be used"
fi
rm -f $TEMPFILE
if [ $MODE_QUIET -eq 0 ]
then
$DETECT_SCRIPT $DETARGS --detect.blackduck.signature.scanner.host.url=${BD_URL} --blackduck.offline.mode=true 2>/dev/null | tee $TEMPFILE
RET=${PIPESTATUS[0]}
else
output "Running Detect offline ..."
$DETECT_SCRIPT $DETARGS --detect.blackduck.signature.scanner.host.url=${BD_URL} --blackduck.offline.mode=true 2>/dev/null >$TEMPFILE
RET=$?
cat $TEMPFILE >>$LOGFILE
fi
if [ $RET -ne 0 ]
then
debug "run_detect_offline(): Detect returned code $RET"
return $RET
fi
if [ ! -r $TEMPFILE ]
then
return 1
fi
RUNDIR=$(grep 'Run directory: ' $TEMPFILE | sed -e 's/^.*Run directory: //g')
PROJECT=$(grep 'Project name: ' $TEMPFILE | sed -e 's/^.*Project name: //g')
VERSION=$(grep 'Project version: ' $TEMPFILE | sed -e 's/^.*Project version: //g')
if [ -z "$RUNDIR" -o ! -d "$RUNDIR" -o ! -d "$RUNDIR/bdio" -o -z "$PROJECT" -o -z "$VERSION" ]
then
return 1
fi
debug "run_detect_offline(): PROJECT=$PROJECT VERSION=$VERSION RUNDIR=$RUNDIR"
SIGRUN=$(grep -c 'Starting the Black Duck Signature Scan' $TEMPFILE)
if [ $SIGRUN -gt 0 ]
then
SIGFOLDER=$(grep 'You can view the logs at: ' $TEMPFILE | sed -e 's/^.*You can view the logs at: //g' -e "s/'//g")
fi
debug "run_detect_offline(): SIGFOLDER=$SIGFOLDER"
return 0
}
proc_bom_files() {
local CWD=$(pwd)
cd "$RUNDIR"
if [ ! -d bdio ]
then
debug "proc_bom_files(): $RUNDIR/bdio does not exist"
cd "$CWD"
return 1
fi
cd bdio
local COUNT=0
for bom in *.jsonld
do
if [ ! -r "$bom" ]
then
cd "$CWD"
return 1
fi
CKSUM=$(cat $bom | grep -v 'spdx:created' | grep -v 'uuid:' | sort | cksum | cut -f1 -d' ')
FILE=$(basename $bom)
debug "proc_bom_files(): Checksum for '$FILE' is '$CKSUM'"
BOM_FILES+=("${FILE}")
BOM_HASHES+=("${CKSUM}")
((COUNT++))
done
debug "proc_bom_files(): Processed $COUNT .jsonld files"
cd "$CWD"
return 0
}
proc_prev_bom_data() {
if [ ! -z "$PREVSCANDATA" ]
then
local COUNT=0
IFS='|'
for item in $PREVSCANDATA
do
if [[ $item == VER:* ]]
then
PREV_PROJ=$(echo $item|cut -f2 -d:)
PREV_VER=$(echo $item|cut -f3 -d:)
if [ "$PROJECT" != "$PREV_PROJ" -o "$VERSION" != "$PREV_VER" ]
then
break
fi
elif [[ $item == BOM:* ]]
then
PREV_FILES+=($(echo $item|cut -f2 -d:))
PREV_HASHES+=($(echo $item|cut -f3 -d:))
((COUNT++))
fi
done
IFS=
debug "proc_prev_bom_data(): Found $COUNT BOM entries in previous scan data"
fi
}
compare_boms() {
local COUNT=0
for index in ${!BOM_FILES[@]}
do
MATCHED=0
for previndex in ${!PREV_FILES[@]}
do
if [ "${BOM_FILES[$index]}" == "${PREV_FILES[$previndex]}" ]
then
if [ "${BOM_HASHES[$index]}" == "${PREV_HASHES[$previndex]}" ]
then
MATCHED=1
fi
fi
done
if [ $MATCHED -eq 0 ] || [ $MODE_RESET -eq 1 ]
then
UNMATCHED_BOMS+=($index)
fi
((COUNT++))
done
debug "compare_boms(): $COUNT bomfiles processed, MATCHED=$MATCHED"
}
upload_boms() {
echo -n "detect_rescan: BOM files - Uploading ${#UNMATCHED_BOMS[@]} out of ${#BOM_FILES[@]} total ..."
local UPLOADED=0
local FAILED=0
for index in ${UNMATCHED_BOMS[@]}
do
echo -n '.'
curl $CURLOPTS -s -X POST "${BD_URL}/api/scan/data/?mode=replace" \
-H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/vnd.blackducksoftware.bdio+json' \
-H 'cache-control: no-cache' \
--data-binary "@$RUNDIR/bdio/${BOM_FILES[$index]}" >/dev/null 2>&1
if [ $? -eq 0 ]
then
((UPLOADED++))
else
debug "upload_boms(): Upload failed for $RUNDIR/bdio/${BOM_FILES[$index]}"
((FAILED++))
fi
done
echo
msg "$UPLOADED Modified/New Bom Files Uploaded successfully ($FAILED Failed)"
if [ $FAILED -gt 0 ]
then
return 1
fi
return 0
}
run_detect_action() {
output "Rerunning Detect to execute post-scan action"
if [ $DETECT_PROJECT -eq 0 ]
then
DETARGS="$DETARGS '--detect.project.name=$PROJECT'"
fi
if [ $DETECT_VERSION -eq 0 ]
then
DETARGS="$DETARGS '--detect.project.version.name=$VERSION'"
fi
debug "run_detect_action(): Will call Detect with options $DETARGS --detect.tools=NONE"
if [ $MODE_QUIET -eq 0 ]
then
$DETECT_SCRIPT $DETARGS --detect.tools=NONE
RET=$?
else
$DETECT_SCRIPT $DETARGS --detect.tools=NONE >>$LOGFILE
RET=$?
fi
debug "run_detect_action(): Return code $RET"
return $RET
}
api_call() {
if [ -z "$2" ]
then
HEADER="application/json"
else
HEADER="$2"
fi
rm -f $TEMPFILE
debug "api_call(): API call is $1"
curl $CURLOPTS -s -X GET --header "Authorization: Bearer $TOKEN" "$1" 2>/dev/null >$TEMPFILE
RET=$?
if [ $RET -ne 0 ] || [ ! -r $TEMPFILE ]
then
echo "detect_rescan: ERROR: API Error - Curl returned $RET" >&2
debug "api_call(): API call failed: curl -s -X GET --header 'Authorization: Bearer $TOKEN' $1"
return 1
fi
if [ $(grep -c 'failed authorization' $TEMPFILE) -gt 0 ]
then
echo "detect_rescan: ERROR: Server or Project Authorization issue" >&2
return 1
fi
if [ $(grep -c errorCode $TEMPFILE) -gt 0 ]
then
echo "detect_rescan: ERROR: Other API error $($JQ '.errorCode' $TEMPFILE 2>/dev/null)" >&2
return 1
fi
if [ $(grep -c totalCount $TEMPFILE) -gt 0 ]
then
COUNT=$($JQ -r '.totalCount' $TEMPFILE 2>/dev/null)
if [ -z "$COUNT" ]
then
debug "api_call(): totalCount field not found in API response - returning False"
return 1
fi
fi
# $JQ . $TEMPFILE >&2
#debug "api_call(): $COUNT records identified in API response"
return 0
}
get_project() {
#Get projects $1=projectname
debug "get_project(): ARG1=$1"
#local SEARCHPROJ=$(echo ${1} | sed -e 's:/:%2F:g' -e 's/ /+/g')
local SEARCHPROJ=$(encode_url ${1})
local MYURL="${BD_URL}/api/projects?q=name:${SEARCHPROJ}&limit=200"
debug "get_project(): API_URL=$MYURL"
api_call "$MYURL" 'application/vnd.blackducksoftware.project-detail-4+json'
if [ $? -ne 0 ]
then
debug "get_project(): API error - returning early"
return 1
fi
local PROJNAMES=$($JQ -r '[.items[].name]|@csv' $TEMPFILE 2>/dev/null| encode_url )
local PROJURLS=$($JQ -r '[.items[]._meta.href]|@csv' $TEMPFILE 2>/dev/null| sed -e 's/\"//g' )
debug "get_project(): PROJNAMES=$PROJNAMES"
debug "get_project(): PROJURLS=$PROJURLS"
local PROJNUM=1
local FOUNDNUM=0
local IFS=,
for PROJ in $PROJNAMES
do
debug "get_project(): PROJ='$PROJ' SEARCHPROJ='$SEARCHPROJ'"
if [ "$PROJ" == "$SEARCHPROJ" ]
then
FOUNDNUM=$PROJNUM
break
fi
((PROJNUM++))
done
IFS=
debug "get_project(): Found $FOUNDNUM projects"
if [ $FOUNDNUM -eq 0 ]
then
return 0
fi
debug "get_project(): PROJURLS is '$PROJURLS'"
RETURL=$(echo $PROJURLS | cut -f $FOUNDNUM -d ,)
debug "get_project(): returning project URL $RETURL"
echo $RETURL
return 0
}
get_version() {
# Get Version - $1 = PROJURL
local VERNAME=$(encode_url ${2} )
local API_URL="${1//\"}/versions?versionName%3A${VERNAME}&limit=200"
debug "get_version(): version URL is '$API_URL'"
#local SEARCHVERSION="${2// /_}"
#echo "get_version: SEARCHVERSION=$SEARCHVERSION" >&2
api_call "${API_URL}" 'application/vnd.blackducksoftware.project-detail-4+json'
if [ $? -ne 0 ]
then
debug "get_version(): API error"
return 1
fi
local VERNAMES=$($JQ -r '[.items[].versionName]|@csv' $TEMPFILE 2>/dev/null | encode_url )
local VERURLS=$($JQ -r '[.items[]._meta.href]|@csv' $TEMPFILE 2>/dev/null | sed -e 's/\"//g' )
debug "get_version(): VERNAMES=$VERNAMES"
debug "get_version(): VERURLS=$VERURLS"
local VERNUM=1
local FOUNDVERNUM=0
local IFS=,
for NAME in $VERNAMES
do
#echo "get_version: NAME=$NAME" >&2
if [ "$NAME" == "$VERNAME" ]
then
FOUNDVERNUM=$VERNUM
break
fi
((VERNUM++))
done
IFS=
if [ $FOUNDVERNUM -eq 0 ]
then
debug "get_version(): 0 versions found from project"
return 0
fi
RETURL=$(echo $VERURLS | cut -f $FOUNDVERNUM -d ,)
debug "get_version(): returning version URL $RETURL"
echo $RETURL
return 0
}
get_projver() {
# $1=projectname $2=versionname $3=number_of_10_sec_loops
debug "get_projver(): ARG1=$1 ARG2=$2 ARG3=$3"
local NUMLOOPS=${3:-0}
local COUNT=0
while [ $COUNT -le $NUMLOOPS ]
do
debug "get_projver(): Loop $COUNT"
PURL=$(get_project "$1")
if [ $? -ne 0 ]
then
return 1
fi
debug "get_projver(): PURL=$PURL"
if [ ! -z "$PURL" ]
then
VURL=$(get_version "$PURL" "$2")
if [ $? -ne 0 ]
then
return 1
fi
debug "get_projver(): VURL=$VURL"
fi
((COUNT++))
if [ -z "$VURL" ]
then
sleep 10
else
break
fi
done
echo $VURL
debug "get_projver(): Returning version URL $VURL"
return 0
}
get_user() {
debug "get_user(): Getting user"
api_call "${BD_URL}/api/current-user" "application/vnd.blackducksoftware.user-4+json"
if [ $? -ne 0 ]
then
debug "get_user(): api_call() returned failure"
return ''
fi
# ${JQ} . $TEMPFILE >&2
local USERURL=$($JQ -r '._meta.href' $TEMPFILE 2>/dev/null)
debug "get_user(): User URL is ${USERURL//\"}"
echo ${USERURL//\"}
}
wait_for_bom_completion() {
# $1 is versionURL
local VERURL=$1
local USERURL=$(get_user)
debug "wait_for_bom_completion(): User URL is '$USERURL'"
if [ -z "$USERURL" -o "$USERURL" == '' ]
then
return 0
fi
# Check BOM status
# https://poc39.blackduck.synopsys.com/api/users/1735454c-0fcd-431d-ab6e-38ce189acb0e/notifications?
# filter=notificationType%3AVERSION_BOM_CODE_LOCATION_BOM_COMPUTED&limit=100&offset=0&endDate=2021-06-20T15%3A47%3A52.414Z&startDate=2021-06-17T15%3A45%3A30.573Z
local APIURL="${USERURL}/notifications"
APIURL="${APIURL}?filter=notificationType%3AVERSION_BOM_CODE_LOCATION_BOM_COMPUTED&limit=100&offset=0"
local loop=1
debug "wait_for_bom_completion(): Will poll for maximum $DETECT_TIMEOUT seconds"
local LOOPTIME=0
local CURPOLLTIME=$POLLTIME
local CURDATE=$STARTDATE
local BOMCOMPLETE=false
while [ $LOOPTIME -le "$DETECT_TIMEOUT" ]
do
debug "wait_for_bom_completion(): Waiting loop $loop - wait $CURPOLLTIME seconds"
PREVDATE=$CURDATE
CURDATE=$(date -u '+%Y-%m-%dT%H%%3A%M%%3A%S.000Z')
api_call "${APIURL}&endDate=${CURDATE}&startDate=${STARTDATE}" 'application/vnd.blackducksoftware.notification-4+json'
if [ $? -ne 0 ]
then
debug "wait_for_bom_completion(): api_call() returned failure"
return 1
fi
local COUNT=$($JQ -r '.totalCount' $TEMPFILE 2>/dev/null)
# $JQ . $TEMPFILE
if [ -n "$COUNT" ] && [ "$COUNT" -gt 0 ]
then
local IFS=,
for url in $($JQ -r '[.items[].content.projectVersion]|@csv' $TEMPFILE 2>/dev/null)
do
if [ "${url//\"}" == "$VERURL" ]
then
unset IFS
debug "wait_for_bom_completion(): bomcompletion event found"
echo
return 0
fi
done
unset IFS
fi
echo -n '.'
sleep $CURPOLLTIME
let "CURPOLLTIME = CURPOLLTIME + CURPOLLTIME"
let "NEWLOOPTIME = LOOPTIME + CURPOLLTIME"
if [ $LOOPTIME -ge $DETECT_TIMEOUT ]
then
break
elif [ $NEWLOOPTIME -gt $DETECT_TIMEOUT ]
then
let "CURPOLLTIME = DETECT_TIMEOUT - LOOPTIME"
LOOPTIME=$DETECT_TIMEOUT
else
LOOPTIME=$NEWLOOPTIME
fi
((loop++))
done
echo
return 1
}
wait_for_scans() {
local SCANURL=$(echo ${1//\"}| sed -e 's/ /%20/g')
local loop=1
# local LOOPS=$(( DETECT_TIMEOUT / POLLTIME ))
debug "wait_for_scans(): Will poll for maximum $DETECT_TIMEOUT seconds"
local LOOPTIME=0
local CURPOLLTIME=$POLLTIME
# while [ $loop -lt "$LOOPS" ]
while [ $LOOPTIME -le "$DETECT_TIMEOUT" ]
do
# Check scan status
debug "wait_for_scans(): Waiting loop $loop - wait $CURPOLLTIME seconds"
api_call "${SCANURL}" 'application/vnd.blackducksoftware.scan-4+json'
if [ $? -ne 0 ]
then
debug "wait_for_scans(): api_call() returned failure"
return 1
fi
local STATUSES=$($JQ -r '[.items[].status[].status]|@csv' $TEMPFILE 2>/dev/null)
local OPCODES=$($JQ -r '[.items[].status[].operationNameCode]|@csv' $TEMPFILE 2>/dev/null)
local DONE=1
local index=1
local IFS=,
for stat in $STATUSES
do
debug "wait_for_scans(): STATUS is $stat"
IFS=
OPCODE=$(echo $OPCODES | cut -f$index -d,)
((index++))
if [ $OPCODE != '"ServerScanning"' ]
then
continue
fi
if [ $stat != '"COMPLETED"' ]
then
DONE=0
fi
done
if [ $DONE -eq 1 ]
then
debug "wait_for_scans(): ServerScanning field marked as COMPLETED"
return 0
fi
echo -n '.'
sleep $CURPOLLTIME
let "CURPOLLTIME = CURPOLLTIME + CURPOLLTIME"
let "NEWLOOPTIME = LOOPTIME + CURPOLLTIME"
if [ $LOOPTIME -ge $DETECT_TIMEOUT ]
then
break
elif [ $NEWLOOPTIME -gt $DETECT_TIMEOUT ]
then
let "CURPOLLTIME = DETECT_TIMEOUT - LOOPTIME"
LOOPTIME=$DETECT_TIMEOUT
else
LOOPTIME=$NEWLOOPTIME
fi
((loop++))
done
return 1
}
check_sigscan() {
local DIFFTIME=$1
local NOWDATE=$(date '+%Y%m%d%H%M%S')
local SIGDATE=$NOWDATE
local PROCSIGSCAN=0
if [ $MODE_RESET -eq 1 ]
then
echo $NOWDATE
return 1
fi
local PREV_SIGSCAN_DATE=
local IFS='|'
for item in $PREVSCANDATA
do
if [[ $item == VER:* ]]
then
local PREV_PROJ=$(echo $item|cut -f2 -d:)
local PREV_VER=$(echo $item|cut -f3 -d:)
if [ "$PROJECT" != "$PREV_PROJ" -o "$VERSION" != "$PREV_VER" ]
then
break
fi
fi
if [[ $item == SIG:* ]]
then
PREV_SIGSCAN_DATE=$(echo $item|cut -f2 -d:)
debug "check_sigscan(): PREV_SIGSCAN_DATE=$PREV_SIGSCAN_DATE NOW=$NOWDATE"
fi
done
IFS=
if [ ! -z "$PREV_SIGSCAN_DATE" ] && [ "$PREV_SIGSCAN_DATE" -gt 0 ]
then
DIFF=$((NOWDATE-PREV_SIGSCAN_DATE))
if [ $DIFF -gt $DIFFTIME ]
then
PROCSIGSCAN=1
else
SIGDATE=$PREV_SIGSCAN_DATE
fi
else
PROCSIGSCAN=1
fi
debug "check_sigscan(): Return value PROCSIGSCAN=$PROCSIGSCAN"
echo $SIGDATE
return $PROCSIGSCAN
}
proc_sigscan() {
local CWD=$(pwd)
cd "$SIGFOLDER"
if [ ! -d data ]
then
debug "proc_sigscan(): $SIGFOLDER/data does not exist"
cd "$CWD"
return 0 #No Sig scan
fi
cd data
for sig in *.json
do
if [ ! -r "$sig" ]
then
debug "proc_sigscan(): No sig scan found"
cd "$CWD"
return 1 # No sig scan
fi
debug "proc_sigscan(): Processing sig scan file $SIGFOLDER/data/$sig"
#output "Signature Scan - Uploading ..."
curl $CURLOPTS -s -X POST "${BD_URL}/api/scan/data/?mode=replace" \
-H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/ld+json' \
-H 'cache-control: no-cache' \
--data-binary "@$sig" >/dev/null 2>&1
if [ $? -eq 0 ]
then
local SIGSCANNAME=$($JQ '.name' "$sig")
if [ ! -z "$SIGSCANNAME" ]
then
echo $SIGSCANNAME
debug "proc_sigscan(): Signature code location name = $SIGSCANNAME"
cd "$CWD"
return 0
fi
fi
debug "proc_sigscan(): Returning error as no code location name found in sigscan file"
cd "$CWD"
return 1 # Unable to upload sig scan
done
cd "$CWD"
debug "proc_sigscan(): No sig scan found"
return 0 # No sig scan
}
cleanup() {
if [ -z "$DEBUG" ]
then
if [ ! -z "$RUNDIR" ]
then
if [ -d "$RUNDIR/bdio" ]
then
rm -rf "$RUNDIR/bdio"
msg "Deleting $RUNDIR/bdio"
fi
if [ -d "$RUNDIR/extractions" ]
then
rm -rf "$RUNDIR/extractions"
msg "Deleting $RUNDIR/extractions"
fi
if [ -d "$RUNDIR/scan" ]
then
rm -rf "$RUNDIR/scan"
msg "Deleting $RUNDIR/scan"
fi
fi
fi
}
run_report() {
local URL=$1
if [ -z "$URL" ]
then
return 1
fi
api_call "${URL}/policy-status" 'application/vnd.blackducksoftware.bill-of-materials-6+json'
if [ $? -ne 0 ]
then
return 1
fi
if [ $MODE_REPORT -eq 1 ]
then
echo
echo "----------------------------------------------------------------------"
echo BLACK DUCK OSS SUMMARY REPORT
echo "Project: '$PROJECT' Version: '$VERSION'"
echo
fi
local POL_STATUS=$($JQ -r '.overallStatus' $TEMPFILE 2>/dev/null)
if [ "$POL_STATUS" == "IN_VIOLATION" ]
then
POL_TYPES=$($JQ -r '.componentVersionStatusCounts[].name' $TEMPFILE 2>/dev/null | tr '\n' ',')
POL_STATS=$($JQ -r '.componentVersionStatusCounts[].value' $TEMPFILE 2>/dev/null | tr '\n' ',')
if [ $MODE_REPORT -eq 1 ]
then
echo Component Policy Status:
fi
local IFS=,
local INDEX=1
local COMPCOUNT=0
for type in ${POL_TYPES}
do
IFS=
POL_STAT=$(echo $POL_STATS | cut -f$INDEX -d,)
COMPCOUNT=$(($COMPCOUNT+$POL_STAT))
if [ $MODE_REPORT -eq 1 ]
then
if [ "$type" == "IN_VIOLATION_OVERRIDDEN" ]
then
echo " - In Violation Overidden: $POL_STAT"
elif [ "$type" == "NOT_IN_VIOLATION" ]
then
echo " - Not In Violation: $POL_STAT"
elif [ "$type" == "IN_VIOLATION" ]
then
echo " - In Violation: $POL_STAT"
fi
fi
((INDEX++))
done
fi
XMLPOL='policies.xml'
XMLVULN='vulns.xml'
if [ "$POL_STATUS" == "IN_VIOLATION" ] || [ $MODE_TESTXML -eq 1 ]
then
if [ $MODE_REPORT -eq 1 ]
then
echo
echo "Components in Violation:"
fi