forked from CycloneDX/cdxgen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevinser.js
1230 lines (1209 loc) · 37.2 KB
/
evinser.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
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
import {
executeAtom,
getAllFiles,
getGradleCommand,
getMavenCommand,
collectGradleDependencies,
collectMvnDependencies
} from "./utils.js";
import { tmpdir } from "node:os";
import path, { basename } from "node:path";
import fs from "node:fs";
import * as db from "./db.js";
import { PackageURL } from "packageurl-js";
import { Op } from "sequelize";
import process from "node:process";
const DB_NAME = "evinser.db";
const typePurlsCache = {};
/**
* Function to create the db for the libraries referred in the sbom.
*
* @param {object} Command line options
*/
export const prepareDB = async (options) => {
if (!options.dbPath.includes("memory") && !fs.existsSync(options.dbPath)) {
try {
fs.mkdirSync(options.dbPath, { recursive: true });
} catch (e) {
// ignore
}
}
const dirPath = options._[0] || ".";
const bomJsonFile = options.input;
if (!fs.existsSync(bomJsonFile)) {
console.log(
"Bom file doesn't exist. Check if cdxgen was invoked with the correct type argument."
);
if (!process.env.CDXGEN_DEBUG_MODE) {
console.log(
"Set the environment variable CDXGEN_DEBUG_MODE to debug to troubleshoot the issue further."
);
}
return;
}
const bomJson = JSON.parse(fs.readFileSync(bomJsonFile, "utf8"));
if (bomJson.specVersion < 1.5) {
console.log(
"Evinse requires the input SBOM in CycloneDX 1.5 format or above. You can generate one by invoking cdxgen without any --spec-version argument."
);
process.exit(0);
}
const components = bomJson.components || [];
const { sequelize, Namespaces, Usages, DataFlows } = await db.createOrLoad(
DB_NAME,
options.dbPath
);
let hasMavenPkgs = false;
// We need to slice only non-maven packages
const purlsToSlice = {};
const purlsJars = {};
let usagesSlice = undefined;
for (const comp of components) {
if (!comp.purl) {
continue;
}
usagesSlice = await Usages.findByPk(comp.purl);
const namespaceSlice = await Namespaces.findByPk(comp.purl);
if ((!usagesSlice && !namespaceSlice) || options.force) {
if (comp.purl.startsWith("pkg:maven")) {
hasMavenPkgs = true;
}
}
}
// If there are maven packages we collect and store the namespaces
if (!options.skipMavenCollector && hasMavenPkgs) {
const pomXmlFiles = getAllFiles(dirPath, "**/" + "pom.xml");
const gradleFiles = getAllFiles(dirPath, "**/" + "build.gradle*");
if (pomXmlFiles && pomXmlFiles.length) {
await catalogMavenDeps(dirPath, purlsJars, Namespaces, options);
}
if (gradleFiles && gradleFiles.length) {
await catalogGradleDeps(dirPath, purlsJars, Namespaces);
}
}
for (const purl of Object.keys(purlsToSlice)) {
await createAndStoreSlice(purl, purlsJars, Usages, options);
}
return { sequelize, Namespaces, Usages, DataFlows };
};
export const catalogMavenDeps = async (
dirPath,
purlsJars,
Namespaces,
options = {}
) => {
console.log("About to collect jar dependencies for the path", dirPath);
const mavenCmd = getMavenCommand(dirPath, dirPath);
// collect all jars including from the cache if data-flow mode is enabled
const jarNSMapping = collectMvnDependencies(
mavenCmd,
dirPath,
false,
options.withDeepJarCollector
);
if (jarNSMapping) {
for (const purl of Object.keys(jarNSMapping)) {
purlsJars[purl] = jarNSMapping[purl].jarFile;
await Namespaces.findOrCreate({
where: { purl },
defaults: {
purl,
data: JSON.stringify(
{
pom: jarNSMapping[purl].pom,
namespaces: jarNSMapping[purl].namespaces
},
null,
2
)
}
});
}
}
};
export const catalogGradleDeps = async (dirPath, purlsJars, Namespaces) => {
console.log(
"About to collect jar dependencies from the gradle cache. This would take a while ..."
);
const gradleCmd = getGradleCommand(dirPath, dirPath);
// collect all jars including from the cache if data-flow mode is enabled
const jarNSMapping = collectGradleDependencies(
gradleCmd,
dirPath,
false,
true
);
if (jarNSMapping) {
for (const purl of Object.keys(jarNSMapping)) {
purlsJars[purl] = jarNSMapping[purl].jarFile;
await Namespaces.findOrCreate({
where: { purl },
defaults: {
purl,
data: JSON.stringify(
{
pom: jarNSMapping[purl].pom,
namespaces: jarNSMapping[purl].namespaces
},
null,
2
)
}
});
}
}
console.log(
"To speed up successive re-runs, pass the argument --skip-maven-collector to evinse command."
);
};
export const createAndStoreSlice = async (
purl,
purlsJars,
Usages,
options = {}
) => {
const retMap = createSlice(purl, purlsJars[purl], "usages", options);
let sliceData = undefined;
if (retMap && retMap.slicesFile && fs.existsSync(retMap.slicesFile)) {
sliceData = await Usages.findOrCreate({
where: { purl },
defaults: {
purl,
data: fs.readFileSync(retMap.slicesFile, "utf-8")
}
});
}
if (retMap && retMap.tempDir && retMap.tempDir.startsWith(tmpdir())) {
fs.rmSync(retMap.tempDir, { recursive: true, force: true });
}
return sliceData;
};
export const createSlice = (
purlOrLanguage,
filePath,
sliceType = "usages",
options = {}
) => {
if (!filePath) {
return;
}
console.log(`Create ${sliceType} slice for ${purlOrLanguage} ${filePath}`);
const language = purlOrLanguage.startsWith("pkg:")
? purlToLanguage(purlOrLanguage, filePath)
: purlOrLanguage;
if (!language) {
return undefined;
}
let sliceOutputDir = fs.mkdtempSync(
path.join(tmpdir(), `atom-${sliceType}-`)
);
if (options && options.output) {
sliceOutputDir =
fs.existsSync(options.output) &&
fs.lstatSync(options.output).isDirectory()
? path.basename(options.output)
: path.dirname(options.output);
}
const atomFile = path.join(sliceOutputDir, "app.atom");
const slicesFile = path.join(sliceOutputDir, `${sliceType}.slices.json`);
const args = [
sliceType,
"-l",
language,
"-o",
path.resolve(atomFile),
"--slice-outfile",
path.resolve(slicesFile)
];
// For projects with several layers, slice depth needs to be increased from the default 7 to 15 or 20
// This would increase the time but would yield more deeper paths
if (sliceType == "data-flow" && process.env.ATOM_SLICE_DEPTH) {
args.push("--slice-depth");
args.push(process.env.ATOM_SLICE_DEPTH);
}
args.push(path.resolve(filePath));
const result = executeAtom(filePath, args);
if (!result || !fs.existsSync(slicesFile)) {
console.warn(`Unable to generate ${sliceType} slice using atom.`);
console.log(
"Set the environment variable CDXGEN_DEBUG_MODE=debug to troubleshoot."
);
}
return {
tempDir: sliceOutputDir,
slicesFile,
atomFile
};
};
export const purlToLanguage = (purl, filePath) => {
let language = undefined;
const purlObj = PackageURL.fromString(purl);
switch (purlObj.type) {
case "maven":
language = filePath && filePath.endsWith(".jar") ? "jar" : "java";
break;
case "npm":
language = "javascript";
break;
case "pypi":
language = "python";
break;
}
return language;
};
export const initFromSbom = (components) => {
const purlLocationMap = {};
const purlImportsMap = {};
for (const comp of components) {
if (!comp || !comp.evidence) {
continue;
}
(comp.properties || [])
.filter((v) => v.name === "ImportedModules")
.forEach((v) => {
purlImportsMap[comp.purl] = (v.value || "").split(",");
});
if (comp.evidence.occurrences) {
purlLocationMap[comp.purl] = new Set(
comp.evidence.occurrences.map((v) => v.location)
);
}
}
return {
purlLocationMap,
purlImportsMap
};
};
/**
* Function to analyze the project
*
* @param {object} dbObjMap DB and model instances
* @param {object} Command line options
*/
export const analyzeProject = async (dbObjMap, options) => {
const dirPath = options._[0] || ".";
const language = options.language;
let usageSlice = undefined;
let dataFlowSlice = undefined;
let reachablesSlice = undefined;
let usagesSlicesFile = undefined;
let dataFlowSlicesFile = undefined;
let reachablesSlicesFile = undefined;
let dataFlowFrames = {};
let servicesMap = {};
let retMap = {};
let userDefinedTypesMap = {};
const bomFile = options.input;
const bomJson = JSON.parse(fs.readFileSync(bomFile, "utf8"));
const components = bomJson.components || [];
// Load any existing purl-location information from the sbom.
// For eg: cdxgen populates this information for javascript projects
let { purlLocationMap, purlImportsMap } = initFromSbom(components);
// Reuse existing usages slices
if (options.usagesSlicesFile && fs.existsSync(options.usagesSlicesFile)) {
usageSlice = JSON.parse(fs.readFileSync(options.usagesSlicesFile, "utf-8"));
usagesSlicesFile = options.usagesSlicesFile;
} else {
// Generate our own slices
retMap = createSlice(language, dirPath, "usages", options);
if (retMap && retMap.slicesFile && fs.existsSync(retMap.slicesFile)) {
usageSlice = JSON.parse(fs.readFileSync(retMap.slicesFile, "utf-8"));
usagesSlicesFile = retMap.slicesFile;
console.log(
`To speed up this step, cache ${usagesSlicesFile} and invoke evinse with the --usages-slices-file argument.`
);
}
}
if (usageSlice && Object.keys(usageSlice).length) {
const retMap = await parseObjectSlices(
language,
usageSlice,
dbObjMap,
servicesMap,
purlLocationMap,
purlImportsMap
);
purlLocationMap = retMap.purlLocationMap;
servicesMap = retMap.servicesMap;
userDefinedTypesMap = retMap.userDefinedTypesMap;
}
if (options.withDataFlow) {
if (
options.dataFlowSlicesFile &&
fs.existsSync(options.dataFlowSlicesFile)
) {
dataFlowSlicesFile = options.dataFlowSlicesFile;
dataFlowSlice = JSON.parse(
fs.readFileSync(options.dataFlowSlicesFile, "utf-8")
);
} else {
retMap = createSlice(language, dirPath, "data-flow", options);
if (retMap && retMap.slicesFile && fs.existsSync(retMap.slicesFile)) {
dataFlowSlicesFile = retMap.slicesFile;
dataFlowSlice = JSON.parse(fs.readFileSync(retMap.slicesFile, "utf-8"));
console.log(
`To speed up this step, cache ${dataFlowSlicesFile} and invoke evinse with the --data-flow-slices-file argument.`
);
}
}
}
if (dataFlowSlice && Object.keys(dataFlowSlice).length) {
dataFlowFrames = await collectDataFlowFrames(
language,
userDefinedTypesMap,
dataFlowSlice,
dbObjMap,
purlLocationMap,
purlImportsMap
);
}
if (options.withReachables) {
if (
options.reachablesSlicesFile &&
fs.existsSync(options.reachablesSlicesFile)
) {
reachablesSlicesFile = options.reachablesSlicesFile;
reachablesSlice = JSON.parse(
fs.readFileSync(options.reachablesSlicesFile, "utf-8")
);
} else {
retMap = createSlice(language, dirPath, "reachables", options);
if (retMap && retMap.slicesFile && fs.existsSync(retMap.slicesFile)) {
reachablesSlicesFile = retMap.slicesFile;
reachablesSlice = JSON.parse(
fs.readFileSync(retMap.slicesFile, "utf-8")
);
console.log(
`To speed up this step, cache ${reachablesSlicesFile} and invoke evinse with the --reachables-slices-file argument.`
);
}
}
}
if (reachablesSlice && Object.keys(reachablesSlice).length) {
dataFlowFrames = await collectReachableFrames(language, reachablesSlice);
}
return {
atomFile: retMap.atomFile,
usagesSlicesFile,
dataFlowSlicesFile,
reachablesSlicesFile,
purlLocationMap,
servicesMap,
dataFlowFrames,
tempDir: retMap.tempDir,
userDefinedTypesMap
};
};
export const parseObjectSlices = async (
language,
usageSlice,
dbObjMap,
servicesMap = {},
purlLocationMap = {},
purlImportsMap = {}
) => {
if (!usageSlice || !Object.keys(usageSlice).length) {
return purlLocationMap;
}
const userDefinedTypesMap = {};
(usageSlice.userDefinedTypes || []).forEach((ut) => {
userDefinedTypesMap[ut.name] = true;
});
for (const slice of [
...(usageSlice.objectSlices || []),
...(usageSlice.userDefinedTypes || [])
]) {
// Skip the library code typically without filename
if (
!slice.fileName ||
!slice.fileName.trim().length ||
slice.fileName === "<empty>" ||
slice.fileName === "<unknown>"
) {
continue;
}
await parseSliceUsages(
language,
userDefinedTypesMap,
slice,
dbObjMap,
purlLocationMap,
purlImportsMap
);
detectServicesFromUsages(language, slice, servicesMap);
}
detectServicesFromUDT(language, usageSlice.userDefinedTypes, servicesMap);
return {
purlLocationMap,
servicesMap,
userDefinedTypesMap
};
};
/**
* The implementation of this function is based on the logic proposed in the atom slices specification
* https://github.com/AppThreat/atom/blob/main/specification/docs/slices.md#use
*
* @param {string} language Application language
* @param {object} userDefinedTypesMap User Defined types in the application
* @param {array} usages Usages array for each objectSlice
* @param {object} dbObjMap DB Models
* @param {object} purlLocationMap Object to track locations where purls are used
* @param {object} purlImportsMap Object to track package urls and their import aliases
* @returns
*/
export const parseSliceUsages = async (
language,
userDefinedTypesMap,
slice,
dbObjMap,
purlLocationMap,
purlImportsMap
) => {
const usages = slice.usages;
if (!usages || !usages.length) {
return undefined;
}
const fileName = slice.fileName;
const typesToLookup = new Set();
const lKeyOverrides = {};
for (const ausage of usages) {
const ausageLine =
ausage?.targetObj?.lineNumber || ausage?.definedBy?.lineNumber;
// First capture the types in the targetObj and definedBy
for (const atype of [
[ausage?.targetObj?.isExternal, ausage?.targetObj?.typeFullName],
[ausage?.targetObj?.isExternal, ausage?.targetObj?.resolvedMethod],
[ausage?.definedBy?.isExternal, ausage?.definedBy?.typeFullName],
[ausage?.definedBy?.isExternal, ausage?.definedBy?.resolvedMethod],
...(ausage?.fields || []).map((f) => [f?.isExternal, f?.typeFullName])
]) {
if (
atype[0] !== false &&
!isFilterableType(language, userDefinedTypesMap, atype[1])
) {
if (!atype[1].includes("(") && !atype[1].includes(".py")) {
typesToLookup.add(atype[1]);
// Javascript calls can be resolved to a precise line number only from the call nodes
if (
["javascript", "js", "ts", "typescript"].includes(language) &&
ausageLine
) {
if (atype[1].includes(":")) {
typesToLookup.add(atype[1].split("::")[0].replace(/:/g, "/"));
}
addToOverrides(lKeyOverrides, atype[1], fileName, ausageLine);
}
}
const maybeClassType = getClassTypeFromSignature(language, atype[1]);
typesToLookup.add(maybeClassType);
if (ausageLine) {
addToOverrides(lKeyOverrides, maybeClassType, fileName, ausageLine);
}
}
}
// Now capture full method signatures from invokedCalls, argToCalls including the paramtypes
for (const acall of []
.concat(ausage?.invokedCalls || [])
.concat(ausage?.argToCalls || [])
.concat(ausage?.procedures || [])) {
if (acall.isExternal == false) {
continue;
}
if (
!isFilterableType(language, userDefinedTypesMap, acall?.resolvedMethod)
) {
if (
!acall?.resolvedMethod.includes("(") &&
!acall?.resolvedMethod.includes(".py")
) {
typesToLookup.add(acall?.resolvedMethod);
// Javascript calls can be resolved to a precise line number only from the call nodes
if (acall.lineNumber) {
addToOverrides(
lKeyOverrides,
acall?.resolvedMethod,
fileName,
acall.lineNumber
);
}
}
const maybeClassType = getClassTypeFromSignature(
language,
acall?.resolvedMethod
);
typesToLookup.add(maybeClassType);
if (acall.lineNumber) {
addToOverrides(
lKeyOverrides,
maybeClassType,
fileName,
acall.lineNumber
);
}
}
for (const aparamType of acall?.paramTypes || []) {
if (!isFilterableType(language, userDefinedTypesMap, aparamType)) {
if (!aparamType.includes("(") && !aparamType.includes(".py")) {
typesToLookup.add(aparamType);
if (acall.lineNumber) {
if (aparamType.includes(":")) {
typesToLookup.add(aparamType.split("::")[0].replace(/:/g, "/"));
}
addToOverrides(
lKeyOverrides,
aparamType,
fileName,
acall.lineNumber
);
}
}
const maybeClassType = getClassTypeFromSignature(
language,
aparamType
);
typesToLookup.add(maybeClassType);
if (acall.lineNumber) {
addToOverrides(
lKeyOverrides,
maybeClassType,
fileName,
acall.lineNumber
);
}
}
}
}
}
for (const atype of typesToLookup) {
if (isFilterableType(language, userDefinedTypesMap, atype)) {
continue;
}
if (purlImportsMap && Object.keys(purlImportsMap).length) {
for (const apurl of Object.keys(purlImportsMap)) {
const apurlImports = purlImportsMap[apurl];
if (apurlImports && apurlImports.includes(atype)) {
if (!purlLocationMap[apurl]) {
purlLocationMap[apurl] = new Set();
}
if (lKeyOverrides[atype]) {
purlLocationMap[apurl].add(...lKeyOverrides[atype]);
}
}
}
} else {
// Check the namespaces db
let nsHits = typePurlsCache[atype];
if (["java", "jar"].includes(language)) {
nsHits = await dbObjMap.Namespaces.findAll({
attributes: ["purl"],
where: {
data: {
[Op.like]: `%${atype}%`
}
}
});
}
if (nsHits && nsHits.length) {
for (const ns of nsHits) {
if (!purlLocationMap[ns.purl]) {
purlLocationMap[ns.purl] = new Set();
}
if (lKeyOverrides[atype]) {
purlLocationMap[ns.purl].add(...lKeyOverrides[atype]);
}
}
typePurlsCache[atype] = nsHits;
}
}
}
};
export const isFilterableType = (
language,
userDefinedTypesMap,
typeFullName
) => {
if (
!typeFullName ||
["ANY", "UNKNOWN", "VOID", "IMPORT"].includes(typeFullName.toUpperCase())
) {
return true;
}
for (const ab of [
"<operator",
"<unresolved",
"<unknownFullName",
"__builtin",
"LAMBDA",
"../"
]) {
if (typeFullName.startsWith(ab)) {
return true;
}
}
if (language && ["java", "jar"].includes(language)) {
if (
!typeFullName.includes(".") ||
typeFullName.startsWith("@") ||
typeFullName.startsWith("java.") ||
typeFullName.startsWith("sun.") ||
typeFullName.startsWith("jdk.") ||
typeFullName.startsWith("org.w3c.") ||
typeFullName.startsWith("org.xml.") ||
typeFullName.startsWith("javax.xml.")
) {
return true;
}
}
if (["javascript", "js", "ts", "typescript"].includes(language)) {
if (
typeFullName.includes(".js") ||
typeFullName.includes("=>") ||
typeFullName.startsWith("__") ||
typeFullName.startsWith("{ ") ||
typeFullName.startsWith("JSON") ||
typeFullName.startsWith("void:") ||
typeFullName.startsWith("node:")
) {
return true;
}
}
if (["python", "py"].includes(language)) {
if (
typeFullName.startsWith("tmp") ||
typeFullName.startsWith("self.") ||
typeFullName.startsWith("_")
) {
return true;
}
}
if (userDefinedTypesMap[typeFullName]) {
return true;
}
return false;
};
/**
* Method to detect services from annotation objects in the usage slice
*
* @param {string} language Application language
* @param {array} usages Usages array for each objectSlice
* @param {object} servicesMap Existing service map
*/
export const detectServicesFromUsages = (language, slice, servicesMap = {}) => {
const usages = slice.usages;
if (!usages) {
return [];
}
for (const usage of usages) {
const targetObj = usage?.targetObj;
const definedBy = usage?.definedBy;
let endpoints = [];
let authenticated = undefined;
if (targetObj && targetObj?.resolvedMethod) {
endpoints = extractEndpoints(language, targetObj?.resolvedMethod);
if (targetObj?.resolvedMethod.toLowerCase().includes("auth")) {
authenticated = true;
}
} else if (definedBy && definedBy?.resolvedMethod) {
endpoints = extractEndpoints(language, definedBy?.resolvedMethod);
if (definedBy?.resolvedMethod.toLowerCase().includes("auth")) {
authenticated = true;
}
}
if (usage.invokedCalls) {
for (const acall of usage.invokedCalls) {
if (acall.resolvedMethod) {
const tmpEndpoints = extractEndpoints(language, acall.resolvedMethod);
if (acall.resolvedMethod.toLowerCase().includes("auth")) {
authenticated = true;
}
if (tmpEndpoints && tmpEndpoints.length) {
endpoints = (endpoints || []).concat(tmpEndpoints);
}
}
}
}
if (endpoints && endpoints.length) {
const serviceName = constructServiceName(language, slice);
if (!servicesMap[serviceName]) {
servicesMap[serviceName] = {
endpoints: new Set(),
authenticated,
xTrustBoundary: authenticated === true ? true : undefined
};
}
for (const endpoint of endpoints) {
servicesMap[serviceName].endpoints.add(endpoint);
}
}
}
};
/**
* Method to detect services from user defined types in the usage slice
*
* @param {string} language Application language
* @param {array} userDefinedTypes User defined types
* @param {object} servicesMap Existing service map
*/
export const detectServicesFromUDT = (
language,
userDefinedTypes,
servicesMap
) => {
if (
["python", "py"].includes(language) &&
userDefinedTypes &&
userDefinedTypes.length
) {
for (const audt of userDefinedTypes) {
if (
audt.name.includes("route") ||
audt.name.includes("path") ||
audt.name.includes("url")
) {
const fields = audt.fields || [];
if (
fields.length &&
fields[0] &&
fields[0].name &&
fields[0].name.length > 1
) {
const endpoints = extractEndpoints(language, fields[0].name);
let serviceName = "service";
if (audt.fileName) {
serviceName = `${basename(
audt.fileName.replace(".py", "")
)}-service`;
}
if (!servicesMap[serviceName]) {
servicesMap[serviceName] = {
endpoints: new Set(),
authenticated: false,
xTrustBoundary: undefined
};
}
if (endpoints) {
for (const endpoint of endpoints) {
servicesMap[serviceName].endpoints.add(endpoint);
}
}
}
}
}
}
};
export const constructServiceName = (language, slice) => {
let serviceName = "service";
if (slice?.fullName) {
serviceName = slice.fullName.split(":")[0].replace(/\./g, "-");
} else if (slice?.fileName) {
serviceName = path.basename(slice.fileName).split(".")[0];
}
if (!serviceName.endsWith("service")) {
serviceName = serviceName + "-service";
}
return serviceName;
};
export const extractEndpoints = (language, code) => {
if (!code) {
return undefined;
}
let endpoints = undefined;
switch (language) {
case "java":
case "jar":
if (
code.startsWith("@") &&
code.includes("Mapping") &&
code.includes("(")
) {
const matches = code.match(/['"](.*?)['"]/gi) || [];
endpoints = matches
.map((v) => v.replace(/["']/g, ""))
.filter(
(v) =>
v.length &&
!v.startsWith(".") &&
v.includes("/") &&
!v.startsWith("@")
);
}
break;
case "js":
case "ts":
case "javascript":
case "typescript":
if (code.includes("app.") || code.includes("route")) {
const matches = code.match(/['"](.*?)['"]/gi) || [];
endpoints = matches
.map((v) => v.replace(/["']/g, ""))
.filter(
(v) =>
v.length &&
!v.startsWith(".") &&
v.includes("/") &&
!v.startsWith("@") &&
!v.startsWith("application/") &&
!v.startsWith("text/")
);
}
break;
case "py":
case "python":
endpoints = (code.match(/['"](.*?)['"]/gi) || [])
.map((v) => v.replace(/["']/g, "").replace("\n", ""))
.filter((v) => v.length > 2);
break;
default:
break;
}
return endpoints;
};
/**
* Method to create the SBOM with evidence file called evinse file.
*
* @param {object} sliceArtefacts Various artefacts from the slice operation
* @param {object} options Command line options
* @returns
*/
export const createEvinseFile = (sliceArtefacts, options) => {
const {
tempDir,
usagesSlicesFile,
dataFlowSlicesFile,
reachablesSlicesFile,
purlLocationMap,
servicesMap,
dataFlowFrames
} = sliceArtefacts;
const bomFile = options.input;
const evinseOutFile = options.output;
const bomJson = JSON.parse(fs.readFileSync(bomFile, "utf8"));
const components = bomJson.components || [];
let occEvidencePresent = false;
let csEvidencePresent = false;
for (const comp of components) {
if (!comp.purl) {
continue;
}
delete comp.signature;
const locationOccurrences = Array.from(
purlLocationMap[comp.purl] || []
).sort();
if (locationOccurrences.length) {
if (!comp.evidence) {
comp.evidence = {};
}
// This step would replace any existing occurrences
// This is fine as long as the input sbom was also generated by cdxgen
comp.evidence.occurrences = locationOccurrences
.filter((l) => !!l)
.map((l) => ({
location: l
}));
occEvidencePresent = true;
}
const dfFrames = dataFlowFrames[comp.purl];
if (dfFrames && dfFrames.length) {
if (!comp.evidence) {
comp.evidence = {};
}
if (!comp.evidence.callstack) {
comp.evidence.callstack = {};
}
if (!comp.evidence.callstack.frames) {
comp.evidence.callstack.frames = framePicker(dfFrames);
csEvidencePresent = true;
}
}
} // for
if (servicesMap && Object.keys(servicesMap).length) {
const services = [];
for (const serviceName of Object.keys(servicesMap)) {
services.push({
name: serviceName,
endpoints: Array.from(servicesMap[serviceName].endpoints),
authenticated: servicesMap[serviceName].authenticated,
"x-trust-boundary": servicesMap[serviceName].xTrustBoundary
});
}
// Add to existing services
bomJson.services = (bomJson.services || []).concat(services);
}
if (options.annotate) {
if (!bomJson.annotations) {
bomJson.annotations = [];
}
if (usagesSlicesFile && fs.existsSync(usagesSlicesFile)) {
bomJson.annotations.push({
subjects: [bomJson.serialNumber],
annotator: { component: bomJson.metadata.tools.components[0] },
timestamp: new Date().toISOString(),
text: fs.readFileSync(usagesSlicesFile, "utf8")
});
}
if (dataFlowSlicesFile && fs.existsSync(dataFlowSlicesFile)) {
bomJson.annotations.push({
subjects: [bomJson.serialNumber],
annotator: { component: bomJson.metadata.tools.components[0] },
timestamp: new Date().toISOString(),
text: fs.readFileSync(dataFlowSlicesFile, "utf8")
});
}
if (reachablesSlicesFile && fs.existsSync(reachablesSlicesFile)) {
bomJson.annotations.push({
subjects: [bomJson.serialNumber],
annotator: { component: bomJson.metadata.tools.components[0] },
timestamp: new Date().toISOString(),
text: fs.readFileSync(reachablesSlicesFile, "utf8")
});
}
}
// Increment the version
bomJson.version = (bomJson.version || 1) + 1;
// Set the current timestamp to indicate this is newer
bomJson.metadata.timestamp = new Date().toISOString();
delete bomJson.signature;
fs.writeFileSync(evinseOutFile, JSON.stringify(bomJson, null, 2));
if (occEvidencePresent || csEvidencePresent) {
console.log(evinseOutFile, "created successfully.");
} else {
console.log(
"Unable to identify component evidence for the input SBOM. Only java, javascript and python projects are supported by evinse."
);
}
if (tempDir && tempDir.startsWith(tmpdir())) {
fs.rmSync(tempDir, { recursive: true, force: true });
}
return bomJson;
};
/**
* Method to convert dataflow slice into usable callstack frames
* Implemented based on the logic proposed here - https://github.com/AppThreat/atom/blob/main/specification/docs/slices.md#data-flow-slice
*
* @param {string} language Application language