]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/creds-util.c
man/systemd.mount: tmpfs automatically gains After=swap.target dep
[thirdparty/systemd.git] / src / shared / creds-util.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <sys/file.h>
4
5 #if HAVE_OPENSSL
6 #include <openssl/err.h>
7 #endif
8
9 #include "sd-id128.h"
10
11 #include "blockdev-util.h"
12 #include "capability-util.h"
13 #include "chattr-util.h"
14 #include "constants.h"
15 #include "creds-util.h"
16 #include "efi-api.h"
17 #include "env-util.h"
18 #include "fd-util.h"
19 #include "fileio.h"
20 #include "fs-util.h"
21 #include "io-util.h"
22 #include "memory-util.h"
23 #include "mkdir.h"
24 #include "openssl-util.h"
25 #include "parse-util.h"
26 #include "path-util.h"
27 #include "random-util.h"
28 #include "sparse-endian.h"
29 #include "stat-util.h"
30 #include "tpm2-util.h"
31 #include "virt.h"
32
33 #define PUBLIC_KEY_MAX (UINT32_C(1024) * UINT32_C(1024))
34
35 bool credential_name_valid(const char *s) {
36 /* We want that credential names are both valid in filenames (since that's our primary way to pass
37 * them around) and as fdnames (which is how we might want to pass them around eventually) */
38 return filename_is_valid(s) && fdname_is_valid(s);
39 }
40
41 bool credential_glob_valid(const char *s) {
42 const char *e, *a;
43 size_t n;
44
45 /* Checks if a credential glob expression is valid. Note that this is more restrictive than
46 * fnmatch()! We only allow trailing asterisk matches for now (simply because we want some freedom
47 * with automatically extending the pattern in a systematic way to cover for unit instances getting
48 * per-instance credentials or similar. Moreover, credential globbing expressions are also more
49 * restrictive then credential names: we don't allow *, ?, [, ] in them (except for the asterisk
50 * match at the end of the string), simply to not allow ambiguity. After all, we want the flexibility
51 * to one day add full globbing should the need arise. */
52
53 if (isempty(s))
54 return false;
55
56 /* Find first glob (or NUL byte) */
57 n = strcspn(s, "*?[]");
58 e = s + n;
59
60 /* For now, only allow asterisk wildcards, and only at the end of the string. If it's anything else, refuse. */
61 if (isempty(e))
62 return credential_name_valid(s);
63
64 if (!streq(e, "*")) /* only allow trailing "*", no other globs */
65 return false;
66
67 if (n == 0) /* Explicitly allow the complete wildcard. */
68 return true;
69
70 if (n > NAME_MAX + strlen(e)) /* before we make a copy on the stack, let's check this is not overly large */
71 return false;
72
73 /* Make a copy of the string without the '*' suffix */
74 a = strndupa_safe(s, n);
75
76 return credential_name_valid(a);
77 }
78
79 static int get_credentials_dir_internal(const char *envvar, const char **ret) {
80 const char *e;
81
82 assert(ret);
83
84 e = secure_getenv(envvar);
85 if (!e)
86 return -ENXIO;
87
88 if (!path_is_absolute(e) || !path_is_normalized(e))
89 return -EINVAL;
90
91 *ret = e;
92 return 0;
93 }
94
95 int get_credentials_dir(const char **ret) {
96 return get_credentials_dir_internal("CREDENTIALS_DIRECTORY", ret);
97 }
98
99 int get_encrypted_credentials_dir(const char **ret) {
100 return get_credentials_dir_internal("ENCRYPTED_CREDENTIALS_DIRECTORY", ret);
101 }
102
103 int read_credential(const char *name, void **ret, size_t *ret_size) {
104 _cleanup_free_ char *fn = NULL;
105 const char *d;
106 int r;
107
108 assert(ret);
109
110 if (!credential_name_valid(name))
111 return -EINVAL;
112
113 r = get_credentials_dir(&d);
114 if (r < 0)
115 return r;
116
117 fn = path_join(d, name);
118 if (!fn)
119 return -ENOMEM;
120
121 return read_full_file_full(
122 AT_FDCWD, fn,
123 UINT64_MAX, SIZE_MAX,
124 READ_FULL_FILE_SECURE,
125 NULL,
126 (char**) ret, ret_size);
127 }
128
129 int read_credential_with_decryption(const char *name, void **ret, size_t *ret_size) {
130 _cleanup_(erase_and_freep) void *data = NULL;
131 _cleanup_free_ char *fn = NULL;
132 size_t sz = 0;
133 const char *d;
134 int r;
135
136 assert(ret);
137
138 /* Just like read_credential() but will also look for encrypted credentials. Note that services only
139 * receive decrypted credentials, hence use read_credential() for those. This helper here is for
140 * generators, i.e. code that runs outside of service context, and thus has no decrypted credentials
141 * yet.
142 *
143 * Note that read_credential_harder_and_warn() logs on its own, while read_credential() does not!
144 * (It's a lot more complex and error prone given its TPM2 connectivity, and is generally called from
145 * generators only where logging is OK).
146 *
147 * Error handling is also a bit different: if we can't find a credential we'll return 0 and NULL
148 * pointers/zero size, rather than -ENXIO/-ENOENT. */
149
150 if (!credential_name_valid(name))
151 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid credential name: %s", name);
152
153 r = read_credential(name, ret, ret_size);
154 if (r >= 0)
155 return 1; /* found */
156 if (!IN_SET(r, -ENXIO, -ENOENT))
157 return log_error_errno(r, "Failed read unencrypted credential '%s': %m", name);
158
159 r = get_encrypted_credentials_dir(&d);
160 if (r == -ENXIO)
161 goto not_found;
162 if (r < 0)
163 return log_error_errno(r, "Failed to determine encrypted credentials directory: %m");
164
165 fn = path_join(d, name);
166 if (!fn)
167 return log_oom();
168
169 r = read_full_file_full(
170 AT_FDCWD, fn,
171 UINT64_MAX, SIZE_MAX,
172 READ_FULL_FILE_SECURE,
173 NULL,
174 (char**) &data, &sz);
175 if (r == -ENOENT)
176 goto not_found;
177 if (r < 0)
178 return log_error_errno(r, "Failed to read encrypted credential data: %m");
179
180 r = decrypt_credential_and_warn(
181 name,
182 now(CLOCK_REALTIME),
183 /* tpm2_device = */ NULL,
184 /* tpm2_signature_path = */ NULL,
185 data,
186 sz,
187 ret,
188 ret_size);
189 if (r < 0)
190 return r;
191
192 return 1; /* found */
193
194 not_found:
195 *ret = NULL;
196
197 if (ret_size)
198 *ret_size = 0;
199
200 return 0; /* not found */
201 }
202
203 int read_credential_strings_many_internal(
204 const char *first_name, char **first_value,
205 ...) {
206
207 _cleanup_free_ void *b = NULL;
208 int r, ret = 0;
209
210 /* Reads a bunch of credentials into the specified buffers. If the specified buffers are already
211 * non-NULL frees them if a credential is found. Only supports string-based credentials
212 * (i.e. refuses embedded NUL bytes).
213 *
214 * 0 is returned when some or all credentials are missing.
215 */
216
217 if (!first_name)
218 return 0;
219
220 r = read_credential(first_name, &b, NULL);
221 if (r == -ENXIO) /* No creds passed at all? Bail immediately. */
222 return 0;
223 if (r < 0) {
224 if (r != -ENOENT)
225 ret = r;
226 } else
227 free_and_replace(*first_value, b);
228
229 va_list ap;
230 va_start(ap, first_value);
231
232 for (;;) {
233 _cleanup_free_ void *bb = NULL;
234 const char *name;
235 char **value;
236
237 name = va_arg(ap, const char *);
238 if (!name)
239 break;
240
241 value = va_arg(ap, char **);
242 if (*value)
243 continue;
244
245 r = read_credential(name, &bb, NULL);
246 if (r < 0) {
247 if (ret >= 0 && r != -ENOENT)
248 ret = r;
249 } else
250 free_and_replace(*value, bb);
251 }
252
253 va_end(ap);
254 return ret;
255 }
256
257 int read_credential_bool(const char *name) {
258 _cleanup_free_ void *data = NULL;
259 int r;
260
261 r = read_credential(name, &data, NULL);
262 if (r < 0)
263 return IN_SET(r, -ENXIO, -ENOENT) ? 0 : r;
264
265 return parse_boolean(data);
266 }
267
268 int get_credential_user_password(const char *username, char **ret_password, bool *ret_is_hashed) {
269 _cleanup_(erase_and_freep) char *creds_password = NULL;
270 _cleanup_free_ char *cn = NULL;
271 int r;
272
273 /* Try to pick up the password for this account via the credentials logic */
274 cn = strjoin("passwd.hashed-password.", username);
275 if (!cn)
276 return -ENOMEM;
277
278 r = read_credential(cn, (void**) &creds_password, NULL);
279 if (r == -ENOENT) {
280 free(cn);
281 cn = strjoin("passwd.plaintext-password.", username);
282 if (!cn)
283 return -ENOMEM;
284
285 r = read_credential(cn, (void**) &creds_password, NULL);
286 if (r < 0)
287 log_debug_errno(r, "Couldn't read credential '%s', ignoring: %m", cn);
288 else
289 *ret_is_hashed = false;
290 } else if (r < 0)
291 log_debug_errno(r, "Couldn't read credential '%s', ignoring: %m", cn);
292 else
293 *ret_is_hashed = true;
294
295 *ret_password = TAKE_PTR(creds_password);
296
297 return r;
298 }
299
300 #if HAVE_OPENSSL
301
302 #define CREDENTIAL_HOST_SECRET_SIZE 4096
303
304 static const sd_id128_t credential_app_id =
305 SD_ID128_MAKE(d3,ac,ec,ba,0d,ad,4c,df,b8,c9,38,15,28,93,6c,58);
306
307 struct credential_host_secret_format {
308 /* The hashed machine ID of the machine this belongs to. Why? We want to ensure that each machine
309 * gets its own secret, even if people forget to flush out this secret file. Hence we bind it to the
310 * machine ID, for which there's hopefully a better chance it will be flushed out. We use a hashed
311 * machine ID instead of the literal one, because it's trivial to, and it might be a good idea not
312 * being able to directly associate a secret key file with a host. */
313 sd_id128_t machine_id;
314
315 /* The actual secret key */
316 uint8_t data[CREDENTIAL_HOST_SECRET_SIZE];
317 } _packed_;
318
319 static void warn_not_encrypted(int fd, CredentialSecretFlags flags, const char *dirname, const char *filename) {
320 int r;
321
322 assert(fd >= 0);
323 assert(dirname);
324 assert(filename);
325
326 if (!FLAGS_SET(flags, CREDENTIAL_SECRET_WARN_NOT_ENCRYPTED))
327 return;
328
329 r = fd_is_encrypted(fd);
330 if (r < 0)
331 log_debug_errno(r, "Failed to determine if credential secret file '%s/%s' is encrypted.",
332 dirname, filename);
333 else if (r == 0)
334 log_warning("Credential secret file '%s/%s' is not located on encrypted media, using anyway.",
335 dirname, filename);
336 }
337
338 static int make_credential_host_secret(
339 int dfd,
340 const sd_id128_t machine_id,
341 CredentialSecretFlags flags,
342 const char *dirname,
343 const char *fn,
344 void **ret_data,
345 size_t *ret_size) {
346
347 _cleanup_free_ char *t = NULL;
348 _cleanup_close_ int fd = -EBADF;
349 int r;
350
351 assert(dfd >= 0);
352 assert(fn);
353
354 /* For non-root users creating a temporary file using the openat(2) over "." will fail later, in the
355 * linkat(2) step at the end. The reason is that linkat(2) requires the CAP_DAC_READ_SEARCH
356 * capability when it uses the AT_EMPTY_PATH flag. */
357 if (have_effective_cap(CAP_DAC_READ_SEARCH) > 0) {
358 fd = openat(dfd, ".", O_CLOEXEC|O_WRONLY|O_TMPFILE, 0400);
359 if (fd < 0)
360 log_debug_errno(errno, "Failed to create temporary credential file with O_TMPFILE, proceeding without: %m");
361 }
362 if (fd < 0) {
363 if (asprintf(&t, "credential.secret.%016" PRIx64, random_u64()) < 0)
364 return -ENOMEM;
365
366 fd = openat(dfd, t, O_CLOEXEC|O_WRONLY|O_CREAT|O_EXCL|O_NOFOLLOW, 0400);
367 if (fd < 0)
368 return -errno;
369 }
370
371 r = chattr_secret(fd, 0);
372 if (r < 0)
373 log_debug_errno(r, "Failed to set file attributes for secrets file, ignoring: %m");
374
375 struct credential_host_secret_format buf = {
376 .machine_id = machine_id,
377 };
378
379 CLEANUP_ERASE(buf);
380
381 r = crypto_random_bytes(buf.data, sizeof(buf.data));
382 if (r < 0)
383 goto fail;
384
385 r = loop_write(fd, &buf, sizeof(buf));
386 if (r < 0)
387 goto fail;
388
389 if (fsync(fd) < 0) {
390 r = -errno;
391 goto fail;
392 }
393
394 warn_not_encrypted(fd, flags, dirname, fn);
395
396 if (t) {
397 r = rename_noreplace(dfd, t, dfd, fn);
398 if (r < 0)
399 goto fail;
400
401 t = mfree(t);
402 } else if (linkat(fd, "", dfd, fn, AT_EMPTY_PATH) < 0) {
403 r = -errno;
404 goto fail;
405 }
406
407 if (fsync(dfd) < 0) {
408 r = -errno;
409 goto fail;
410 }
411
412 if (ret_data) {
413 void *copy;
414
415 copy = memdup(buf.data, sizeof(buf.data));
416 if (!copy) {
417 r = -ENOMEM;
418 goto fail;
419 }
420
421 *ret_data = copy;
422 }
423
424 if (ret_size)
425 *ret_size = sizeof(buf.data);
426
427 return 0;
428
429 fail:
430 if (t && unlinkat(dfd, t, 0) < 0)
431 log_debug_errno(errno, "Failed to remove temporary credential key: %m");
432
433 return r;
434 }
435
436 int get_credential_host_secret(CredentialSecretFlags flags, void **ret, size_t *ret_size) {
437 _cleanup_free_ char *_dirname = NULL, *_filename = NULL;
438 _cleanup_close_ int dfd = -EBADF;
439 sd_id128_t machine_id;
440 const char *dirname, *filename;
441 int r;
442
443 r = sd_id128_get_machine_app_specific(credential_app_id, &machine_id);
444 if (r < 0)
445 return r;
446
447 const char *e = secure_getenv("SYSTEMD_CREDENTIAL_SECRET");
448 if (e) {
449 if (!path_is_normalized(e))
450 return -EINVAL;
451 if (!path_is_absolute(e))
452 return -EINVAL;
453
454 r = path_extract_directory(e, &_dirname);
455 if (r < 0)
456 return r;
457
458 r = path_extract_filename(e, &_filename);
459 if (r < 0)
460 return r;
461
462 dirname = _dirname;
463 filename = _filename;
464 } else {
465 dirname = "/var/lib/systemd";
466 filename = "credential.secret";
467 }
468
469 assert(dirname);
470 assert(filename);
471
472 mkdir_parents(dirname, 0755);
473 dfd = open_mkdir_at(AT_FDCWD, dirname, O_CLOEXEC, 0755);
474 if (dfd < 0)
475 return log_debug_errno(dfd, "Failed to create or open directory '%s': %m", dirname);
476
477 if (FLAGS_SET(flags, CREDENTIAL_SECRET_FAIL_ON_TEMPORARY_FS)) {
478 r = fd_is_temporary_fs(dfd);
479 if (r < 0)
480 return log_debug_errno(r, "Failed to check directory '%s': %m", dirname);
481 if (r > 0)
482 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM),
483 "Directory '%s' is on a temporary file system, refusing.", dirname);
484 }
485
486 for (unsigned attempt = 0;; attempt++) {
487 _cleanup_(erase_and_freep) struct credential_host_secret_format *f = NULL;
488 _cleanup_close_ int fd = -EBADF;
489 size_t l = 0;
490 ssize_t n = 0;
491 struct stat st;
492
493 if (attempt >= 3) /* Somebody is playing games with us */
494 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
495 "All attempts to create secret store in %s failed.", dirname);
496
497 fd = openat(dfd, filename, O_CLOEXEC|O_RDONLY|O_NOCTTY|O_NOFOLLOW);
498 if (fd < 0) {
499 if (errno != ENOENT || !FLAGS_SET(flags, CREDENTIAL_SECRET_GENERATE))
500 return log_debug_errno(errno,
501 "Failed to open %s/%s: %m", dirname, filename);
502
503
504 r = make_credential_host_secret(dfd, machine_id, flags, dirname, filename, ret, ret_size);
505 if (r == -EEXIST) {
506 log_debug_errno(r, "Credential secret %s/%s appeared while we were creating it, rereading.",
507 dirname, filename);
508 continue;
509 }
510 if (r < 0)
511 return log_debug_errno(r, "Failed to create credential secret %s/%s: %m",
512 dirname, filename);
513 return 0;
514 }
515
516 if (fstat(fd, &st) < 0)
517 return log_debug_errno(errno, "Failed to stat %s/%s: %m", dirname, filename);
518
519 r = stat_verify_regular(&st);
520 if (r < 0)
521 return log_debug_errno(r, "%s/%s is not a regular file: %m", dirname, filename);
522 if (st.st_nlink == 0) /* Deleted by now, try again */
523 continue;
524 if (st.st_nlink > 1)
525 /* Our deletion check won't work if hardlinked somewhere else */
526 return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
527 "%s/%s has too many links, refusing.",
528 dirname, filename);
529 if ((st.st_mode & 07777) != 0400)
530 /* Don't use file if not 0400 access mode */
531 return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
532 "%s/%s has permissive access mode, refusing.",
533 dirname, filename);
534 l = st.st_size;
535 if (l < offsetof(struct credential_host_secret_format, data) + 1)
536 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
537 "%s/%s is too small, refusing.", dirname, filename);
538 if (l > 16*1024*1024)
539 return log_debug_errno(SYNTHETIC_ERRNO(E2BIG),
540 "%s/%s is too big, refusing.", dirname, filename);
541
542 f = malloc(l+1);
543 if (!f)
544 return log_oom_debug();
545
546 n = read(fd, f, l+1);
547 if (n < 0)
548 return log_debug_errno(errno,
549 "Failed to read %s/%s: %m", dirname, filename);
550 if ((size_t) n != l) /* What? The size changed? */
551 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
552 "Failed to read %s/%s: %m", dirname, filename);
553
554 if (sd_id128_equal(machine_id, f->machine_id)) {
555 size_t sz;
556
557 warn_not_encrypted(fd, flags, dirname, filename);
558
559 sz = l - offsetof(struct credential_host_secret_format, data);
560 assert(sz > 0);
561
562 if (ret) {
563 void *copy;
564
565 assert(sz <= sizeof(f->data)); /* Ensure we don't read past f->data bounds */
566
567 copy = memdup(f->data, sz);
568 if (!copy)
569 return log_oom_debug();
570
571 *ret = copy;
572 }
573
574 if (ret_size)
575 *ret_size = sz;
576
577 return 0;
578 }
579
580 /* Hmm, this secret is from somewhere else. Let's delete the file. Let's first acquire a lock
581 * to ensure we are the only ones accessing the file while we delete it. */
582
583 if (flock(fd, LOCK_EX) < 0)
584 return log_debug_errno(errno,
585 "Failed to flock %s/%s: %m", dirname, filename);
586
587 /* Before we delete it check that the file is still linked into the file system */
588 if (fstat(fd, &st) < 0)
589 return log_debug_errno(errno, "Failed to stat %s/%s: %m", dirname, filename);
590 if (st.st_nlink == 0) /* Already deleted by now? */
591 continue;
592 if (st.st_nlink != 1) /* Safety check, someone is playing games with us */
593 return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
594 "%s/%s unexpectedly has too many links.",
595 dirname, filename);
596 if (unlinkat(dfd, filename, 0) < 0)
597 return log_debug_errno(errno, "Failed to unlink %s/%s: %m", dirname, filename);
598
599 /* And now try again */
600 }
601 }
602
603 /* Construction is like this:
604 *
605 * A symmetric encryption key is derived from:
606 *
607 * 1. Either the "host" key (a key stored in /var/lib/credential.secret)
608 *
609 * 2. A key generated by letting the TPM2 calculate an HMAC hash of some nonce we pass to it, keyed
610 * by a key derived from its internal seed key.
611 *
612 * 3. The concatenation of the above.
613 *
614 * 4. Or a fixed "empty" key. This will not provide confidentiality or authenticity, of course, but is
615 * useful to encode credentials for the initrd on TPM-less systems, where we simply have no better
616 * concept to bind things to. Note that decryption of a key set up like this will be refused on
617 * systems that have a TPM and have SecureBoot enabled.
618 *
619 * The above is hashed with SHA256 which is then used as encryption key for AES256-GCM. The encrypted
620 * credential is a short (unencrypted) header describing which of the three keys to use, the IV to use for
621 * AES256-GCM and some more meta information (sizes of certain objects) that is strictly speaking redundant,
622 * but kinda nice to have since we can have a more generic parser. If the TPM2 key is used this is followed
623 * by another (unencrypted) header, with information about the TPM2 policy used (specifically: the PCR mask
624 * to bind against, and a hash of the resulting policy — the latter being redundant, but speeding up things a
625 * bit, since we can more quickly refuse PCR state), followed by a sealed/exported TPM2 HMAC key. This is
626 * then followed by the encrypted data, which begins with a metadata header (which contains validity
627 * timestamps as well as the credential name), followed by the actual credential payload. The file ends in
628 * the AES256-GCM tag. To make things simple, the AES256-GCM AAD covers the main and the TPM2 header in
629 * full. This means the whole file is either protected by AAD, or is ciphertext, or is the tag. No
630 * unprotected data is included.
631 */
632
633 struct _packed_ encrypted_credential_header {
634 sd_id128_t id;
635 le32_t key_size;
636 le32_t block_size;
637 le32_t iv_size;
638 le32_t tag_size;
639 uint8_t iv[];
640 /* Followed by NUL bytes until next 8 byte boundary */
641 };
642
643 struct _packed_ tpm2_credential_header {
644 le64_t pcr_mask; /* Note that the spec for PC Clients only mandates 24 PCRs, and that's what systems
645 * generally have. But keep the door open for more. */
646 le16_t pcr_bank; /* For now, either TPM2_ALG_SHA256 or TPM2_ALG_SHA1 */
647 le16_t primary_alg; /* Primary key algorithm (either TPM2_ALG_RSA or TPM2_ALG_ECC for now) */
648 le32_t blob_size;
649 le32_t policy_hash_size;
650 uint8_t policy_hash_and_blob[];
651 /* Followed by NUL bytes until next 8 byte boundary */
652 };
653
654 struct _packed_ tpm2_public_key_credential_header {
655 le64_t pcr_mask; /* PCRs used for the public key PCR policy (usually just PCR 11, i.e. the unified kernel) */
656 le32_t size; /* Size of DER public key */
657 uint8_t data[]; /* DER public key */
658 /* Followed by NUL bytes until next 8 byte boundary */
659 };
660
661 struct _packed_ metadata_credential_header {
662 le64_t timestamp;
663 le64_t not_after;
664 le32_t name_size;
665 char name[];
666 /* Followed by NUL bytes until next 8 byte boundary */
667 };
668
669 /* Some generic limit for parts of the encrypted credential for which we don't know the right size ahead of
670 * time, but where we are really sure it won't be larger than this. Should be larger than any possible IV,
671 * padding, tag size and so on. This is purely used for early filtering out of invalid sizes. */
672 #define CREDENTIAL_FIELD_SIZE_MAX (16U*1024U)
673
674 static int sha256_hash_host_and_tpm2_key(
675 const void *host_key,
676 size_t host_key_size,
677 const void *tpm2_key,
678 size_t tpm2_key_size,
679 uint8_t ret[static SHA256_DIGEST_LENGTH]) {
680
681 _cleanup_(EVP_MD_CTX_freep) EVP_MD_CTX *md = NULL;
682 unsigned l;
683
684 assert(host_key_size == 0 || host_key);
685 assert(tpm2_key_size == 0 || tpm2_key);
686 assert(ret);
687
688 /* Combines the host key and the TPM2 HMAC hash into a SHA256 hash value we'll use as symmetric encryption key. */
689
690 md = EVP_MD_CTX_new();
691 if (!md)
692 return log_oom();
693
694 if (EVP_DigestInit_ex(md, EVP_sha256(), NULL) != 1)
695 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initial SHA256 context.");
696
697 if (host_key && EVP_DigestUpdate(md, host_key, host_key_size) != 1)
698 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to hash host key.");
699
700 if (tpm2_key && EVP_DigestUpdate(md, tpm2_key, tpm2_key_size) != 1)
701 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to hash TPM2 key.");
702
703 assert(EVP_MD_CTX_size(md) == SHA256_DIGEST_LENGTH);
704
705 if (EVP_DigestFinal_ex(md, ret, &l) != 1)
706 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to finalize SHA256 hash.");
707
708 assert(l == SHA256_DIGEST_LENGTH);
709 return 0;
710 }
711
712 int encrypt_credential_and_warn(
713 sd_id128_t with_key,
714 const char *name,
715 usec_t timestamp,
716 usec_t not_after,
717 const char *tpm2_device,
718 uint32_t tpm2_hash_pcr_mask,
719 const char *tpm2_pubkey_path,
720 uint32_t tpm2_pubkey_pcr_mask,
721 const void *input,
722 size_t input_size,
723 void **ret,
724 size_t *ret_size) {
725
726 _cleanup_(EVP_CIPHER_CTX_freep) EVP_CIPHER_CTX *context = NULL;
727 _cleanup_(erase_and_freep) void *host_key = NULL, *tpm2_key = NULL;
728 size_t host_key_size = 0, tpm2_key_size = 0, tpm2_blob_size = 0, tpm2_policy_hash_size = 0, output_size, p, ml;
729 _cleanup_free_ void *tpm2_blob = NULL, *tpm2_policy_hash = NULL, *iv = NULL, *output = NULL;
730 _cleanup_free_ struct metadata_credential_header *m = NULL;
731 uint16_t tpm2_pcr_bank = 0, tpm2_primary_alg = 0;
732 struct encrypted_credential_header *h;
733 int ksz, bsz, ivsz, tsz, added, r;
734 _cleanup_free_ void *pubkey = NULL;
735 size_t pubkey_size = 0;
736 uint8_t md[SHA256_DIGEST_LENGTH];
737 const EVP_CIPHER *cc;
738 sd_id128_t id;
739
740 assert(input || input_size == 0);
741 assert(ret);
742 assert(ret_size);
743
744 if (!sd_id128_in_set(with_key,
745 _CRED_AUTO,
746 _CRED_AUTO_INITRD,
747 CRED_AES256_GCM_BY_HOST,
748 CRED_AES256_GCM_BY_TPM2_HMAC,
749 CRED_AES256_GCM_BY_TPM2_HMAC_WITH_PK,
750 CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC,
751 CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK,
752 CRED_AES256_GCM_BY_TPM2_ABSENT))
753 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid key type: " SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(with_key));
754
755 if (name && !credential_name_valid(name))
756 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid credential name: %s", name);
757
758 if (not_after != USEC_INFINITY && timestamp != USEC_INFINITY && not_after < timestamp)
759 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Credential is invalidated before it is valid (" USEC_FMT " < " USEC_FMT ").", not_after, timestamp);
760
761 if (DEBUG_LOGGING) {
762 char buf[FORMAT_TIMESTAMP_MAX];
763
764 if (name)
765 log_debug("Including credential name '%s' in encrypted credential.", name);
766 if (timestamp != USEC_INFINITY)
767 log_debug("Including timestamp '%s' in encrypted credential.", format_timestamp(buf, sizeof(buf), timestamp));
768 if (not_after != USEC_INFINITY)
769 log_debug("Including not-after timestamp '%s' in encrypted credential.", format_timestamp(buf, sizeof(buf), not_after));
770 }
771
772 if (sd_id128_in_set(with_key,
773 _CRED_AUTO,
774 CRED_AES256_GCM_BY_HOST,
775 CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC,
776 CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK)) {
777
778 r = get_credential_host_secret(
779 CREDENTIAL_SECRET_GENERATE|
780 CREDENTIAL_SECRET_WARN_NOT_ENCRYPTED|
781 (sd_id128_equal(with_key, _CRED_AUTO) ? CREDENTIAL_SECRET_FAIL_ON_TEMPORARY_FS : 0),
782 &host_key,
783 &host_key_size);
784 if (r == -ENOMEDIUM && sd_id128_equal(with_key, _CRED_AUTO))
785 log_debug_errno(r, "Credential host secret location on temporary file system, not using.");
786 else if (r < 0)
787 return log_error_errno(r, "Failed to determine local credential host secret: %m");
788 }
789
790 #if HAVE_TPM2
791 bool try_tpm2;
792 if (sd_id128_in_set(with_key, _CRED_AUTO, _CRED_AUTO_INITRD)) {
793 /* If automatic mode is selected lets see if a TPM2 it is present. If we are running in a
794 * container tpm2_support will detect this, and will return a different flag combination of
795 * TPM2_SUPPORT_FULL, effectively skipping the use of TPM2 when inside one. */
796
797 try_tpm2 = tpm2_support() == TPM2_SUPPORT_FULL;
798 if (!try_tpm2)
799 log_debug("System lacks TPM2 support or running in a container, not attempting to use TPM2.");
800 } else
801 try_tpm2 = sd_id128_in_set(with_key,
802 CRED_AES256_GCM_BY_TPM2_HMAC,
803 CRED_AES256_GCM_BY_TPM2_HMAC_WITH_PK,
804 CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC,
805 CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK);
806
807 if (try_tpm2) {
808 if (sd_id128_in_set(with_key,
809 _CRED_AUTO,
810 _CRED_AUTO_INITRD,
811 CRED_AES256_GCM_BY_TPM2_HMAC_WITH_PK,
812 CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK)) {
813
814 /* Load public key for PCR policies, if one is specified, or explicitly requested */
815
816 r = tpm2_load_pcr_public_key(tpm2_pubkey_path, &pubkey, &pubkey_size);
817 if (r < 0) {
818 if (tpm2_pubkey_path || r != -ENOENT || !sd_id128_in_set(with_key, _CRED_AUTO, _CRED_AUTO_INITRD))
819 return log_error_errno(r, "Failed read TPM PCR public key: %m");
820
821 log_debug_errno(r, "Failed to read TPM2 PCR public key, proceeding without: %m");
822 }
823 }
824
825 if (!pubkey)
826 tpm2_pubkey_pcr_mask = 0;
827
828 _cleanup_(tpm2_context_unrefp) Tpm2Context *tpm2_context = NULL;
829 r = tpm2_context_new(tpm2_device, &tpm2_context);
830 if (r < 0)
831 return log_error_errno(r, "Failed to create TPM2 context: %m");
832
833 r = tpm2_get_best_pcr_bank(tpm2_context, tpm2_hash_pcr_mask | tpm2_pubkey_pcr_mask, &tpm2_pcr_bank);
834 if (r < 0)
835 return log_error_errno(r, "Could not find best pcr bank: %m");
836
837 TPML_PCR_SELECTION tpm2_hash_pcr_selection;
838 tpm2_tpml_pcr_selection_from_mask(tpm2_hash_pcr_mask, tpm2_pcr_bank, &tpm2_hash_pcr_selection);
839
840 _cleanup_free_ Tpm2PCRValue *tpm2_hash_pcr_values = NULL;
841 size_t tpm2_n_hash_pcr_values;
842 r = tpm2_pcr_read(tpm2_context, &tpm2_hash_pcr_selection, &tpm2_hash_pcr_values, &tpm2_n_hash_pcr_values);
843 if (r < 0)
844 return log_error_errno(r, "Could not read PCR values: %m");
845
846 TPM2B_PUBLIC public;
847 if (pubkey) {
848 r = tpm2_tpm2b_public_from_pem(pubkey, pubkey_size, &public);
849 if (r < 0)
850 return log_error_errno(r, "Could not convert public key to TPM2B_PUBLIC: %m");
851 }
852
853 TPM2B_DIGEST tpm2_policy = TPM2B_DIGEST_MAKE(NULL, TPM2_SHA256_DIGEST_SIZE);
854 r = tpm2_calculate_sealing_policy(
855 tpm2_hash_pcr_values,
856 tpm2_n_hash_pcr_values,
857 pubkey ? &public : NULL,
858 /* use_pin= */ false,
859 /* pcrlock_policy= */ NULL,
860 &tpm2_policy);
861 if (r < 0)
862 return log_error_errno(r, "Could not calculate sealing policy digest: %m");
863
864 r = tpm2_seal(tpm2_context,
865 /* seal_key_handle= */ 0,
866 &tpm2_policy,
867 /* pin= */ NULL,
868 &tpm2_key, &tpm2_key_size,
869 &tpm2_blob, &tpm2_blob_size,
870 &tpm2_primary_alg,
871 /* ret_srk_buf= */ NULL,
872 /* ret_srk_buf_size= */ NULL);
873 if (r < 0) {
874 if (sd_id128_equal(with_key, _CRED_AUTO_INITRD))
875 log_warning("TPM2 present and used, but we didn't manage to talk to it. Credential will be refused if SecureBoot is enabled.");
876 else if (!sd_id128_equal(with_key, _CRED_AUTO))
877 return log_error_errno(r, "Failed to seal to TPM2: %m");
878
879 log_notice_errno(r, "TPM2 sealing didn't work, continuing without TPM2: %m");
880 }
881
882 tpm2_policy_hash_size = tpm2_policy.size;
883 tpm2_policy_hash = malloc(tpm2_policy_hash_size);
884 if (!tpm2_policy_hash)
885 return log_oom();
886 memcpy(tpm2_policy_hash, tpm2_policy.buffer, tpm2_policy_hash_size);
887
888 assert(tpm2_blob_size <= CREDENTIAL_FIELD_SIZE_MAX);
889 assert(tpm2_policy_hash_size <= CREDENTIAL_FIELD_SIZE_MAX);
890 }
891 #endif
892
893 if (sd_id128_in_set(with_key, _CRED_AUTO, _CRED_AUTO_INITRD)) {
894 /* Let's settle the key type in auto mode now. */
895
896 if (host_key && tpm2_key)
897 id = pubkey ? CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK : CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC;
898 else if (tpm2_key)
899 id = pubkey ? CRED_AES256_GCM_BY_TPM2_HMAC_WITH_PK : CRED_AES256_GCM_BY_TPM2_HMAC;
900 else if (host_key)
901 id = CRED_AES256_GCM_BY_HOST;
902 else if (sd_id128_equal(with_key, _CRED_AUTO_INITRD))
903 id = CRED_AES256_GCM_BY_TPM2_ABSENT;
904 else
905 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
906 "TPM2 not available and host key located on temporary file system, no encryption key available.");
907 } else
908 id = with_key;
909
910 if (sd_id128_equal(id, CRED_AES256_GCM_BY_TPM2_ABSENT))
911 log_warning("Using a null key for encryption and signing. Confidentiality or authenticity will not be provided.");
912
913 /* Let's now take the host key and the TPM2 key and hash it together, to use as encryption key for the data */
914 r = sha256_hash_host_and_tpm2_key(host_key, host_key_size, tpm2_key, tpm2_key_size, md);
915 if (r < 0)
916 return r;
917
918 assert_se(cc = EVP_aes_256_gcm());
919
920 ksz = EVP_CIPHER_key_length(cc);
921 assert(ksz == sizeof(md));
922
923 bsz = EVP_CIPHER_block_size(cc);
924 assert(bsz > 0);
925 assert((size_t) bsz <= CREDENTIAL_FIELD_SIZE_MAX);
926
927 ivsz = EVP_CIPHER_iv_length(cc);
928 if (ivsz > 0) {
929 assert((size_t) ivsz <= CREDENTIAL_FIELD_SIZE_MAX);
930
931 iv = malloc(ivsz);
932 if (!iv)
933 return log_oom();
934
935 r = crypto_random_bytes(iv, ivsz);
936 if (r < 0)
937 return log_error_errno(r, "Failed to acquired randomized IV: %m");
938 }
939
940 tsz = 16; /* FIXME: On OpenSSL 3 there is EVP_CIPHER_CTX_get_tag_length(), until then let's hardcode this */
941
942 context = EVP_CIPHER_CTX_new();
943 if (!context)
944 return log_error_errno(SYNTHETIC_ERRNO(ENOMEM), "Failed to allocate encryption object: %s",
945 ERR_error_string(ERR_get_error(), NULL));
946
947 if (EVP_EncryptInit_ex(context, cc, NULL, md, iv) != 1)
948 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initialize encryption context: %s",
949 ERR_error_string(ERR_get_error(), NULL));
950
951 /* Just an upper estimate */
952 output_size =
953 ALIGN8(offsetof(struct encrypted_credential_header, iv) + ivsz) +
954 ALIGN8(tpm2_key ? offsetof(struct tpm2_credential_header, policy_hash_and_blob) + tpm2_blob_size + tpm2_policy_hash_size : 0) +
955 ALIGN8(pubkey ? offsetof(struct tpm2_public_key_credential_header, data) + pubkey_size : 0) +
956 ALIGN8(offsetof(struct metadata_credential_header, name) + strlen_ptr(name)) +
957 input_size + 2U * (size_t) bsz +
958 tsz;
959
960 output = malloc0(output_size);
961 if (!output)
962 return log_oom();
963
964 h = (struct encrypted_credential_header*) output;
965 h->id = id;
966 h->block_size = htole32(bsz);
967 h->key_size = htole32(ksz);
968 h->tag_size = htole32(tsz);
969 h->iv_size = htole32(ivsz);
970 memcpy(h->iv, iv, ivsz);
971
972 p = ALIGN8(offsetof(struct encrypted_credential_header, iv) + ivsz);
973
974 if (tpm2_key) {
975 struct tpm2_credential_header *t;
976
977 t = (struct tpm2_credential_header*) ((uint8_t*) output + p);
978 t->pcr_mask = htole64(tpm2_hash_pcr_mask);
979 t->pcr_bank = htole16(tpm2_pcr_bank);
980 t->primary_alg = htole16(tpm2_primary_alg);
981 t->blob_size = htole32(tpm2_blob_size);
982 t->policy_hash_size = htole32(tpm2_policy_hash_size);
983 memcpy(t->policy_hash_and_blob, tpm2_blob, tpm2_blob_size);
984 memcpy(t->policy_hash_and_blob + tpm2_blob_size, tpm2_policy_hash, tpm2_policy_hash_size);
985
986 p += ALIGN8(offsetof(struct tpm2_credential_header, policy_hash_and_blob) + tpm2_blob_size + tpm2_policy_hash_size);
987 }
988
989 if (pubkey) {
990 struct tpm2_public_key_credential_header *z;
991
992 z = (struct tpm2_public_key_credential_header*) ((uint8_t*) output + p);
993 z->pcr_mask = htole64(tpm2_pubkey_pcr_mask);
994 z->size = htole32(pubkey_size);
995 memcpy(z->data, pubkey, pubkey_size);
996
997 p += ALIGN8(offsetof(struct tpm2_public_key_credential_header, data) + pubkey_size);
998 }
999
1000 /* Pass the encrypted + TPM2 header as AAD */
1001 if (EVP_EncryptUpdate(context, NULL, &added, output, p) != 1)
1002 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to write AAD data: %s",
1003 ERR_error_string(ERR_get_error(), NULL));
1004
1005 /* Now construct the metadata header */
1006 ml = strlen_ptr(name);
1007 m = malloc0(ALIGN8(offsetof(struct metadata_credential_header, name) + ml));
1008 if (!m)
1009 return log_oom();
1010
1011 m->timestamp = htole64(timestamp);
1012 m->not_after = htole64(not_after);
1013 m->name_size = htole32(ml);
1014 memcpy_safe(m->name, name, ml);
1015
1016 /* And encrypt the metadata header */
1017 if (EVP_EncryptUpdate(context, (uint8_t*) output + p, &added, (const unsigned char*) m, ALIGN8(offsetof(struct metadata_credential_header, name) + ml)) != 1)
1018 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to encrypt metadata header: %s",
1019 ERR_error_string(ERR_get_error(), NULL));
1020
1021 assert(added >= 0);
1022 assert((size_t) added <= output_size - p);
1023 p += added;
1024
1025 /* Then encrypt the plaintext */
1026 if (EVP_EncryptUpdate(context, (uint8_t*) output + p, &added, input, input_size) != 1)
1027 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to encrypt data: %s",
1028 ERR_error_string(ERR_get_error(), NULL));
1029
1030 assert(added >= 0);
1031 assert((size_t) added <= output_size - p);
1032 p += added;
1033
1034 /* Finalize */
1035 if (EVP_EncryptFinal_ex(context, (uint8_t*) output + p, &added) != 1)
1036 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to finalize data encryption: %s",
1037 ERR_error_string(ERR_get_error(), NULL));
1038
1039 assert(added >= 0);
1040 assert((size_t) added <= output_size - p);
1041 p += added;
1042
1043 assert(p <= output_size - tsz);
1044
1045 /* Append tag */
1046 if (EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_GCM_GET_TAG, tsz, (uint8_t*) output + p) != 1)
1047 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to get tag: %s",
1048 ERR_error_string(ERR_get_error(), NULL));
1049
1050 p += tsz;
1051 assert(p <= output_size);
1052
1053 if (DEBUG_LOGGING && input_size > 0) {
1054 size_t base64_size;
1055
1056 base64_size = DIV_ROUND_UP(p * 4, 3); /* Include base64 size increase in debug output */
1057 assert(base64_size >= input_size);
1058 log_debug("Input of %zu bytes grew to output of %zu bytes (+%2zu%%).", input_size, base64_size, base64_size * 100 / input_size - 100);
1059 }
1060
1061 *ret = TAKE_PTR(output);
1062 *ret_size = p;
1063
1064 return 0;
1065 }
1066
1067 int decrypt_credential_and_warn(
1068 const char *validate_name,
1069 usec_t validate_timestamp,
1070 const char *tpm2_device,
1071 const char *tpm2_signature_path,
1072 const void *input,
1073 size_t input_size,
1074 void **ret,
1075 size_t *ret_size) {
1076
1077 _cleanup_(erase_and_freep) void *host_key = NULL, *tpm2_key = NULL, *plaintext = NULL;
1078 _cleanup_(json_variant_unrefp) JsonVariant *signature_json = NULL;
1079 _cleanup_(EVP_CIPHER_CTX_freep) EVP_CIPHER_CTX *context = NULL;
1080 size_t host_key_size = 0, tpm2_key_size = 0, plaintext_size, p, hs;
1081 struct encrypted_credential_header *h;
1082 struct metadata_credential_header *m;
1083 uint8_t md[SHA256_DIGEST_LENGTH];
1084 bool with_tpm2, with_host_key, is_tpm2_absent, with_tpm2_pk;
1085 const EVP_CIPHER *cc;
1086 int r, added;
1087
1088 assert(input || input_size == 0);
1089 assert(ret);
1090 assert(ret_size);
1091
1092 h = (struct encrypted_credential_header*) input;
1093
1094 /* The ID must fit in, for the current and all future formats */
1095 if (input_size < sizeof(h->id))
1096 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
1097
1098 with_host_key = sd_id128_in_set(h->id, CRED_AES256_GCM_BY_HOST, CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC, CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK);
1099 with_tpm2_pk = sd_id128_in_set(h->id, CRED_AES256_GCM_BY_TPM2_HMAC_WITH_PK, CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK);
1100 with_tpm2 = sd_id128_in_set(h->id, CRED_AES256_GCM_BY_TPM2_HMAC, CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC) || with_tpm2_pk;
1101 is_tpm2_absent = sd_id128_equal(h->id, CRED_AES256_GCM_BY_TPM2_ABSENT);
1102
1103 if (!with_host_key && !with_tpm2 && !is_tpm2_absent)
1104 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Unknown encryption format, or corrupted data: %m");
1105
1106 if (with_tpm2_pk) {
1107 r = tpm2_load_pcr_signature(tpm2_signature_path, &signature_json);
1108 if (r < 0)
1109 return log_error_errno(r, "Failed to load pcr signature: %m");
1110 }
1111
1112 if (is_tpm2_absent) {
1113 /* So this is a credential encrypted with a zero length key. We support this to cover for the
1114 * case where neither a host key not a TPM2 are available (specifically: initrd environments
1115 * where the host key is not yet accessible and no TPM2 chip exists at all), to minimize
1116 * different codeflow for TPM2 and non-TPM2 codepaths. Of course, credentials encoded this
1117 * way offer no confidentiality nor authenticity. Because of that it's important we refuse to
1118 * use them on systems that actually *do* have a TPM2 chip – if we are in SecureBoot
1119 * mode. Otherwise an attacker could hand us credentials like this and we'd use them thinking
1120 * they are trusted, even though they are not. */
1121
1122 if (efi_has_tpm2()) {
1123 if (is_efi_secure_boot())
1124 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG),
1125 "Credential uses fixed key for fallback use when TPM2 is absent — but TPM2 is present, and SecureBoot is enabled, refusing.");
1126
1127 log_warning("Credential uses fixed key for use when TPM2 is absent, but TPM2 is present! Accepting anyway, since SecureBoot is disabled.");
1128 } else
1129 log_debug("Credential uses fixed key for use when TPM2 is absent, and TPM2 indeed is absent. Accepting.");
1130 }
1131
1132 /* Now we know the minimum header size */
1133 if (input_size < offsetof(struct encrypted_credential_header, iv))
1134 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
1135
1136 /* Verify some basic header values */
1137 if (le32toh(h->key_size) != sizeof(md))
1138 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected key size in header.");
1139 if (le32toh(h->block_size) <= 0 || le32toh(h->block_size) > CREDENTIAL_FIELD_SIZE_MAX)
1140 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected block size in header.");
1141 if (le32toh(h->iv_size) > CREDENTIAL_FIELD_SIZE_MAX)
1142 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "IV size too large.");
1143 if (le32toh(h->tag_size) != 16) /* FIXME: On OpenSSL 3, let's verify via EVP_CIPHER_CTX_get_tag_length() */
1144 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected tag size in header.");
1145
1146 /* Ensure we have space for the full header now (we don't know the size of the name hence this is a
1147 * lower limit only) */
1148 if (input_size <
1149 ALIGN8(offsetof(struct encrypted_credential_header, iv) + le32toh(h->iv_size)) +
1150 ALIGN8(with_tpm2 ? offsetof(struct tpm2_credential_header, policy_hash_and_blob) : 0) +
1151 ALIGN8(with_tpm2_pk ? offsetof(struct tpm2_public_key_credential_header, data) : 0) +
1152 ALIGN8(offsetof(struct metadata_credential_header, name)) +
1153 le32toh(h->tag_size))
1154 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
1155
1156 p = ALIGN8(offsetof(struct encrypted_credential_header, iv) + le32toh(h->iv_size));
1157
1158 if (with_tpm2) {
1159 #if HAVE_TPM2
1160 struct tpm2_credential_header* t = (struct tpm2_credential_header*) ((uint8_t*) input + p);
1161 struct tpm2_public_key_credential_header *z = NULL;
1162
1163 if (!TPM2_PCR_MASK_VALID(t->pcr_mask))
1164 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "TPM2 PCR mask out of range.");
1165 if (!tpm2_hash_alg_to_string(le16toh(t->pcr_bank)))
1166 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "TPM2 PCR bank invalid or not supported");
1167 if (!tpm2_asym_alg_to_string(le16toh(t->primary_alg)))
1168 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "TPM2 primary key algorithm invalid or not supported.");
1169 if (le32toh(t->blob_size) > CREDENTIAL_FIELD_SIZE_MAX)
1170 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected TPM2 blob size.");
1171 if (le32toh(t->policy_hash_size) > CREDENTIAL_FIELD_SIZE_MAX)
1172 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected TPM2 policy hash size.");
1173
1174 /* Ensure we have space for the full TPM2 header now (still don't know the name, and its size
1175 * though, hence still just a lower limit test only) */
1176 if (input_size <
1177 ALIGN8(offsetof(struct encrypted_credential_header, iv) + le32toh(h->iv_size)) +
1178 ALIGN8(offsetof(struct tpm2_credential_header, policy_hash_and_blob) + le32toh(t->blob_size) + le32toh(t->policy_hash_size)) +
1179 ALIGN8(with_tpm2_pk ? offsetof(struct tpm2_public_key_credential_header, data) : 0) +
1180 ALIGN8(offsetof(struct metadata_credential_header, name)) +
1181 le32toh(h->tag_size))
1182 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
1183
1184 p += ALIGN8(offsetof(struct tpm2_credential_header, policy_hash_and_blob) +
1185 le32toh(t->blob_size) +
1186 le32toh(t->policy_hash_size));
1187
1188 if (with_tpm2_pk) {
1189 z = (struct tpm2_public_key_credential_header*) ((uint8_t*) input + p);
1190
1191 if (!TPM2_PCR_MASK_VALID(le64toh(z->pcr_mask)) || le64toh(z->pcr_mask) == 0)
1192 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "TPM2 PCR mask out of range.");
1193 if (le32toh(z->size) > PUBLIC_KEY_MAX)
1194 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected public key size.");
1195
1196 if (input_size <
1197 ALIGN8(offsetof(struct encrypted_credential_header, iv) + le32toh(h->iv_size)) +
1198 ALIGN8(offsetof(struct tpm2_credential_header, policy_hash_and_blob) + le32toh(t->blob_size) + le32toh(t->policy_hash_size)) +
1199 ALIGN8(offsetof(struct tpm2_public_key_credential_header, data) + le32toh(z->size)) +
1200 ALIGN8(offsetof(struct metadata_credential_header, name)) +
1201 le32toh(h->tag_size))
1202 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
1203
1204 p += ALIGN8(offsetof(struct tpm2_public_key_credential_header, data) +
1205 le32toh(z->size));
1206 }
1207
1208 _cleanup_(tpm2_context_unrefp) Tpm2Context *tpm2_context = NULL;
1209 r = tpm2_context_new(tpm2_device, &tpm2_context);
1210 if (r < 0)
1211 return r;
1212
1213 // TODO: Add the SRK data to the credential structure so it can be plumbed
1214 // through and used to verify the TPM session.
1215 r = tpm2_unseal(tpm2_context,
1216 le64toh(t->pcr_mask),
1217 le16toh(t->pcr_bank),
1218 z ? z->data : NULL,
1219 z ? le32toh(z->size) : 0,
1220 z ? le64toh(z->pcr_mask) : 0,
1221 signature_json,
1222 /* pin= */ NULL,
1223 /* pcrlock_policy= */ NULL,
1224 le16toh(t->primary_alg),
1225 t->policy_hash_and_blob,
1226 le32toh(t->blob_size),
1227 t->policy_hash_and_blob + le32toh(t->blob_size),
1228 le32toh(t->policy_hash_size),
1229 /* srk_buf= */ NULL,
1230 /* srk_buf_size= */ 0,
1231 &tpm2_key,
1232 &tpm2_key_size);
1233 if (r < 0)
1234 return log_error_errno(r, "Failed to unseal secret using TPM2: %m");
1235 #else
1236 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Credential requires TPM2 support, but TPM2 support not available.");
1237 #endif
1238 }
1239
1240 if (with_host_key) {
1241 r = get_credential_host_secret(
1242 0,
1243 &host_key,
1244 &host_key_size);
1245 if (r < 0)
1246 return log_error_errno(r, "Failed to determine local credential key: %m");
1247 }
1248
1249 if (is_tpm2_absent)
1250 log_warning("Warning: using a null key for decryption and authentication. Confidentiality or authenticity are not provided.");
1251
1252 sha256_hash_host_and_tpm2_key(host_key, host_key_size, tpm2_key, tpm2_key_size, md);
1253
1254 assert_se(cc = EVP_aes_256_gcm());
1255
1256 /* Make sure cipher expectations match the header */
1257 if (EVP_CIPHER_key_length(cc) != (int) le32toh(h->key_size))
1258 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected key size in header.");
1259 if (EVP_CIPHER_block_size(cc) != (int) le32toh(h->block_size))
1260 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected block size in header.");
1261
1262 context = EVP_CIPHER_CTX_new();
1263 if (!context)
1264 return log_error_errno(SYNTHETIC_ERRNO(ENOMEM), "Failed to allocate decryption object: %s",
1265 ERR_error_string(ERR_get_error(), NULL));
1266
1267 if (EVP_DecryptInit_ex(context, cc, NULL, NULL, NULL) != 1)
1268 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initialize decryption context: %s",
1269 ERR_error_string(ERR_get_error(), NULL));
1270
1271 if (EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_GCM_SET_IVLEN, le32toh(h->iv_size), NULL) != 1)
1272 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to set IV size on decryption context: %s",
1273 ERR_error_string(ERR_get_error(), NULL));
1274
1275 if (EVP_DecryptInit_ex(context, NULL, NULL, md, h->iv) != 1)
1276 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to set IV and key: %s",
1277 ERR_error_string(ERR_get_error(), NULL));
1278
1279 if (EVP_DecryptUpdate(context, NULL, &added, input, p) != 1)
1280 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to write AAD data: %s",
1281 ERR_error_string(ERR_get_error(), NULL));
1282
1283 plaintext = malloc(input_size - p - le32toh(h->tag_size));
1284 if (!plaintext)
1285 return -ENOMEM;
1286
1287 if (EVP_DecryptUpdate(
1288 context,
1289 plaintext,
1290 &added,
1291 (uint8_t*) input + p,
1292 input_size - p - le32toh(h->tag_size)) != 1)
1293 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to decrypt data: %s",
1294 ERR_error_string(ERR_get_error(), NULL));
1295
1296 assert(added >= 0);
1297 assert((size_t) added <= input_size - p - le32toh(h->tag_size));
1298 plaintext_size = added;
1299
1300 if (EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_GCM_SET_TAG, le32toh(h->tag_size), (uint8_t*) input + input_size - le32toh(h->tag_size)) != 1)
1301 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to set tag: %s",
1302 ERR_error_string(ERR_get_error(), NULL));
1303
1304 if (EVP_DecryptFinal_ex(context, (uint8_t*) plaintext + plaintext_size, &added) != 1)
1305 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Decryption failed (incorrect key?): %s",
1306 ERR_error_string(ERR_get_error(), NULL));
1307
1308 plaintext_size += added;
1309
1310 if (plaintext_size < ALIGN8(offsetof(struct metadata_credential_header, name)))
1311 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Metadata header incomplete.");
1312
1313 m = plaintext;
1314
1315 if (le64toh(m->timestamp) != USEC_INFINITY &&
1316 le64toh(m->not_after) != USEC_INFINITY &&
1317 le64toh(m->timestamp) >= le64toh(m->not_after))
1318 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Timestamps of credential are not in order, refusing.");
1319
1320 if (le32toh(m->name_size) > CREDENTIAL_NAME_MAX)
1321 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Embedded credential name too long, refusing.");
1322
1323 hs = ALIGN8(offsetof(struct metadata_credential_header, name) + le32toh(m->name_size));
1324 if (plaintext_size < hs)
1325 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Metadata header incomplete.");
1326
1327 if (le32toh(m->name_size) > 0) {
1328 _cleanup_free_ char *embedded_name = NULL;
1329
1330 r = make_cstring(m->name, le32toh(m->name_size), MAKE_CSTRING_REFUSE_TRAILING_NUL, &embedded_name);
1331 if (r < 0)
1332 return log_error_errno(r, "Unable to convert embedded credential name to C string: %m");
1333
1334 if (!credential_name_valid(embedded_name))
1335 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Embedded credential name is not valid, refusing.");
1336
1337 if (validate_name && !streq(embedded_name, validate_name)) {
1338
1339 r = getenv_bool_secure("SYSTEMD_CREDENTIAL_VALIDATE_NAME");
1340 if (r < 0 && r != -ENXIO)
1341 log_debug_errno(r, "Failed to parse $SYSTEMD_CREDENTIAL_VALIDATE_NAME: %m");
1342 if (r != 0)
1343 return log_error_errno(SYNTHETIC_ERRNO(EREMOTE), "Embedded credential name '%s' does not match filename '%s', refusing.", embedded_name, validate_name);
1344
1345 log_debug("Embedded credential name '%s' does not match expected name '%s', but configured to use credential anyway.", embedded_name, validate_name);
1346 }
1347 }
1348
1349 if (validate_timestamp != USEC_INFINITY) {
1350 if (le64toh(m->timestamp) != USEC_INFINITY && le64toh(m->timestamp) > validate_timestamp)
1351 log_debug("Credential timestamp is from the future, assuming clock skew.");
1352
1353 if (le64toh(m->not_after) != USEC_INFINITY && le64toh(m->not_after) < validate_timestamp) {
1354
1355 r = getenv_bool_secure("SYSTEMD_CREDENTIAL_VALIDATE_NOT_AFTER");
1356 if (r < 0 && r != -ENXIO)
1357 log_debug_errno(r, "Failed to parse $SYSTEMD_CREDENTIAL_VALIDATE_NOT_AFTER: %m");
1358 if (r != 0)
1359 return log_error_errno(SYNTHETIC_ERRNO(ESTALE), "Credential's time passed, refusing to use.");
1360
1361 log_debug("Credential not-after timestamp has passed, but configured to use credential anyway.");
1362 }
1363 }
1364
1365 if (ret) {
1366 char *without_metadata;
1367
1368 without_metadata = memdup((uint8_t*) plaintext + hs, plaintext_size - hs);
1369 if (!without_metadata)
1370 return log_oom();
1371
1372 *ret = without_metadata;
1373 }
1374
1375 if (ret_size)
1376 *ret_size = plaintext_size - hs;
1377
1378 return 0;
1379 }
1380
1381 #else
1382
1383 int get_credential_host_secret(CredentialSecretFlags flags, void **ret, size_t *ret_size) {
1384 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Support for encrypted credentials not available.");
1385 }
1386
1387 int encrypt_credential_and_warn(sd_id128_t with_key, const char *name, usec_t timestamp, usec_t not_after, const char *tpm2_device, uint32_t tpm2_hash_pcr_mask, const char *tpm2_pubkey_path, uint32_t tpm2_pubkey_pcr_mask, const void *input, size_t input_size, void **ret, size_t *ret_size) {
1388 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Support for encrypted credentials not available.");
1389 }
1390
1391 int decrypt_credential_and_warn(const char *validate_name, usec_t validate_timestamp, const char *tpm2_device, const char *tpm2_signature_path, const void *input, size_t input_size, void **ret, size_t *ret_size) {
1392 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Support for encrypted credentials not available.");
1393 }
1394
1395 #endif