Debian Codegraph @

src/analyze/analyze-srk.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <stdio.h>
4 #include <unistd.h>
5
6 #include "alloc-util.h"
7 #include "analyze-srk.h"
8 #include "fileio.h"
9 #include "log.h"
10 #include "terminal-util.h"
11 #include "tpm2-util.h"
12
13 int verb_srk(int argc, char *argv[], uintptr_t _data, void *userdata) {
14 #if HAVE_TPM2
15 _cleanup_(tpm2_context_unrefp) Tpm2Context *c = NULL;
16 _cleanup_(Esys_Freep) TPM2B_PUBLIC *public = NULL;
17 int r;
18
19 r = tpm2_context_new_or_warn(/* device= */ NULL, &c);
20 if (r < 0)
21 return r;
22
23 r = tpm2_get_srk(
24 c,
25 /* session= */ NULL,
26 &public,
27 /* ret_name= */ NULL,
28 /* ret_qname= */ NULL,
29 /* ret_handle= */ NULL);
30 if (r < 0)
31 return log_error_errno(r, "Failed to get SRK: %m");
32 if (r == 0)
33 return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "No SRK stored so far.");
34
35 _cleanup_free_ void *marshalled = NULL;
36 size_t marshalled_size = 0;
37 r = tpm2_marshal_public(public, &marshalled, &marshalled_size);
38 if (r < 0)
39 return log_error_errno(r, "Failed to marshal SRK: %m");
40
41 if (isatty_safe(STDOUT_FILENO))
42 return log_error_errno(SYNTHETIC_ERRNO(EIO),
43 "Refusing to write binary data to TTY, please redirect output to file.");
44
45 if (fwrite(marshalled, 1, marshalled_size, stdout) != marshalled_size)
46 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to write SRK to stdout.");
47
48 r = fflush_and_check(stdout);
49 if (r < 0)
50 return log_error_errno(r, "Failed to write SRK to stdout: %m");
51
52 return EXIT_SUCCESS;
53 #else
54 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM2 support not available.");
55 #endif
56 }