forked from guacsec/trustify-da-java-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageUtils.java
More file actions
529 lines (472 loc) · 18.6 KB
/
ImageUtils.java
File metadata and controls
529 lines (472 loc) · 18.6 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
/*
* Copyright 2023-2025 Trustify Dependency Analytics Authors
*
* 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.
*/
package com.redhat.exhort.image;
import static com.redhat.exhort.image.Platform.EMPTY_PLATFORM;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.github.packageurl.MalformedPackageURLException;
import com.redhat.exhort.tools.Operations;
import com.redhat.exhort.utils.Environment;
import java.io.File;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
public class ImageUtils {
static final String EXHORT_SYFT_CONFIG_PATH = "EXHORT_SYFT_CONFIG_PATH";
static final String EXHORT_SYFT_IMAGE_SOURCE = "EXHORT_SYFT_IMAGE_SOURCE";
static final String EXHORT_IMAGE_PLATFORM = "EXHORT_IMAGE_PLATFORM";
static final String EXHORT_IMAGE_OS = "EXHORT_IMAGE_OS";
static final String EXHORT_IMAGE_ARCH = "EXHORT_IMAGE_ARCH";
static final String EXHORT_IMAGE_VARIANT = "EXHORT_IMAGE_VARIANT";
static final String EXHORT_SKOPEO_CONFIG_PATH = "EXHORT_SKOPEO_CONFIG_PATH";
static final String EXHORT_IMAGE_SERVICE_ENDPOINT = "EXHORT_IMAGE_SERVICE_ENDPOINT";
private static final String MEDIA_TYPE_DOCKER2_MANIFEST =
"application/vnd.docker.distribution.manifest.v2+json";
private static final String MEDIA_TYPE_DOCKER2_MANIFEST_LIST =
"application/vnd.docker.distribution.manifest.list.v2+json";
private static final String MEDIA_TYPE_OCI1_MANIFEST =
"application/vnd.oci.image.manifest.v1+json";
private static final String MEDIA_TYPE_OCI1_MANIFEST_LIST =
"application/vnd.oci.image.index.v1+json";
private static final String DOCKER = "docker";
private static final String PODMAN = "podman";
private static final String SYFT = "syft";
private static final String SKOPEO = "skopeo";
public static final String SKIP_VALIDATION_KEY = "skip.binary.validation";
public static final String ARG_VERSION = "--version";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final Map<String, String> archMapping =
Map.ofEntries(
new AbstractMap.SimpleEntry<>("amd64", "amd64"),
new AbstractMap.SimpleEntry<>("x86_64", "amd64"),
new AbstractMap.SimpleEntry<>("armv5tl", "arm"),
new AbstractMap.SimpleEntry<>("armv5tel", "arm"),
new AbstractMap.SimpleEntry<>("armv5tejl", "arm"),
new AbstractMap.SimpleEntry<>("armv6l", "arm"),
new AbstractMap.SimpleEntry<>("armv7l", "arm"),
new AbstractMap.SimpleEntry<>("armv7ml", "arm"),
new AbstractMap.SimpleEntry<>("arm64", "arm64"),
new AbstractMap.SimpleEntry<>("aarch64", "arm64"),
new AbstractMap.SimpleEntry<>("i386", "386"),
new AbstractMap.SimpleEntry<>("i486", "386"),
new AbstractMap.SimpleEntry<>("i586", "386"),
new AbstractMap.SimpleEntry<>("i686", "386"),
new AbstractMap.SimpleEntry<>("mips64le", "mips64le"),
new AbstractMap.SimpleEntry<>("ppc64le", "ppc64le"),
new AbstractMap.SimpleEntry<>("riscv64", "riscv64"),
new AbstractMap.SimpleEntry<>("s390x", "s390x"));
private static final Map<String, String> variantMapping =
Map.ofEntries(
new AbstractMap.SimpleEntry<>("armv5tl", "v5"),
new AbstractMap.SimpleEntry<>("armv5tel", "v5"),
new AbstractMap.SimpleEntry<>("armv5tejl", "v5"),
new AbstractMap.SimpleEntry<>("armv6l", "v6"),
new AbstractMap.SimpleEntry<>("armv7l", "v7"),
new AbstractMap.SimpleEntry<>("armv7ml", "v7"),
new AbstractMap.SimpleEntry<>("arm64", "v8"),
new AbstractMap.SimpleEntry<>("aarch64", "v8"));
static String updatePATHEnv(String execPath) {
String path = Environment.get("PATH");
if (path != null) {
return String.format("PATH=%s%s%s", path, File.pathSeparator, execPath);
} else {
return String.format("PATH=%s", execPath);
}
}
public static JsonNode generateImageSBOM(ImageRef imageRef)
throws IOException, MalformedPackageURLException {
var output = execSyft(imageRef);
if (!output.getError().isEmpty() || output.getExitCode() != 0) {
throw new RuntimeException(output.getError());
}
var node = OBJECT_MAPPER.readTree(output.getOutput());
if (node.hasNonNull("metadata")) {
var metadataNode = node.get("metadata");
if (metadataNode.hasNonNull("component")) {
var componentNode = metadataNode.get("component");
if (componentNode.isObject()) {
String imagePurl = imageRef.getPackageURL().canonicalize();
((ObjectNode) componentNode).set("purl", new TextNode(imagePurl));
return node;
}
}
}
throw new RuntimeException(
String.format("The generated SBOM of the image is invalid: %s", output.getOutput()));
}
static Operations.ProcessExecOutput execSyft(ImageRef imageRef) {
var syft = Operations.getExecutable(SYFT, ARG_VERSION);
var docker = Operations.getCustomPathOrElse(DOCKER);
var podman = Operations.getCustomPathOrElse(PODMAN);
var syftConfigPath = Environment.get(EXHORT_SYFT_CONFIG_PATH, "");
var imageSource = Environment.get(EXHORT_SYFT_IMAGE_SOURCE, "");
SyftImageSource.getImageSource(imageSource);
var dockerPath =
docker != null && docker.contains(File.separator)
? docker.substring(0, docker.lastIndexOf(File.separator) + 1)
: "";
var podmanPath =
podman != null && podman.contains(File.separator)
? podman.substring(0, podman.lastIndexOf(File.separator) + 1)
: "";
var envs = getSyftEnvs(dockerPath, podmanPath);
var scheme = imageRef.getImage().toString();
String[] cmd;
if (!imageSource.isEmpty()) {
cmd =
syftConfigPath.isEmpty()
? new String[] {
syft,
scheme,
"--from",
imageSource,
"-s",
"all-layers",
"-o",
"cyclonedx-json",
"-q"
}
: new String[] {
syft,
scheme,
"--from",
imageSource,
"-c",
syftConfigPath,
"-s",
"all-layers",
"-o",
"cyclonedx-json",
"-q"
};
} else {
cmd =
syftConfigPath.isEmpty()
? new String[] {syft, scheme, "-s", "all-layers", "-o", "cyclonedx-json", "-q"}
: new String[] {
syft, scheme, "-c", syftConfigPath, "-s", "all-layers", "-o", "cyclonedx-json", "-q"
};
}
return Operations.runProcessGetFullOutput(
null, cmd, envs.isEmpty() ? null : envs.toArray(new String[1]));
}
static List<String> getSyftEnvs(String dockerPath, String podmanPath) {
String path = null;
if (!dockerPath.isEmpty() && !podmanPath.isEmpty()) {
path = String.format("%s%s%s", dockerPath, File.pathSeparator, podmanPath);
} else if (!dockerPath.isEmpty()) {
path = dockerPath;
} else if (!podmanPath.isEmpty()) {
path = podmanPath;
}
return path != null ? List.of(updatePATHEnv(path)) : Collections.emptyList();
}
public static Platform getImagePlatform() {
var platform = Environment.get(EXHORT_IMAGE_PLATFORM, "");
if (!platform.isEmpty()) {
return new Platform(platform);
}
var imageSource = Environment.get(EXHORT_SYFT_IMAGE_SOURCE, "");
SyftImageSource source = SyftImageSource.getImageSource(imageSource);
var os = Environment.get(EXHORT_IMAGE_OS, "");
if (os.isEmpty()) {
os = source.getOs();
}
var arch = Environment.get(EXHORT_IMAGE_ARCH, "");
if (arch.isEmpty()) {
arch = source.getArch();
}
if (!os.isEmpty() && !arch.isEmpty()) {
if (!Platform.isVariantRequired(os, arch)) {
return new Platform(os, arch, null);
}
var variant = Environment.get(EXHORT_IMAGE_VARIANT, "");
if (variant.isEmpty()) {
variant = source.getVariant();
}
if (!variant.isEmpty()) {
return new Platform(os, arch, variant);
}
}
return null;
}
static String hostInfo(String engine, String info) {
var exec = Operations.getCustomPathOrElse(engine);
var cmd = new String[] {exec, "info"};
var output = Operations.runProcessGetFullOutput(null, cmd, null);
if (output.getOutput().isEmpty()
&& (!output.getError().isEmpty() || output.getExitCode() != 0)) {
throw new RuntimeException(output.getError());
}
return output
.getOutput()
.lines()
.filter(line -> line.stripLeading().startsWith(info + ":"))
.map(line -> line.strip().substring(info.length() + 1).strip())
.findAny()
.orElse("");
}
static String dockerGetOs() {
return hostInfo(DOCKER, "OSType");
}
static String dockerGetArch() {
var arch = hostInfo(DOCKER, "Architecture");
arch = archMapping.get(arch);
return Objects.requireNonNullElse(arch, "");
}
static String dockerGetVariant() {
var variant = hostInfo(DOCKER, "Architecture");
variant = variantMapping.get(variant);
return Objects.requireNonNullElse(variant, "");
}
static String podmanGetOs() {
return hostInfo(PODMAN, "os");
}
static String podmanGetArch() {
return hostInfo(PODMAN, "arch");
}
static String podmanGetVariant() {
return hostInfo(PODMAN, "variant");
}
static String dockerPodmanInfo(Supplier<String> dockerSupplier, Supplier<String> podmanSupplier) {
var info = dockerSupplier.get();
if (info.isEmpty()) {
info = podmanSupplier.get();
}
return info;
}
public static Map<Platform, String> getImageDigests(ImageRef imageRef)
throws JsonProcessingException {
var output = execSkopeoInspect(imageRef, true);
if (!output.getError().isEmpty() || output.getExitCode() != 0) {
throw new RuntimeException(output.getError());
}
var node = OBJECT_MAPPER.readTree(output.getOutput());
if (node.hasNonNull("mediaType")) {
var mediaTypeNode = node.get("mediaType");
if (mediaTypeNode.isTextual()) {
var mediaType = mediaTypeNode.asText();
switch (mediaType) {
case MEDIA_TYPE_OCI1_MANIFEST:
case MEDIA_TYPE_DOCKER2_MANIFEST:
return getSingleImageDigest(imageRef);
case MEDIA_TYPE_OCI1_MANIFEST_LIST:
case MEDIA_TYPE_DOCKER2_MANIFEST_LIST:
return getMultiImageDigests(node);
}
}
}
throw new RuntimeException(String.format("The image info is invalid: %s", output.getOutput()));
}
static Map<Platform, String> getMultiImageDigests(JsonNode node) {
if (node.hasNonNull("manifests")) {
var manifestsNode = node.get("manifests");
if (manifestsNode.isArray()) {
return StreamSupport.stream(manifestsNode.spliterator(), false)
.filter(ImageUtils::filterMediaType)
.filter(ImageUtils::filterDigest)
.filter(ImageUtils::filterPlatform)
.collect(
Collectors.toMap(
manifestNode -> {
var platformNode = manifestNode.get("platform");
var arch = platformNode.get("architecture").asText();
var os = platformNode.get("os").asText();
if (platformNode.hasNonNull("variant")) {
var variant = platformNode.get("variant").asText();
return new Platform(String.format("%s/%s/%s", os, arch, variant));
} else {
return new Platform(String.format("%s/%s", os, arch));
}
},
manifestNode -> manifestNode.get("digest").asText()));
}
}
return Collections.emptyMap();
}
static boolean filterMediaType(JsonNode manifestNode) {
if (manifestNode.hasNonNull("mediaType")) {
var mediaTypeNode = manifestNode.get("mediaType");
if (mediaTypeNode.isTextual()) {
var mediaType = mediaTypeNode.asText();
return MEDIA_TYPE_OCI1_MANIFEST.equals(mediaType)
|| MEDIA_TYPE_DOCKER2_MANIFEST.equals(mediaType);
}
}
return false;
}
static boolean filterDigest(JsonNode manifestNode) {
if (manifestNode.hasNonNull("digest")) {
var digestNode = manifestNode.get("digest");
return digestNode.isTextual();
}
return false;
}
static boolean filterPlatform(JsonNode manifestNode) {
if (manifestNode.hasNonNull("platform")) {
var platformNode = manifestNode.get("platform");
if (platformNode.isObject()) {
if (platformNode.hasNonNull("architecture") && platformNode.hasNonNull("os")) {
var architectureNode = platformNode.get("architecture");
var osNode = platformNode.get("os");
if (architectureNode.isTextual() && osNode.isTextual()) {
if (platformNode.hasNonNull("variant")) {
var variantNode = platformNode.get("variant");
if (variantNode.isTextual()) {
try {
new Platform(
String.format(
"%s/%s/%s",
osNode.asText(), architectureNode.asText(), variantNode.asText()));
} catch (IllegalArgumentException e) {
return false;
}
return true;
}
}
try {
new Platform(String.format("%s/%s", osNode.asText(), architectureNode.asText()));
} catch (IllegalArgumentException e) {
return false;
}
return true;
}
}
}
}
return false;
}
static Map<Platform, String> getSingleImageDigest(ImageRef imageRef)
throws JsonProcessingException {
var output = execSkopeoInspect(imageRef, false);
if (!output.getError().isEmpty() || output.getExitCode() != 0) {
throw new RuntimeException(output.getError());
}
var node = OBJECT_MAPPER.readTree(output.getOutput());
if (node.hasNonNull("Digest")) {
var digestNode = node.get("Digest");
if (digestNode.isTextual()) {
return Collections.singletonMap(EMPTY_PLATFORM, digestNode.asText());
}
}
return Collections.emptyMap();
}
static Operations.ProcessExecOutput execSkopeoInspect(ImageRef imageRef, boolean raw) {
var skopeo = Operations.getExecutable(SKOPEO, ARG_VERSION);
var configPath = Environment.get(EXHORT_SKOPEO_CONFIG_PATH, "");
var daemonHost = Environment.get(EXHORT_IMAGE_SERVICE_ENDPOINT, "");
String[] cmd;
if (daemonHost.isEmpty()) {
cmd =
configPath.isEmpty()
? new String[] {
skopeo,
"inspect",
raw ? "--raw" : "",
String.format("docker://%s", imageRef.getImage().getFullName())
}
: new String[] {
skopeo,
"inspect",
"--authfile",
configPath,
raw ? "--raw" : "",
String.format("docker://%s", imageRef.getImage().getFullName())
};
} else {
cmd =
configPath.isEmpty()
? new String[] {
skopeo,
"inspect",
"--daemon-host",
daemonHost,
raw ? "--raw" : "",
String.format("docker-daemon:%s", imageRef.getImage().getFullName())
}
: new String[] {
skopeo,
"inspect",
"--authfile",
configPath,
"--daemon-host",
daemonHost,
raw ? "--raw" : "",
String.format("docker-daemon:%s", imageRef.getImage().getFullName())
};
}
return Operations.runProcessGetFullOutput(null, cmd, null);
}
private enum SyftImageSource {
DEFAULT(
"",
() -> dockerPodmanInfo(ImageUtils::dockerGetOs, ImageUtils::podmanGetOs),
() -> dockerPodmanInfo(ImageUtils::dockerGetArch, ImageUtils::podmanGetArch),
() -> dockerPodmanInfo(ImageUtils::dockerGetVariant, ImageUtils::podmanGetVariant)),
REGISTRY(
"registry",
() -> dockerPodmanInfo(ImageUtils::dockerGetOs, ImageUtils::podmanGetOs),
() -> dockerPodmanInfo(ImageUtils::dockerGetArch, ImageUtils::podmanGetArch),
() -> dockerPodmanInfo(ImageUtils::dockerGetVariant, ImageUtils::podmanGetVariant)),
DOCKER(
"docker", ImageUtils::dockerGetOs, ImageUtils::dockerGetArch, ImageUtils::dockerGetVariant),
PODMAN(
"podman", ImageUtils::podmanGetOs, ImageUtils::podmanGetArch, ImageUtils::podmanGetVariant);
private final String name;
private final Supplier<String> osSupplier;
private final Supplier<String> archSupplier;
private final Supplier<String> variantSupplier;
SyftImageSource(
String name,
Supplier<String> osSupplier,
Supplier<String> archSupplier,
Supplier<String> variantSupplier) {
this.name = name;
this.osSupplier = osSupplier;
this.archSupplier = archSupplier;
this.variantSupplier = variantSupplier;
}
static SyftImageSource getImageSource(String name) {
return EnumSet.allOf(SyftImageSource.class).stream()
.filter(s -> s.name.equals(name))
.findAny()
.orElseThrow(
() ->
new IllegalArgumentException(
String.format("The image source for syft is not valid: %s", name)));
}
String getOs() {
return osSupplier.get();
}
String getArch() {
return archSupplier.get();
}
String getVariant() {
return variantSupplier.get();
}
}
}