-
-
Notifications
You must be signed in to change notification settings - Fork 171
/
Copy pathcdxgen.js
executable file
·915 lines (899 loc) · 28.2 KB
/
cdxgen.js
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
#!/usr/bin/env node
import crypto from "node:crypto";
import fs from "node:fs";
import { basename, dirname, join, resolve } from "node:path";
import process from "node:process";
import { URL } from "node:url";
import { findUpSync } from "find-up";
import globalAgent from "global-agent";
import { load as _load } from "js-yaml";
import jws from "jws";
import { createBom, submitBom } from "../lib/cli/index.js";
import {
printCallStack,
printDependencyTree,
printFormulation,
printOccurrences,
printReachables,
printServices,
printSponsorBanner,
printSummary,
printTable,
} from "../lib/helpers/display.js";
import {
ATOM_DB,
dirNameStr,
getTmpDir,
isMac,
isSecureMode,
isWin,
} from "../lib/helpers/utils.js";
import { validateBom } from "../lib/helpers/validator.js";
import { postProcess } from "../lib/stages/postgen/postgen.js";
import { prepareEnv } from "../lib/stages/pregen/pregen.js";
// Support for config files
const configPath = findUpSync([
".cdxgenrc",
".cdxgen.json",
".cdxgen.yml",
".cdxgen.yaml",
]);
let config = {};
if (configPath) {
try {
if (configPath.endsWith(".yml") || configPath.endsWith(".yaml")) {
config = _load(fs.readFileSync(configPath, "utf-8"));
} else {
config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
}
} catch (e) {
console.log("Invalid config file", configPath);
}
}
let url = import.meta.url;
if (!url.startsWith("file://")) {
url = new URL(`file://${import.meta.url}`).toString();
}
const dirName = dirNameStr;
import yargs from "yargs";
import { hideBin } from "yargs/helpers";
const args = yargs(hideBin(process.argv))
.env("CDXGEN")
.parserConfiguration({
"greedy-arrays": false,
"short-option-groups": false,
})
.option("output", {
alias: "o",
description: "Output file. Default bom.json",
default: "bom.json",
})
.option("evinse-output", {
description:
"Create bom with evidence as a separate file. Default bom.json",
hidden: true,
})
.option("type", {
alias: "t",
description:
"Project type. Please refer to https://cyclonedx.github.io/cdxgen/#/PROJECT_TYPES for supported languages/platforms.",
})
.option("exclude-type", {
description:
"Project types to exclude. Please refer to https://cyclonedx.github.io/cdxgen/#/PROJECT_TYPES for supported languages/platforms.",
})
.option("recurse", {
alias: "r",
type: "boolean",
default: true,
description:
"Recurse mode suitable for mono-repos. Defaults to true. Pass --no-recurse to disable.",
})
.option("print", {
alias: "p",
type: "boolean",
description: "Print the SBOM as a table with tree.",
})
.option("resolve-class", {
alias: "c",
type: "boolean",
description: "Resolve class names for packages. jars only for now.",
})
.option("deep", {
type: "boolean",
description:
"Perform deep searches for components. Useful while scanning C/C++ apps, live OS and oci images.",
})
.option("server-url", {
description: "Dependency track url. Eg: https://deptrack.cyclonedx.io",
})
.option("skip-dt-tls-check", {
type: "boolean",
default: false,
description: "Skip TLS certificate check when calling Dependency-Track. ",
})
.option("api-key", {
description: "Dependency track api key",
})
.option("project-group", {
description: "Dependency track project group",
})
.option("project-name", {
description:
"Dependency track project name. Default use the directory name",
})
.option("project-version", {
description: "Dependency track project version",
default: "",
type: "string",
})
.option("project-id", {
description:
"Dependency track project id. Either provide the id or the project name and version together",
type: "string",
})
.option("parent-project-id", {
description: "Dependency track parent project id",
type: "string",
})
.option("required-only", {
type: "boolean",
description:
"Include only the packages with required scope on the SBOM. Would set compositions.aggregate to incomplete unless --no-auto-compositions is passed.",
})
.option("fail-on-error", {
type: "boolean",
default: isSecureMode,
description: "Fail if any dependency extractor fails.",
})
.option("no-babel", {
type: "boolean",
description:
"Do not use babel to perform usage analysis for JavaScript/TypeScript projects.",
})
.option("generate-key-and-sign", {
type: "boolean",
description:
"Generate an RSA public/private key pair and then sign the generated SBOM using JSON Web Signatures.",
})
.option("server", {
type: "boolean",
description: "Run cdxgen as a server",
})
.option("server-host", {
description: "Listen address",
default: "127.0.0.1",
})
.option("server-port", {
description: "Listen port",
default: "9090",
})
.option("install-deps", {
type: "boolean",
default: !isSecureMode,
description:
"Install dependencies automatically for some projects. Defaults to true but disabled for containers and oci scans. Use --no-install-deps to disable this feature.",
})
.option("validate", {
type: "boolean",
default: true,
description:
"Validate the generated SBOM using json schema. Defaults to true. Pass --no-validate to disable.",
})
.option("evidence", {
type: "boolean",
default: false,
description: "Generate SBOM with evidence for supported languages.",
})
.option("deps-slices-file", {
description: "Path for the parsedeps slice file created by atom.",
default: "deps.slices.json",
hidden: true,
})
.option("usages-slices-file", {
description: "Path for the usages slices file created by atom.",
default: "usages.slices.json",
hidden: true,
})
.option("data-flow-slices-file", {
description: "Path for the data-flow slices file created by atom.",
default: "data-flow.slices.json",
hidden: true,
})
.option("reachables-slices-file", {
description: "Path for the reachables slices file created by atom.",
default: "reachables.slices.json",
hidden: true,
})
.option("semantics-slices-file", {
description: "Path for the semantics slices file.",
default: "semantics.slices.json",
hidden: true,
})
.option("spec-version", {
description: "CycloneDX Specification version to use. Defaults to 1.6",
default: 1.6,
type: "number",
})
.option("filter", {
description:
"Filter components containing this word in purl or component.properties.value. Multiple values allowed.",
})
.option("only", {
description:
"Include components only containing this word in purl. Useful to generate BOM with first party components alone. Multiple values allowed.",
})
.option("author", {
description:
"The person(s) who created the BOM. Set this value if you're intending the modify the BOM and claim authorship.",
default: "OWASP Foundation",
})
.option("profile", {
description: "BOM profile to use for generation. Default generic.",
default: "generic",
choices: [
"appsec",
"research",
"operational",
"threat-modeling",
"license-compliance",
"generic",
"machine-learning",
"ml",
"deep-learning",
"ml-deep",
"ml-tiny",
],
})
.option("lifecycle", {
description: "Product lifecycle for the generated BOM.",
hidden: true,
choices: ["pre-build", "build", "post-build"],
})
.option("exclude", {
description: "Additional glob pattern(s) to ignore",
})
.option("export-proto", {
type: "boolean",
default: false,
description: "Serialize and export BOM as protobuf binary.",
hidden: true,
})
.option("proto-bin-file", {
description: "Path for the serialized protobuf binary.",
default: "bom.cdx",
hidden: true,
})
.option("include-formulation", {
type: "boolean",
default: false,
description:
"Generate formulation section with git metadata and build tools. Defaults to false.",
})
.option("include-crypto", {
type: "boolean",
default: false,
description: "Include crypto libraries as components.",
})
.option("standard", {
description:
"The list of standards which may consist of regulations, industry or organizational-specific standards, maturity models, best practices, or any other requirements which can be evaluated against or attested to.",
choices: [
"asvs-5.0",
"asvs-4.0.3",
"bsimm-v13",
"masvs-2.0.0",
"nist_ssdf-1.1",
"pcissc-secure-slc-1.1",
"scvs-1.0.0",
"ssaf-DRAFT-2023-11",
],
})
.option("no-banner", {
type: "boolean",
default: false,
hidden: true,
description:
"Do not show the donation banner. Set this attribute if you are an active sponsor for OWASP CycloneDX.",
})
.option("feature-flags", {
description: "Experimental feature flags to enable. Advanced users only.",
hidden: true,
choices: ["safe-pip-install", "suggest-build-tools", "ruby-docker-install"],
})
.option("min-confidence", {
description:
"Minimum confidence needed for the identity of a component from 0 - 1, where 1 is 100% confidence.",
default: 0,
type: "number",
})
.option("technique", {
description: "Analysis technique to use",
choices: [
"auto",
"source-code-analysis",
"binary-analysis",
"manifest-analysis",
"hash-comparison",
"instrumentation",
"filename",
],
})
.completion("completion", "Generate bash/zsh completion")
.array("type")
.array("excludeType")
.array("filter")
.array("only")
.array("author")
.array("exclude")
.array("standard")
.array("feature-flags")
.array("technique")
.option("auto-compositions", {
type: "boolean",
default: true,
description:
"Automatically set compositions when the BOM was filtered. Defaults to true",
})
.example([
["$0 -t java .", "Generate a Java SBOM for the current directory"],
[
"$0 -t java -t js .",
"Generate a SBOM for Java and JavaScript in the current directory",
],
[
"$0 -t java --profile ml .",
"Generate a Java SBOM for machine learning purposes.",
],
[
"$0 -t python --profile research .",
"Generate a Python SBOM for appsec research.",
],
["$0 --server", "Run cdxgen as a server"],
])
.epilogue("for documentation, visit https://cyclonedx.github.io/cdxgen")
.config(config)
.scriptName("cdxgen")
.version()
.alias("v", "version")
.help("h")
.alias("h", "help")
.wrap(Math.min(120, yargs().terminalWidth())).argv;
if (process.env?.CDXGEN_NODE_OPTIONS) {
process.env.NODE_OPTIONS = `${process.env.NODE_OPTIONS || ""} ${process.env.CDXGEN_NODE_OPTIONS}`;
}
if (args.version) {
const packageJsonAsString = fs.readFileSync(
join(dirName, "..", "package.json"),
"utf-8",
);
const packageJson = JSON.parse(packageJsonAsString);
console.log(packageJson.version);
process.exit(0);
}
if (process.env.GLOBAL_AGENT_HTTP_PROXY || process.env.HTTP_PROXY) {
// Support standard HTTP_PROXY variable if the user doesn't override the namespace
if (!process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE) {
process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE = "";
}
globalAgent.bootstrap();
}
const filePath = args._[0] || process.cwd();
if (!args.projectName) {
if (filePath !== ".") {
args.projectName = basename(filePath);
} else {
args.projectName = basename(resolve(filePath));
}
}
// Support for obom/cbom aliases
if (process.argv[1].includes("obom") && !args.type) {
args.type = "os";
}
/**
* Command line options
*/
const options = Object.assign({}, args, {
projectType: args.type,
multiProject: args.recurse,
noBabel: args.noBabel || args.babel === false,
project: args.projectId,
deep: args.deep || args.evidence,
});
if (process.argv[1].includes("cbom")) {
options.includeCrypto = true;
options.evidence = true;
options.specVersion = 1.6;
options.deep = true;
}
if (options.standard) {
options.specVersion = 1.6;
}
if (options.includeFormulation) {
console.log(
"NOTE: Formulation section could include sensitive data such as emails and secrets.\nPlease review the generated SBOM before distribution.\n",
);
}
/**
* Method to apply advanced options such as profile and lifecycles
*
* @param {object} options CLI options
*/
const applyAdvancedOptions = (options) => {
switch (options.profile) {
case "appsec":
options.deep = true;
break;
case "research":
options.deep = true;
options.evidence = true;
options.includeCrypto = true;
process.env.CDX_MAVEN_INCLUDE_TEST_SCOPE = "true";
process.env.ASTGEN_IGNORE_DIRS = "";
process.env.ASTGEN_IGNORE_FILE_PATTERN = "";
break;
case "operational":
if (options?.projectType) {
options.projectType.push("os");
} else {
options.projectType = ["os"];
}
break;
case "threat-modeling":
options.deep = true;
options.evidence = true;
break;
case "license-compliance":
process.env.FETCH_LICENSE = "true";
break;
case "ml-tiny":
process.env.FETCH_LICENSE = "true";
options.deep = false;
options.evidence = false;
options.includeCrypto = false;
options.installDeps = false;
break;
case "machine-learning":
case "ml":
process.env.FETCH_LICENSE = "true";
options.deep = true;
options.evidence = false;
options.includeCrypto = false;
options.installDeps = !isSecureMode;
break;
case "deep-learning":
case "ml-deep":
process.env.FETCH_LICENSE = "true";
options.deep = true;
options.evidence = true;
options.includeCrypto = true;
options.installDeps = !isSecureMode;
break;
default:
break;
}
switch (options.lifecycle) {
case "pre-build":
options.installDeps = false;
break;
case "post-build":
if (
!options.projectType ||
(Array.isArray(options.projectType) &&
options.projectType.length > 1) ||
![
"csharp",
"dotnet",
"container",
"docker",
"podman",
"oci",
"android",
"apk",
"aab",
"go",
"golang",
"rust",
"rust-lang",
"cargo",
].includes(options.projectType[0])
) {
console.log(
"PREVIEW: post-build lifecycle SBOM generation is supported only for android, dotnet, go, and Rust projects. Please specify the type using the -t argument.",
);
process.exit(1);
}
options.installDeps = true;
break;
default:
break;
}
// When the user specifies source-code-analysis as a technique, then enable deep and evidence mode.
if (
options?.technique &&
Array.isArray(options.technique) &&
options?.technique?.includes("source-code-analysis")
) {
options.deep = true;
options.evidence = true;
}
return options;
};
applyAdvancedOptions(options);
/**
* Check for node >= 20 permissions
*
* @param {string} filePath File path
* @param {Object} options CLI Options
* @returns
*/
const checkPermissions = (filePath, options) => {
if (!process.permission) {
return true;
}
const fullFilePath = resolve(filePath);
// Secure mode checks
if (isSecureMode) {
if (process.permission.has("fs.read", "*")) {
console.log(
"\x1b[1;35mSECURE MODE: DO NOT run cdxgen with FileSystemRead permission set to wildcard.\x1b[0m",
);
}
if (process.permission.has("fs.write", "*")) {
console.log(
"\x1b[1;35mSECURE MODE: DO NOT run cdxgen with FileSystemWrite permission set to wildcard.\x1b[0m",
);
}
if (process.permission.has("worker")) {
console.log(
"SECURE MODE: DO NOT run cdxgen with worker thread permission! Remove `--allow-worker` argument.",
);
}
if (filePath !== fullFilePath) {
console.log(
`\x1b[1;35mSECURE MODE: Invoke cdxgen with an absolute path to improve security. Use ${fullFilePath} instead of ${filePath}.\x1b[0m`,
);
if (fullFilePath.includes(" ")) {
console.log(
"\x1b[1;35mSECURE MODE: Directory names containing spaces are known to cause issues. Rename the directories by replacing spaces with hyphens or underscores.\x1b[0m",
);
} else if (fullFilePath.length > 255 && isWin) {
console.log(
"Ensure 'Enable Win32 Long paths' is set to 'Enabled' by using Group Policy Editor.",
);
}
return false;
}
}
if (!process.permission.has("fs.read", filePath)) {
console.log(
`\x1b[1;35mSECURE MODE: FileSystemRead permission required. Please invoke cdxgen with the argument --allow-fs-read="${resolve(
filePath,
)}"\x1b[0m`,
);
return false;
}
if (!process.permission.has("fs.write", options.output)) {
console.log(
`\x1b[1;35mSECURE MODE: FileSystemWrite permission is required to create the output BOM file. Please invoke cdxgen with the argument --allow-fs-write="${options.output}"\x1b[0m`,
);
}
if (options.evidence) {
const slicesFilesKeys = [
"deps-slices-file",
"usages-slices-file",
"reachables-slices-file",
];
if (options?.type?.includes("swift")) {
slicesFilesKeys.push("semantics-slices-file");
}
for (const sf of slicesFilesKeys) {
let issueFound = false;
if (!process.permission.has("fs.write", options[sf])) {
console.log(
`SECURE MODE: FileSystemWrite permission is required to create the output slices file. Please invoke cdxgen with the argument --allow-fs-write="${options[sf]}"`,
);
if (!issueFound) {
issueFound = true;
}
}
if (issueFound) {
return false;
}
}
if (!process.permission.has("fs.write", process.env.ATOM_DB || ATOM_DB)) {
console.log(
`SECURE MODE: FileSystemWrite permission is required to create the output slices file. Please invoke cdxgen with the argument --allow-fs-write="${process.env.ATOM_DB || ATOM_DB}"`,
);
return false;
}
console.log(
"TIP: Invoke cdxgen with `--allow-addons` to allow the use of sqlite3 native addon. This addon is required for evidence mode.",
);
} else {
if (process.permission.has("fs.write", process.env.ATOM_DB || ATOM_DB)) {
console.log(
`SECURE MODE: FileSystemWrite permission is not required for the directory "${process.env.ATOM_DB || ATOM_DB}" in non-evidence mode. Consider removing the argument --allow-fs-write="${process.env.ATOM_DB || ATOM_DB}".`,
);
return false;
}
}
if (!process.permission.has("fs.write", getTmpDir())) {
console.log(
`FileSystemWrite permission may be required to the TEMP directory. Please invoke cdxgen with the argument --allow-fs-write="${join(getTmpDir(), "*")}"`,
);
if (isMac) {
console.log(
"TIP: macOS doesn't use `/tmp` prefix for TEMP directories. Use the argument shown above.",
);
}
}
if (!process.permission.has("child") && !isSecureMode) {
console.log(
"ChildProcess permission is missing. This is required to spawn commands for some languages. Please invoke cdxgen with the argument --allow-child-process in case of issues.",
);
}
if (process.permission.has("child") && options?.lifecycle === "pre-build") {
console.log(
"SECURE MODE: ChildProcess permission is not required for pre-build SBOM generation. Please invoke cdxgen without the argument --allow-child-process.",
);
return false;
}
return true;
};
/**
* Method to start the bom creation process
*/
(async () => {
// Display the sponsor banner
printSponsorBanner(options);
// Start SBOM server
if (options.server) {
const serverModule = await import("../lib/server/server.js");
return serverModule.start(options);
}
// Check if cdxgen has the required permissions
if (!checkPermissions(filePath, options)) {
if (isSecureMode) {
process.exit(1);
}
return;
}
// This will prevent people from accidentally using the usages slices belonging to a different project
if (!options.usagesSlicesFile) {
options.usagesSlicesFile = `${options.projectName}-usages.json`;
}
prepareEnv(filePath, options);
let bomNSData = (await createBom(filePath, options)) || {};
// Add extra metadata and annotations with post processing
bomNSData = postProcess(bomNSData, options);
if (
options.output &&
(typeof options.output === "string" || options.output instanceof String)
) {
const jsonFile = options.output;
// Create bom json file
if (bomNSData.bomJson) {
let jsonPayload = undefined;
if (
typeof bomNSData.bomJson === "string" ||
bomNSData.bomJson instanceof String
) {
fs.writeFileSync(jsonFile, bomNSData.bomJson);
jsonPayload = bomNSData.bomJson;
} else {
jsonPayload = JSON.stringify(bomNSData.bomJson, null, null);
fs.writeFileSync(jsonFile, jsonPayload);
}
if (
jsonPayload &&
(options.generateKeyAndSign ||
(process.env.SBOM_SIGN_ALGORITHM &&
process.env.SBOM_SIGN_ALGORITHM !== "none" &&
process.env.SBOM_SIGN_PRIVATE_KEY &&
fs.existsSync(process.env.SBOM_SIGN_PRIVATE_KEY)))
) {
let alg = process.env.SBOM_SIGN_ALGORITHM || "RS512";
if (alg.includes("none")) {
alg = "RS512";
}
let privateKeyToUse = undefined;
let jwkPublicKey = undefined;
let publicKeyFile = undefined;
if (options.generateKeyAndSign) {
const jdirName = dirname(jsonFile);
publicKeyFile = join(jdirName, "public.key");
const privateKeyFile = join(jdirName, "private.key");
const { privateKey, publicKey } = crypto.generateKeyPairSync("rsa", {
modulusLength: 4096,
publicKeyEncoding: {
type: "spki",
format: "pem",
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem",
},
});
fs.writeFileSync(publicKeyFile, publicKey);
fs.writeFileSync(privateKeyFile, privateKey);
console.log(
"Created public/private key pairs for testing purposes",
publicKeyFile,
privateKeyFile,
);
privateKeyToUse = privateKey;
jwkPublicKey = crypto
.createPublicKey(publicKey)
.export({ format: "jwk" });
} else {
privateKeyToUse = fs.readFileSync(
process.env.SBOM_SIGN_PRIVATE_KEY,
"utf8",
);
if (
process.env.SBOM_SIGN_PUBLIC_KEY &&
fs.existsSync(process.env.SBOM_SIGN_PUBLIC_KEY)
) {
jwkPublicKey = crypto
.createPublicKey(
fs.readFileSync(process.env.SBOM_SIGN_PUBLIC_KEY, "utf8"),
)
.export({ format: "jwk" });
}
}
try {
// Sign the individual components
// Let's leave the services unsigned for now since it might require additional cleansing
const bomJsonUnsignedObj = JSON.parse(jsonPayload);
for (const comp of bomJsonUnsignedObj.components) {
const compSignature = jws.sign({
header: { alg },
payload: comp,
privateKey: privateKeyToUse,
});
const compSignatureBlock = {
algorithm: alg,
value: compSignature,
};
if (jwkPublicKey) {
compSignatureBlock.publicKey = jwkPublicKey;
}
comp.signature = compSignatureBlock;
}
const signature = jws.sign({
header: { alg },
payload: JSON.stringify(bomJsonUnsignedObj, null, 2),
privateKey: privateKeyToUse,
});
if (signature) {
const signatureBlock = {
algorithm: alg,
value: signature,
};
if (jwkPublicKey) {
signatureBlock.publicKey = jwkPublicKey;
}
bomJsonUnsignedObj.signature = signatureBlock;
fs.writeFileSync(
jsonFile,
JSON.stringify(bomJsonUnsignedObj, null, null),
);
if (publicKeyFile) {
// Verifying this signature
const signatureVerification = jws.verify(
signature,
alg,
fs.readFileSync(publicKeyFile, "utf8"),
);
if (signatureVerification) {
console.log(
"SBOM signature is verifiable with the public key and the algorithm",
publicKeyFile,
alg,
);
} else {
console.log("SBOM signature verification was unsuccessful");
console.log(
"Check if the public key was exported in PEM format",
);
}
}
}
} catch (ex) {
console.log("SBOM signing was unsuccessful", ex);
console.log("Check if the private key was exported in PEM format");
}
}
}
// bom ns mapping
if (bomNSData.nsMapping && Object.keys(bomNSData.nsMapping).length) {
const nsFile = `${jsonFile}.map`;
fs.writeFileSync(nsFile, JSON.stringify(bomNSData.nsMapping));
}
} else if (!options.print) {
if (bomNSData.bomJson) {
console.log(JSON.stringify(bomNSData.bomJson, null, 2));
} else {
console.log("Unable to produce BOM for", filePath);
console.log("Try running the command with -t <type> or -r argument");
}
}
// Evidence generation
if (options.evidence || options.includeCrypto) {
// Set the evinse output file to be the same as output file
if (!options.evinseOutput) {
options.evinseOutput = options.output;
}
const evinserModule = await import("../lib/evinser/evinser.js");
options.projectType = options.projectType || ["java"];
const evinseOptions = {
_: args._,
input: options.output,
output: options.evinseOutput,
language: options.projectType,
dbPath: process.env.ATOM_DB || ATOM_DB,
skipMavenCollector: false,
force: false,
withReachables: options.deep,
usagesSlicesFile: options.usagesSlicesFile,
dataFlowSlicesFile: options.dataFlowSlicesFile,
reachablesSlicesFile: options.reachablesSlicesFile,
semanticsSlicesFile: options.semanticsSlicesFile,
includeCrypto: options.includeCrypto,
specVersion: options.specVersion,
profile: options.profile,
};
const dbObjMap = await evinserModule.prepareDB(evinseOptions);
if (dbObjMap) {
const sliceArtefacts = await evinserModule.analyzeProject(
dbObjMap,
evinseOptions,
);
const evinseJson = evinserModule.createEvinseFile(
sliceArtefacts,
evinseOptions,
);
bomNSData.bomJson = evinseJson;
if (options.print && evinseJson) {
printOccurrences(evinseJson);
printCallStack(evinseJson);
printReachables(sliceArtefacts);
printServices(evinseJson);
}
}
}
// Perform automatic validation
if (options.validate) {
if (!validateBom(bomNSData.bomJson)) {
process.exit(1);
}
}
// Automatically submit the bom data
// biome-ignore lint/suspicious/noDoubleEquals: yargs passes true for empty values
if (options.serverUrl && options.serverUrl != true && options.apiKey) {
try {
await submitBom(options, bomNSData.bomJson);
} catch (err) {
console.log(err);
}
}
// Protobuf serialization
if (options.exportProto) {
const protobomModule = await import("../lib/helpers/protobom.js");
protobomModule.writeBinary(bomNSData.bomJson, options.protoBinFile);
}
if (options.print && bomNSData.bomJson && bomNSData.bomJson.components) {
printSummary(bomNSData.bomJson);
if (options.includeFormulation) {
printFormulation(bomNSData.bomJson);
}
printDependencyTree(bomNSData.bomJson);
printTable(bomNSData.bomJson);
// CBOM related print
if (options.includeCrypto) {
printTable(bomNSData.bomJson, ["cryptographic-asset"]);
printDependencyTree(bomNSData.bomJson, "provides");
}
}
})();