Debian Codegraph @

src/shared/creds-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <pwd.h>
4 #include <sys/file.h>
5 #include <unistd.h>
6 #include "efivars.h"
7 #include "time-util.h"
8
9 #include "sd-id128.h"
10 #include "sd-json.h"
11 #include "sd-varlink.h"
12
13 #include "alloc-util.h"
14 #include "blockdev-util.h"
15 #include "chattr-util.h"
16 #include "copy.h"
17 #include "creds-util.h"
18 #include "crypto-util.h"
19 #include "efi-api.h"
20 #include "env-util.h"
21 #include "errno-util.h"
22 #include "fd-util.h"
23 #include "fileio.h"
24 #include "find-esp.h"
25 #include "format-util.h"
26 #include "fs-util.h"
27 #include "io-util.h"
28 #include "json-util.h"
29 #include "log.h"
30 #include "memory-util.h"
31 #include "mkdir.h"
32 #include "parse-util.h"
33 #include "path-util.h"
34 #include "random-util.h"
35 #include "recurse-dir.h"
36 #include "sparse-endian.h"
37 #include "stat-util.h"
38 #include "string-util.h"
39 #include "tmpfile-util.h"
40 #include "tpm2-pcr.h"
41 #include "tpm2-util.h"
42 #include "user-util.h"
43
44 #define PUBLIC_KEY_MAX (UINT32_C(1024) * UINT32_C(1024))
45
46 bool credential_name_valid(const char *s) {
47 /* We want that credential names are both valid in filenames (since that's our primary way to pass
48 * them around) and as fdnames (which is how we might want to pass them around eventually) */
49 return filename_is_valid(s) && fdname_is_valid(s);
50 }
51
52 bool credential_glob_valid(const char *s) {
53 const char *e, *a;
54 size_t n;
55
56 /* Checks if a credential glob expression is valid. Note that this is more restrictive than
57 * fnmatch()! We only allow trailing asterisk matches for now (simply because we want some freedom
58 * with automatically extending the pattern in a systematic way to cover for unit instances getting
59 * per-instance credentials or similar. Moreover, credential globbing expressions are also more
60 * restrictive than credential names: we don't allow *, ?, [, ] in them (except for the asterisk
61 * match at the end of the string), simply to not allow ambiguity. After all, we want the flexibility
62 * to one day add full globbing should the need arise. */
63
64 if (isempty(s))
65 return false;
66
67 /* Find first glob (or NUL byte) */
68 n = strcspn(s, "*?[]");
69 e = s + n;
70
71 /* For now, only allow asterisk wildcards, and only at the end of the string. If it's anything else, refuse. */
72 if (isempty(e))
73 return credential_name_valid(s);
74
75 if (!streq(e, "*")) /* only allow trailing "*", no other globs */
76 return false;
77
78 if (n == 0) /* Explicitly allow the complete wildcard. */
79 return true;
80
81 if (n > NAME_MAX + strlen(e)) /* before we make a copy on the stack, let's check this is not overly large */
82 return false;
83
84 /* Make a copy of the string without the '*' suffix */
85 a = strndupa_safe(s, n);
86
87 return credential_name_valid(a);
88 }
89
90 static int get_credentials_dir_internal(const char *envvar, const char **ret) {
91 const char *e;
92
93 assert(ret);
94
95 e = secure_getenv(envvar);
96 if (!e)
97 return -ENXIO;
98
99 if (!path_is_absolute(e) || !path_is_normalized(e))
100 return -EINVAL;
101
102 *ret = e;
103 return 0;
104 }
105
106 int get_credentials_dir(const char **ret) {
107 return get_credentials_dir_internal("CREDENTIALS_DIRECTORY", ret);
108 }
109
110 int get_encrypted_credentials_dir(const char **ret) {
111 return get_credentials_dir_internal("ENCRYPTED_CREDENTIALS_DIRECTORY", ret);
112 }
113
114 int open_credentials_dir(void) {
115 const char *d;
116 int r;
117
118 r = get_credentials_dir(&d);
119 if (r < 0)
120 return r;
121
122 return RET_NERRNO(open(d, O_CLOEXEC|O_DIRECTORY));
123 }
124
125 int get_system_credentials_dir(const char **ret) {
126 int r;
127
128 assert(ret);
129
130 /* Note that for system credentials the environment variable we honour is just for debugging purpose
131 * (unlike for the per-service credential path env var where it's key part of the protocol). */
132 r = get_credentials_dir_internal("SYSTEMD_SYSTEM_CREDENTIALS_DIRECTORY", ret);
133 if (r >= 0 || r != -ENXIO)
134 return r;
135
136 *ret = SYSTEM_CREDENTIALS_DIRECTORY;
137 return 0;
138 }
139
140 int get_encrypted_system_credentials_dir(const char **ret) {
141 int r;
142
143 assert(ret);
144
145 r = get_credentials_dir_internal("SYSTEMD_ENCRYPTED_SYSTEM_CREDENTIALS_DIRECTORY", ret);
146 if (r >= 0 || r != -ENXIO)
147 return r;
148
149 *ret = ENCRYPTED_SYSTEM_CREDENTIALS_DIRECTORY;
150 return 0;
151 }
152
153 int read_credential(const char *name, void **ret, size_t *ret_size) {
154 _cleanup_free_ char *fn = NULL;
155 const char *d;
156 int r;
157
158 assert(ret);
159
160 if (!credential_name_valid(name))
161 return -EINVAL;
162
163 r = get_credentials_dir(&d);
164 if (r < 0)
165 return r;
166
167 fn = path_join(d, name);
168 if (!fn)
169 return -ENOMEM;
170
171 return read_full_file_full(
172 AT_FDCWD, fn,
173 UINT64_MAX, SIZE_MAX,
174 READ_FULL_FILE_SECURE,
175 NULL,
176 (char**) ret, ret_size);
177 }
178
179 int read_credential_with_decryption(const char *name, void **ret, size_t *ret_size) {
180 _cleanup_(iovec_done_erase) struct iovec ret_iovec = {};
181 _cleanup_(erase_and_freep) void *data = NULL;
182 _cleanup_free_ char *fn = NULL;
183 size_t sz = 0;
184 const char *d;
185 int r;
186
187 /* Just like read_credential() but will also look for encrypted credentials. Note that services only
188 * receive decrypted credentials, hence use read_credential() for those. This helper here is for
189 * generators, i.e. code that runs outside of service context, and thus has no decrypted credentials
190 * yet.
191 *
192 * Note that read_credential_harder_and_warn() logs on its own, while read_credential() does not!
193 * (It's a lot more complex and error prone given its TPM2 connectivity, and is generally called from
194 * generators only where logging is OK).
195 *
196 * Error handling is also a bit different: if we can't find a credential we'll return 0 and NULL
197 * pointers/zero size, rather than -ENXIO/-ENOENT. */
198
199 if (!credential_name_valid(name))
200 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid credential name: %s", name);
201
202 r = read_credential(name, ret, ret_size);
203 if (r >= 0)
204 return 1; /* found */
205 if (!IN_SET(r, -ENXIO, -ENOENT))
206 return log_error_errno(r, "Failed to read unencrypted credential '%s': %m", name);
207
208 r = get_encrypted_credentials_dir(&d);
209 if (r == -ENXIO)
210 goto not_found;
211 if (r < 0)
212 return log_error_errno(r, "Failed to determine encrypted credentials directory: %m");
213
214 fn = path_join(d, name);
215 if (!fn)
216 return log_oom();
217
218 r = read_full_file_full(
219 AT_FDCWD, fn,
220 UINT64_MAX, SIZE_MAX,
221 READ_FULL_FILE_SECURE,
222 NULL,
223 (char**) &data, &sz);
224 if (r == -ENOENT)
225 goto not_found;
226 if (r < 0)
227 return log_error_errno(r, "Failed to read encrypted credential data: %m");
228
229 if (geteuid() != 0)
230 r = ipc_decrypt_credential(
231 name,
232 now(CLOCK_REALTIME),
233 getuid(),
234 &IOVEC_MAKE(data, sz),
235 CREDENTIAL_ANY_SCOPE,
236 &ret_iovec);
237 else
238 r = decrypt_credential_and_warn(
239 name,
240 now(CLOCK_REALTIME),
241 /* tpm2_device= */ NULL,
242 /* tpm2_signature_path= */ NULL,
243 getuid(),
244 &IOVEC_MAKE(data, sz),
245 CREDENTIAL_ANY_SCOPE,
246 &ret_iovec);
247 if (r < 0)
248 return r;
249
250 if (ret)
251 *ret = TAKE_PTR(ret_iovec.iov_base);
252 if (ret_size)
253 *ret_size = ret_iovec.iov_len;
254
255 return 1; /* found */
256
257 not_found:
258 if (ret)
259 *ret = NULL;
260 if (ret_size)
261 *ret_size = 0;
262
263 return 0; /* not found */
264 }
265
266 int read_credential_strings_many_internal(
267 const char *first_name, char **first_value,
268 ...) {
269
270 _cleanup_free_ void *b = NULL;
271 bool all = true;
272 int r, ret = 0;
273
274 assert(first_value);
275
276 /* Reads a bunch of credentials into the specified buffers. If the specified buffers are already
277 * non-NULL frees them if a credential is found. Only supports string-based credentials
278 * (i.e. refuses embedded NUL bytes).
279 *
280 * 0 is returned when some or all credentials are missing.
281 */
282
283 if (!first_name)
284 return 0;
285
286 r = read_credential(first_name, &b, NULL);
287 if (r == -ENXIO) /* No creds passed at all? Bail immediately. */
288 return 0;
289 if (r == -ENOENT)
290 all = false;
291 else if (r < 0)
292 RET_GATHER(ret, r);
293 else
294 free_and_replace(*first_value, b);
295
296 va_list ap;
297 va_start(ap, first_value);
298
299 for (;;) {
300 _cleanup_free_ void *bb = NULL;
301 const char *name;
302 char **value;
303
304 name = va_arg(ap, const char *);
305 if (!name)
306 break;
307
308 value = ASSERT_PTR(va_arg(ap, char **));
309
310 r = read_credential(name, &bb, NULL);
311 if (r == -ENOENT)
312 all = false;
313 else if (r < 0)
314 RET_GATHER(ret, r);
315 else
316 free_and_replace(*value, bb);
317 }
318
319 va_end(ap);
320 return ret < 0 ? ret : all;
321 }
322
323 int read_credential_bool(const char *name) {
324 _cleanup_free_ void *data = NULL;
325 int r;
326
327 r = read_credential(name, &data, NULL);
328 if (r < 0)
329 return IN_SET(r, -ENXIO, -ENOENT) ? 0 : r;
330
331 return parse_boolean(data);
332 }
333
334 int get_credential_user_password(const char *username, char **ret_password, bool *ret_is_hashed) {
335 _cleanup_(erase_and_freep) char *creds_password = NULL;
336 _cleanup_free_ char *cn = NULL;
337 int r;
338
339 assert(ret_password);
340 assert(ret_is_hashed);
341
342 /* Try to pick up the password for this account via the credentials logic */
343 cn = strjoin("passwd.hashed-password.", username);
344 if (!cn)
345 return -ENOMEM;
346
347 r = read_credential(cn, (void**) &creds_password, NULL);
348 if (r == -ENOENT) {
349 free(cn);
350 cn = strjoin("passwd.plaintext-password.", username);
351 if (!cn)
352 return -ENOMEM;
353
354 r = read_credential(cn, (void**) &creds_password, NULL);
355 if (r < 0)
356 log_debug_errno(r, "Couldn't read credential '%s', ignoring: %m", cn);
357 else
358 *ret_is_hashed = false;
359 } else if (r < 0)
360 log_debug_errno(r, "Couldn't read credential '%s', ignoring: %m", cn);
361 else
362 *ret_is_hashed = true;
363
364 *ret_password = TAKE_PTR(creds_password);
365
366 return r;
367 }
368
369 #if HAVE_OPENSSL
370
371 #define CREDENTIAL_HOST_SECRET_SIZE 4096
372
373 static const sd_id128_t credential_app_id =
374 SD_ID128_MAKE(d3,ac,ec,ba,0d,ad,4c,df,b8,c9,38,15,28,93,6c,58);
375
376 struct credential_host_secret_format {
377 /* The hashed machine ID of the machine this belongs to. Why? We want to ensure that each machine
378 * gets its own secret, even if people forget to flush out this secret file. Hence we bind it to the
379 * machine ID, for which there's hopefully a better chance it will be flushed out. We use a hashed
380 * machine ID instead of the literal one, because it's trivial to, and it might be a good idea not
381 * being able to directly associate a secret key file with a host. */
382 sd_id128_t machine_id;
383
384 /* The actual secret key */
385 uint8_t data[CREDENTIAL_HOST_SECRET_SIZE];
386 } _packed_;
387
388 static void warn_not_encrypted(int fd, CredentialSecretFlags flags, const char *dirname, const char *filename) {
389 int r;
390
391 assert(fd >= 0);
392 assert(dirname);
393 assert(filename);
394
395 if (!FLAGS_SET(flags, CREDENTIAL_SECRET_WARN_NOT_ENCRYPTED))
396 return;
397
398 r = fd_is_encrypted(fd);
399 if (r < 0)
400 log_debug_errno(r, "Failed to determine if credential secret file '%s/%s' is encrypted.",
401 dirname, filename);
402 else if (r == 0)
403 log_warning("Credential secret file '%s/%s' is not located on encrypted media, using anyway.",
404 dirname, filename);
405 }
406
407 static int make_credential_host_secret(
408 int dfd,
409 const sd_id128_t machine_id,
410 CredentialSecretFlags flags,
411 const char *dirname,
412 const char *fn,
413 struct iovec *ret) {
414
415 _cleanup_free_ char *t = NULL;
416 _cleanup_close_ int fd = -EBADF;
417 int r;
418
419 assert(dfd >= 0);
420 assert(fn);
421
422 fd = open_tmpfile_linkable_at(dfd, fn, O_CLOEXEC|O_WRONLY, &t);
423 if (fd < 0)
424 return log_debug_errno(fd, "Failed to create temporary file for credential host secret: %m");
425
426 CLEANUP_TMPFILE_AT(dfd, t);
427
428 r = chattr_secret(fd, 0);
429 if (r < 0)
430 log_debug_errno(r, "Failed to set file attributes for secrets file, ignoring: %m");
431
432 struct credential_host_secret_format buf = {
433 .machine_id = machine_id,
434 };
435
436 CLEANUP_ERASE(buf);
437
438 r = crypto_random_bytes(buf.data, sizeof(buf.data));
439 if (r < 0)
440 return r;
441
442 r = loop_write(fd, &buf, sizeof(buf));
443 if (r < 0)
444 return r;
445
446 if (fchmod(fd, 0400) < 0)
447 return -errno;
448
449 warn_not_encrypted(fd, flags, dirname, fn);
450
451 r = link_tmpfile_at(fd, dfd, t, fn, LINK_TMPFILE_SYNC);
452 if (r < 0)
453 return log_debug_errno(r, "Failed to link host key into place: %m");
454
455 t = mfree(t); /* disarm CLEANUP_TMPFILE_AT() */
456
457 if (ret) {
458 void *copy;
459
460 copy = memdup(buf.data, sizeof(buf.data));
461 if (!copy)
462 return -ENOMEM;
463
464 *ret = IOVEC_MAKE(copy, sizeof(buf.data));
465 }
466
467 return 0;
468 }
469
470 int get_credential_host_secret(CredentialSecretFlags flags, struct iovec *ret) {
471 _cleanup_free_ char *_dirname = NULL, *_filename = NULL;
472 _cleanup_close_ int dfd = -EBADF;
473 sd_id128_t machine_id;
474 const char *dirname, *filename;
475 int r;
476
477 r = sd_id128_get_machine_app_specific(credential_app_id, &machine_id);
478 if (r < 0)
479 return r;
480
481 const char *e = secure_getenv("SYSTEMD_CREDENTIAL_SECRET");
482 if (e) {
483 if (!path_is_normalized(e))
484 return -EINVAL;
485 if (!path_is_absolute(e))
486 return -EINVAL;
487
488 r = path_split_prefix_filename(e, &_dirname, &_filename);
489 if (r < 0)
490 return r;
491 if (r == O_DIRECTORY)
492 return -EINVAL;
493
494 /* We validate that the path is absolute above, hence dirname must be extractable. */
495 dirname = _dirname;
496 filename = _filename;
497 } else {
498 dirname = "/var/lib/systemd";
499 filename = "credential.secret";
500 }
501
502 assert(dirname);
503 assert(filename);
504
505 (void) mkdir_parents(dirname, 0755);
506
507 dfd = open_mkdir(dirname, O_CLOEXEC, 0755);
508 if (dfd < 0)
509 return log_debug_errno(dfd, "Failed to create or open directory '%s': %m", dirname);
510
511 if (FLAGS_SET(flags, CREDENTIAL_SECRET_FAIL_ON_TEMPORARY_FS)) {
512 r = fd_is_temporary_fs(dfd);
513 if (r < 0)
514 return log_debug_errno(r, "Failed to check directory '%s': %m", dirname);
515 if (r > 0)
516 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM),
517 "Directory '%s' is on a temporary file system, refusing.", dirname);
518 }
519
520 for (unsigned attempt = 0;; attempt++) {
521 _cleanup_(erase_and_freep) struct credential_host_secret_format *f = NULL;
522 _cleanup_close_ int fd = -EBADF;
523 size_t l = 0;
524 ssize_t n = 0;
525 struct stat st;
526
527 if (attempt >= 3) /* Somebody is playing games with us */
528 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
529 "All attempts to create secret store in %s failed.", dirname);
530
531 fd = openat(dfd, filename, O_CLOEXEC|O_RDONLY|O_NOCTTY|O_NOFOLLOW);
532 if (fd < 0) {
533 if (errno != ENOENT || !FLAGS_SET(flags, CREDENTIAL_SECRET_GENERATE))
534 return log_debug_errno(errno,
535 "Failed to open %s/%s: %m", dirname, filename);
536
537 r = make_credential_host_secret(dfd, machine_id, flags, dirname, filename, ret);
538 if (r == -EEXIST) {
539 log_debug_errno(r, "Credential secret %s/%s appeared while we were creating it, rereading.",
540 dirname, filename);
541 continue;
542 }
543 if (r < 0)
544 return log_debug_errno(r, "Failed to create credential secret %s/%s: %m",
545 dirname, filename);
546 return 0;
547 }
548
549 if (fstat(fd, &st) < 0)
550 return log_debug_errno(errno, "Failed to stat %s/%s: %m", dirname, filename);
551
552 r = stat_verify_regular(&st);
553 if (r < 0)
554 return log_debug_errno(r, "%s/%s is not a regular file: %m", dirname, filename);
555 if (st.st_nlink == 0) /* Deleted by now, try again */
556 continue;
557 if (st.st_nlink > 1)
558 /* Our deletion check won't work if hardlinked somewhere else */
559 return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
560 "%s/%s has too many links, refusing.",
561 dirname, filename);
562 if ((st.st_mode & 07777) != 0400)
563 /* Don't use file if not 0400 access mode */
564 return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
565 "%s/%s has permissive access mode, refusing.",
566 dirname, filename);
567 l = st.st_size;
568 if (l < offsetof(struct credential_host_secret_format, data) + 1)
569 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
570 "%s/%s is too small, refusing.", dirname, filename);
571 if (l > 16*1024*1024)
572 return log_debug_errno(SYNTHETIC_ERRNO(E2BIG),
573 "%s/%s is too big, refusing.", dirname, filename);
574
575 f = malloc(l+1);
576 if (!f)
577 return log_oom_debug();
578
579 n = read(fd, f, l+1);
580 if (n < 0)
581 return log_debug_errno(errno,
582 "Failed to read %s/%s: %m", dirname, filename);
583 if ((size_t) n != l) /* What? The size changed? */
584 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
585 "Failed to read %s/%s.", dirname, filename);
586
587 if (sd_id128_equal(machine_id, f->machine_id)) {
588 size_t sz;
589
590 warn_not_encrypted(fd, flags, dirname, filename);
591
592 sz = l - offsetof(struct credential_host_secret_format, data);
593 assert(sz > 0);
594
595 if (ret) {
596 void *copy;
597
598 assert(sz <= sizeof(f->data)); /* Ensure we don't read past f->data bounds */
599
600 copy = memdup(f->data, sz);
601 if (!copy)
602 return log_oom_debug();
603
604 *ret = IOVEC_MAKE(copy, sz);
605 }
606
607 return 0;
608 }
609
610 /* Hmm, this secret is from somewhere else. Let's delete the file. Let's first acquire a lock
611 * to ensure we are the only ones accessing the file while we delete it. */
612
613 if (flock(fd, LOCK_EX) < 0)
614 return log_debug_errno(errno,
615 "Failed to flock %s/%s: %m", dirname, filename);
616
617 /* Before we delete it check that the file is still linked into the file system */
618 if (fstat(fd, &st) < 0)
619 return log_debug_errno(errno, "Failed to stat %s/%s: %m", dirname, filename);
620 if (st.st_nlink == 0) /* Already deleted by now? */
621 continue;
622 if (st.st_nlink != 1) /* Safety check, someone is playing games with us */
623 return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
624 "%s/%s unexpectedly has too many links.",
625 dirname, filename);
626 if (unlinkat(dfd, filename, 0) < 0)
627 return log_debug_errno(errno, "Failed to unlink %s/%s: %m", dirname, filename);
628
629 /* And now try again */
630 }
631 }
632
633 /* Construction is like this:
634 *
635 * A symmetric encryption key is derived from:
636 *
637 * 1. Either the "host" key (a key stored in /var/lib/credential.secret)
638 *
639 * 2. A key generated by letting the TPM2 calculate an HMAC hash of some nonce we pass to it, keyed
640 * by a key derived from its internal seed key.
641 *
642 * 3. The concatenation of the above.
643 *
644 * 4. Or a fixed "empty" key. This will not provide confidentiality or authenticity, of course, but is
645 * useful to encode credentials for the initrd on TPM-less systems, where we simply have no better
646 * concept to bind things to. Note that decryption of a key set up like this will be refused on
647 * systems that have a TPM and have SecureBoot enabled.
648 *
649 * The above is hashed with SHA256 which is then used as encryption key for AES256-GCM. The encrypted
650 * credential is a short (unencrypted) header describing which of the three keys to use, the IV to use for
651 * AES256-GCM and some more meta information (sizes of certain objects) that is strictly speaking redundant,
652 * but kinda nice to have since we can have a more generic parser. If the TPM2 key is used this is followed
653 * by another (unencrypted) header, with information about the TPM2 policy used (specifically: the PCR mask
654 * to bind against, and a hash of the resulting policy — the latter being redundant, but speeding up things a
655 * bit, since we can more quickly refuse PCR state), followed by a sealed/exported TPM2 HMAC key. This is
656 * then followed by the encrypted data, which begins with a metadata header (which contains validity
657 * timestamps as well as the credential name), followed by the actual credential payload. The file ends in
658 * the AES256-GCM tag. To make things simple, the AES256-GCM AAD covers the main and the TPM2 header in
659 * full. This means the whole file is either protected by AAD, or is ciphertext, or is the tag. No
660 * unprotected data is included.
661 */
662
663 struct _packed_ encrypted_credential_header {
664 sd_id128_t id;
665 le32_t key_size;
666 le32_t block_size;
667 le32_t iv_size;
668 le32_t tag_size;
669 uint8_t iv[];
670 /* Followed by NUL bytes until next 8 byte boundary */
671 };
672
673 struct _packed_ tpm2_credential_header {
674 le64_t pcr_mask; /* Note that the spec for PC Clients only mandates 24 PCRs, and that's what systems
675 * generally have. But keep the door open for more. */
676 le16_t pcr_bank; /* For now, either TPM2_ALG_SHA256 or TPM2_ALG_SHA1 */
677 le16_t primary_alg; /* Primary key algorithm (either TPM2_ALG_RSA or TPM2_ALG_ECC for now) */
678 le32_t blob_size;
679 le32_t policy_hash_size;
680 uint8_t policy_hash_and_blob[];
681 /* Followed by NUL bytes until next 8 byte boundary */
682 };
683
684 struct _packed_ tpm2_public_key_credential_header {
685 le64_t pcr_mask; /* PCRs used for the public key PCR policy (usually just PCR 11, i.e. the unified kernel) */
686 le32_t size; /* Size of DER public key */
687 uint8_t data[]; /* DER public key */
688 /* Followed by NUL bytes until next 8 byte boundary */
689 };
690
691 struct _packed_ scoped_credential_header {
692 le64_t flags; /* SCOPE_HASH_DATA_BASE_FLAGS for now */
693 };
694
695 /* This header is encrypted */
696 struct _packed_ metadata_credential_header {
697 le64_t timestamp;
698 le64_t not_after;
699 le32_t name_size;
700 char name[];
701 /* Followed by NUL bytes until next 8 byte boundary */
702 };
703
704 struct _packed_ scoped_hash_data {
705 le64_t flags; /* copy of the scoped_credential_header.flags */
706 le32_t uid;
707 sd_id128_t machine_id;
708 char username[]; /* followed by the username */
709 /* Later on we might want to extend this: with a cgroup path to allow per-app secrets, and with the user's $HOME encryption key */
710 };
711
712 enum {
713 /* Flags for scoped_hash_data.flags and scoped_credential_header.flags */
714 SCOPE_HASH_DATA_HAS_UID = 1 << 0,
715 SCOPE_HASH_DATA_HAS_MACHINE = 1 << 1,
716 SCOPE_HASH_DATA_HAS_USERNAME = 1 << 2,
717
718 SCOPE_HASH_DATA_BASE_FLAGS = SCOPE_HASH_DATA_HAS_UID | SCOPE_HASH_DATA_HAS_USERNAME | SCOPE_HASH_DATA_HAS_MACHINE,
719 };
720
721 /* Some generic limit for parts of the encrypted credential for which we don't know the right size ahead of
722 * time, but where we are really sure it won't be larger than this. Should be larger than any possible IV,
723 * padding, tag size and so on. This is purely used for early filtering out of invalid sizes. */
724 #define CREDENTIAL_FIELD_SIZE_MAX (16U*1024U)
725
726 static int sha256_hash_host_and_tpm2_key(
727 const struct iovec *host_key,
728 const struct iovec *tpm2_key,
729 uint8_t ret[static SHA256_DIGEST_LENGTH]) {
730
731 _cleanup_(EVP_MD_CTX_freep) EVP_MD_CTX *md = NULL;
732 unsigned l;
733 int r;
734
735 assert(iovec_is_valid(host_key));
736 assert(iovec_is_valid(tpm2_key));
737 assert(ret);
738
739 /* Combines the host key and the TPM2 HMAC hash into a SHA256 hash value we'll use as symmetric encryption key. */
740
741 r = dlopen_libcrypto(LOG_DEBUG);
742 if (r < 0)
743 return r;
744
745 md = sym_EVP_MD_CTX_new();
746 if (!md)
747 return log_oom();
748
749 if (sym_EVP_DigestInit_ex(md, sym_EVP_sha256(), NULL) != 1)
750 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initial SHA256 context.");
751
752 if (iovec_is_set(host_key) && sym_EVP_DigestUpdate(md, host_key->iov_base, host_key->iov_len) != 1)
753 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to hash host key.");
754
755 if (iovec_is_set(tpm2_key) && sym_EVP_DigestUpdate(md, tpm2_key->iov_base, tpm2_key->iov_len) != 1)
756 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to hash TPM2 key.");
757
758 assert(sym_EVP_MD_CTX_get_size(md) == SHA256_DIGEST_LENGTH);
759
760 if (sym_EVP_DigestFinal_ex(md, ret, &l) != 1)
761 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to finalize SHA256 hash.");
762
763 assert(l == SHA256_DIGEST_LENGTH);
764 return 0;
765 }
766
767 static int mangle_uid_into_key(
768 uid_t uid,
769 uint8_t md[static SHA256_DIGEST_LENGTH]) {
770
771 sd_id128_t mid;
772 int r;
773
774 assert(uid_is_valid(uid));
775 assert(md);
776
777 /* If we shall encrypt for a specific user, we HMAC() a structure with the user's credentials
778 * (specifically, UID, user name, machine ID) with the key we'd otherwise use for system credentials,
779 * and use the resulting hash as actual encryption key. */
780
781 errno = 0;
782 struct passwd *pw = getpwuid(uid);
783 if (!pw)
784 return log_error_errno(
785 IN_SET(errno, 0, ENOENT) ? SYNTHETIC_ERRNO(ESRCH) : errno,
786 "Failed to resolve UID " UID_FMT ": %m", uid);
787
788 r = sd_id128_get_machine(&mid);
789 if (r < 0)
790 return log_error_errno(r, "Failed to read machine ID: %m");
791
792 size_t sz = offsetof(struct scoped_hash_data, username) + strlen(pw->pw_name) + 1;
793 _cleanup_free_ struct scoped_hash_data *d = malloc0(sz);
794 if (!d)
795 return log_oom();
796
797 d->flags = htole64(SCOPE_HASH_DATA_BASE_FLAGS);
798 d->uid = htole32(uid);
799 d->machine_id = mid;
800
801 strcpy(d->username, pw->pw_name);
802
803 _cleanup_(erase_and_freep) void *buf = NULL;
804 size_t buf_size = 0;
805 r = openssl_hmac_many(
806 "sha256",
807 md, SHA256_DIGEST_LENGTH,
808 &IOVEC_MAKE(d, sz), 1,
809 &buf, &buf_size);
810 if (r < 0)
811 return r;
812
813 assert(buf_size == SHA256_DIGEST_LENGTH);
814 memcpy(md, buf, buf_size);
815
816 return 0;
817 }
818
819 int encrypt_credential_and_warn(
820 sd_id128_t with_key,
821 const char *name,
822 usec_t timestamp,
823 usec_t not_after,
824 const char *tpm2_device,
825 uint32_t tpm2_hash_pcr_mask,
826 const char *tpm2_pubkey_path,
827 uint32_t tpm2_pubkey_pcr_mask,
828 uid_t uid,
829 const struct iovec *input,
830 CredentialFlags flags,
831 struct iovec *ret) {
832
833 _cleanup_(iovec_done) struct iovec tpm2_blob = {}, tpm2_policy_hash = {}, iv = {}, pubkey = {};
834 _cleanup_(iovec_done_erase) struct iovec tpm2_key = {}, output = {}, host_key = {};
835 _cleanup_(EVP_CIPHER_CTX_freep) EVP_CIPHER_CTX *context = NULL;
836 _cleanup_free_ struct metadata_credential_header *m = NULL;
837 #if HAVE_TPM2
838 uint16_t tpm2_pcr_bank = 0, tpm2_primary_alg = 0;
839 #endif
840 struct encrypted_credential_header *h;
841 int ksz, bsz, ivsz, tsz, added, r;
842 uint8_t md[SHA256_DIGEST_LENGTH];
843 const EVP_CIPHER *cc;
844 sd_id128_t id;
845 size_t p, ml;
846
847 assert(iovec_is_valid(input));
848 assert(ret);
849
850 /* Only one of these two flags may be set at the same time */
851 assert(!FLAGS_SET(flags, CREDENTIAL_ALLOW_NULL) || !FLAGS_SET(flags, CREDENTIAL_REFUSE_NULL));
852
853 CLEANUP_ERASE(md);
854
855 if (!CRED_KEY_IS_VALID(with_key) && !CRED_KEY_IS_AUTO(with_key))
856 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid key type: " SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(with_key));
857
858 if (name && !credential_name_valid(name))
859 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid credential name: %s", name);
860
861 if (not_after != USEC_INFINITY && timestamp != USEC_INFINITY && not_after < timestamp)
862 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Credential is invalidated before it is valid (" USEC_FMT " < " USEC_FMT ").", not_after, timestamp);
863
864 if (DEBUG_LOGGING) {
865 char buf[FORMAT_TIMESTAMP_MAX];
866
867 if (name)
868 log_debug("Including credential name '%s' in encrypted credential.", name);
869 if (timestamp != USEC_INFINITY)
870 log_debug("Including timestamp '%s' in encrypted credential.", format_timestamp(buf, sizeof(buf), timestamp));
871 if (not_after != USEC_INFINITY)
872 log_debug("Including not-after timestamp '%s' in encrypted credential.", format_timestamp(buf, sizeof(buf), not_after));
873 }
874
875 if (CRED_KEY_IS_SCOPED(with_key)) {
876 if (!uid_is_valid(uid))
877 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
878 "Scoped credential key type "SD_ID128_FORMAT_STR" selected, but no UID specified.", SD_ID128_FORMAT_VAL(with_key));
879 } else
880 uid = UID_INVALID;
881
882 if (CRED_KEY_WANTS_HOST(with_key) || CRED_KEY_REQUIRES_HOST(with_key)) {
883
884 r = get_credential_host_secret(
885 CREDENTIAL_SECRET_GENERATE|
886 CREDENTIAL_SECRET_WARN_NOT_ENCRYPTED|
887 (CRED_KEY_WANTS_HOST(with_key) ? CREDENTIAL_SECRET_FAIL_ON_TEMPORARY_FS : 0),
888 &host_key);
889 if (r == -ENOMEDIUM && CRED_KEY_WANTS_HOST(with_key))
890 log_debug_errno(r, "Credential host secret location on temporary file system, not using.");
891 else if (r < 0)
892 return log_error_errno(r, "Failed to determine local credential host secret: %m");
893 }
894
895 if (tpm2_hash_pcr_mask == UINT32_MAX)
896 tpm2_hash_pcr_mask = 0;
897 if (tpm2_pubkey_pcr_mask == UINT32_MAX)
898 tpm2_pubkey_pcr_mask = UINT32_C(1) << TPM2_PCR_KERNEL_BOOT;
899
900 #if HAVE_TPM2
901 bool try_tpm2;
902 if (CRED_KEY_WANTS_TPM2(with_key)) {
903 /* If automatic mode is selected lets see if a TPM2 it is present. If we are running in a
904 * container tpm2_support will detect this, and will return a different flag combination of
905 * TPM2_SUPPORT_FULL, effectively skipping the use of TPM2 when inside one. */
906
907 try_tpm2 = tpm2_is_mostly_supported();
908 if (!try_tpm2)
909 log_debug("System lacks TPM2 support or running in a container, not attempting to use TPM2.");
910 } else
911 try_tpm2 = CRED_KEY_REQUIRES_TPM2(with_key);
912
913 if (try_tpm2) {
914 /* If the firmware does not support TPMs, then UKI measurements are not going to work, hence
915 * PCR 11 public key stuff cannot work. Because of that, if PK is only wanted (but not
916 * required) we won't try it. */
917 if ((CRED_KEY_WANTS_TPM2_PK(with_key) && tpm2_is_fully_supported()) || CRED_KEY_REQUIRES_TPM2_PK(with_key)) {
918
919 /* Load public key for PCR policies, if one is specified, or explicitly requested */
920
921 r = tpm2_load_pcr_public_key(tpm2_pubkey_path, &pubkey.iov_base, &pubkey.iov_len);
922 if (r < 0) {
923 if (r != -ENOENT || tpm2_pubkey_path || CRED_KEY_REQUIRES_TPM2_PK(with_key))
924 return log_error_errno(r, "Failed to read TPM PCR public key: %m");
925
926 log_debug_errno(r, "Failed to read TPM2 PCR public key, proceeding without: %m");
927 }
928 }
929
930 if (!iovec_is_set(&pubkey))
931 tpm2_pubkey_pcr_mask = 0;
932
933 _cleanup_(tpm2_context_unrefp) Tpm2Context *tpm2_context = NULL;
934 r = tpm2_context_new_or_warn(tpm2_device, &tpm2_context);
935 if (r < 0)
936 return r;
937
938 r = tpm2_get_best_pcr_bank(tpm2_context, tpm2_hash_pcr_mask | tpm2_pubkey_pcr_mask, &tpm2_pcr_bank);
939 if (r < 0)
940 return log_error_errno(r, "Could not find best pcr bank: %m");
941
942 log_debug("Selected literal PCR mask: 0x%x, PK PCR mask: 0x%x", tpm2_hash_pcr_mask, tpm2_pubkey_pcr_mask);
943
944 TPML_PCR_SELECTION tpm2_hash_pcr_selection;
945 tpm2_tpml_pcr_selection_from_mask(tpm2_hash_pcr_mask, tpm2_pcr_bank, &tpm2_hash_pcr_selection);
946
947 _cleanup_free_ Tpm2PCRValue *tpm2_hash_pcr_values = NULL;
948 size_t tpm2_n_hash_pcr_values;
949 r = tpm2_pcr_read(tpm2_context, &tpm2_hash_pcr_selection, &tpm2_hash_pcr_values, &tpm2_n_hash_pcr_values);
950 if (r < 0)
951 return log_error_errno(r, "Could not read PCR values: %m");
952
953 TPM2B_PUBLIC public;
954 if (iovec_is_set(&pubkey)) {
955 r = tpm2_tpm2b_public_from_pem(pubkey.iov_base, pubkey.iov_len, &public);
956 if (r < 0)
957 return log_error_errno(r, "Could not convert public key to TPM2B_PUBLIC: %m");
958 }
959
960 TPM2B_DIGEST tpm2_policy = TPM2B_DIGEST_MAKE(NULL, TPM2_SHA256_DIGEST_SIZE);
961 r = tpm2_calculate_sealing_policy(
962 tpm2_hash_pcr_values,
963 tpm2_n_hash_pcr_values,
964 iovec_is_set(&pubkey) ? &public : NULL,
965 /* use_pin= */ false,
966 /* pcrlock_policy= */ NULL,
967 &tpm2_policy);
968 if (r < 0)
969 return log_error_errno(r, "Could not calculate sealing policy digest: %m");
970
971 struct iovec *blobs = NULL;
972 size_t n_blobs = 0;
973 CLEANUP_ARRAY(blobs, n_blobs, iovec_array_free);
974
975 r = tpm2_seal(tpm2_context,
976 /* seal_key_handle= */ 0,
977 &tpm2_policy,
978 /* n_policy= */ 1,
979 /* pin= */ NULL,
980 &tpm2_key,
981 &blobs,
982 &n_blobs,
983 &tpm2_primary_alg,
984 /* ret_srk= */ NULL);
985 if (r < 0) {
986 if (sd_id128_equal(with_key, _CRED_AUTO_INITRD))
987 log_warning("TPM2 present and used, but we didn't manage to talk to it. Credential will be refused if SecureBoot is enabled.");
988 else if (!sd_id128_in_set(with_key, _CRED_AUTO, _CRED_AUTO_SCOPED))
989 return log_error_errno(r, "Failed to seal to TPM2: %m");
990
991 log_notice_errno(r, "TPM2 sealing didn't work, continuing without TPM2: %m");
992 }
993
994 if (!iovec_memdup(&IOVEC_MAKE(tpm2_policy.buffer, tpm2_policy.size), &tpm2_policy_hash))
995 return log_oom();
996
997 assert(n_blobs == 1);
998 tpm2_blob = TAKE_STRUCT(blobs[0]);
999
1000 assert(tpm2_blob.iov_len <= CREDENTIAL_FIELD_SIZE_MAX);
1001 assert(tpm2_policy_hash.iov_len <= CREDENTIAL_FIELD_SIZE_MAX);
1002 }
1003 #endif
1004
1005 if (CRED_KEY_IS_AUTO(with_key)) {
1006 /* Let's settle the key type in auto mode now. */
1007
1008 if (iovec_is_set(&host_key) && iovec_is_set(&tpm2_key))
1009 id = iovec_is_set(&pubkey) ? (sd_id128_equal(with_key, _CRED_AUTO_SCOPED) ?
1010 CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK_SCOPED : CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK)
1011 : (sd_id128_equal(with_key, _CRED_AUTO_SCOPED) ?
1012 CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_SCOPED : CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC);
1013 else if (iovec_is_set(&tpm2_key) && !sd_id128_equal(with_key, _CRED_AUTO_SCOPED))
1014 id = iovec_is_set(&pubkey) ? CRED_AES256_GCM_BY_TPM2_HMAC_WITH_PK : CRED_AES256_GCM_BY_TPM2_HMAC;
1015 else if (iovec_is_set(&host_key))
1016 id = sd_id128_equal(with_key, _CRED_AUTO_SCOPED) ? CRED_AES256_GCM_BY_HOST_SCOPED : CRED_AES256_GCM_BY_HOST;
1017 else if (sd_id128_equal(with_key, _CRED_AUTO_INITRD))
1018 id = CRED_AES256_GCM_BY_NULL;
1019 else
1020 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1021 "TPM2 not available and host key located on temporary file system, no encryption key available.");
1022 } else
1023 id = with_key;
1024
1025 if (sd_id128_equal(id, CRED_AES256_GCM_BY_NULL)) {
1026 if (FLAGS_SET(flags, CREDENTIAL_REFUSE_NULL))
1027 return log_error_errno(SYNTHETIC_ERRNO(EHWPOISON), "Attempted to encrypt with null key, but this is disallowed.");
1028 if (!FLAGS_SET(flags, CREDENTIAL_ALLOW_NULL))
1029 log_warning("Using a null key for encryption and signing. Confidentiality or authenticity will not be provided.");
1030 }
1031
1032 /* Let's now take the host key and the TPM2 key and hash it together, to use as encryption key for the data */
1033 r = sha256_hash_host_and_tpm2_key(&host_key, &tpm2_key, md);
1034 if (r < 0)
1035 return r;
1036
1037 if (uid_is_valid(uid)) {
1038 r = mangle_uid_into_key(uid, md);
1039 if (r < 0)
1040 return r;
1041 }
1042
1043 r = dlopen_libcrypto(LOG_DEBUG);
1044 if (r < 0)
1045 return r;
1046
1047 assert_se(cc = sym_EVP_aes_256_gcm());
1048
1049 ksz = sym_EVP_CIPHER_get_key_length(cc);
1050 assert(ksz == sizeof(md));
1051
1052 bsz = sym_EVP_CIPHER_get_block_size(cc);
1053 assert(bsz > 0);
1054 assert((size_t) bsz <= CREDENTIAL_FIELD_SIZE_MAX);
1055
1056 ivsz = sym_EVP_CIPHER_get_iv_length(cc);
1057 if (ivsz > 0) {
1058 assert((size_t) ivsz <= CREDENTIAL_FIELD_SIZE_MAX);
1059
1060 r = crypto_random_bytes_allocate_iovec(ivsz, &iv);
1061 if (r < 0)
1062 return log_error_errno(r, "Failed to acquired randomized IV: %m");
1063 }
1064
1065 tsz = 16; /* FIXME: On OpenSSL 3 there is EVP_CIPHER_CTX_get_tag_length(), until then let's hardcode this */
1066
1067 context = sym_EVP_CIPHER_CTX_new();
1068 if (!context)
1069 return log_error_errno(SYNTHETIC_ERRNO(ENOMEM), "Failed to allocate encryption object: %s",
1070 sym_ERR_error_string(sym_ERR_get_error(), NULL));
1071
1072 if (sym_EVP_EncryptInit_ex(context, cc, NULL, md, iv.iov_base) != 1)
1073 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initialize encryption context: %s",
1074 sym_ERR_error_string(sym_ERR_get_error(), NULL));
1075
1076 /* Just an upper estimate */
1077 output.iov_len =
1078 ALIGN8(offsetof(struct encrypted_credential_header, iv) + ivsz) +
1079 ALIGN8(iovec_is_set(&tpm2_key) ? offsetof(struct tpm2_credential_header, policy_hash_and_blob) + tpm2_blob.iov_len + tpm2_policy_hash.iov_len : 0) +
1080 ALIGN8(iovec_is_set(&pubkey) ? offsetof(struct tpm2_public_key_credential_header, data) + pubkey.iov_len : 0) +
1081 ALIGN8(uid_is_valid(uid) ? sizeof(struct scoped_credential_header) : 0) +
1082 ALIGN8(offsetof(struct metadata_credential_header, name) + strlen_ptr(name)) +
1083 input->iov_len + 2U * (size_t) bsz +
1084 tsz;
1085 /* Silence static analyzers */
1086 assert(output.iov_len >= input->iov_len);
1087
1088 output.iov_base = malloc0(output.iov_len);
1089 if (!output.iov_base)
1090 return log_oom();
1091
1092 h = (struct encrypted_credential_header*) output.iov_base;
1093 h->id = id;
1094 h->block_size = htole32(bsz);
1095 h->key_size = htole32(ksz);
1096 h->tag_size = htole32(tsz);
1097 h->iv_size = htole32(ivsz);
1098 memcpy(h->iv, iv.iov_base, ivsz);
1099
1100 p = ALIGN8(offsetof(struct encrypted_credential_header, iv) + ivsz);
1101
1102 #if HAVE_TPM2
1103 if (iovec_is_set(&tpm2_key)) {
1104 struct tpm2_credential_header *t;
1105
1106 t = (struct tpm2_credential_header*) ((uint8_t*) output.iov_base + p);
1107 t->pcr_mask = htole64(tpm2_hash_pcr_mask);
1108 t->pcr_bank = htole16(tpm2_pcr_bank);
1109 t->primary_alg = htole16(tpm2_primary_alg);
1110 t->blob_size = htole32(tpm2_blob.iov_len);
1111 t->policy_hash_size = htole32(tpm2_policy_hash.iov_len);
1112 memcpy(t->policy_hash_and_blob, tpm2_blob.iov_base, tpm2_blob.iov_len);
1113 memcpy(t->policy_hash_and_blob + tpm2_blob.iov_len, tpm2_policy_hash.iov_base, tpm2_policy_hash.iov_len);
1114
1115 p += ALIGN8(offsetof(struct tpm2_credential_header, policy_hash_and_blob) + tpm2_blob.iov_len + tpm2_policy_hash.iov_len);
1116 }
1117 #endif
1118 if (iovec_is_set(&pubkey)) {
1119 struct tpm2_public_key_credential_header *z;
1120
1121 z = (struct tpm2_public_key_credential_header*) ((uint8_t*) output.iov_base + p);
1122 z->pcr_mask = htole64(tpm2_pubkey_pcr_mask);
1123 z->size = htole32(pubkey.iov_len);
1124 memcpy(z->data, pubkey.iov_base, pubkey.iov_len);
1125
1126 p += ALIGN8(offsetof(struct tpm2_public_key_credential_header, data) + pubkey.iov_len);
1127 }
1128
1129 if (uid_is_valid(uid)) {
1130 struct scoped_credential_header *w;
1131
1132 w = (struct scoped_credential_header*) ((uint8_t*) output.iov_base + p);
1133 w->flags = htole64(SCOPE_HASH_DATA_BASE_FLAGS);
1134
1135 p += ALIGN8(sizeof(struct scoped_credential_header));
1136 }
1137
1138 /* Pass the encrypted + TPM2 header + scoped header as AAD */
1139 if (sym_EVP_EncryptUpdate(context, NULL, &added, output.iov_base, p) != 1)
1140 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to write AAD data: %s",
1141 sym_ERR_error_string(sym_ERR_get_error(), NULL));
1142
1143 /* Now construct the metadata header */
1144 ml = strlen_ptr(name);
1145 m = malloc0(ALIGN8(offsetof(struct metadata_credential_header, name) + ml));
1146 if (!m)
1147 return log_oom();
1148
1149 m->timestamp = htole64(timestamp);
1150 m->not_after = htole64(not_after);
1151 m->name_size = htole32(ml);
1152 memcpy_safe(m->name, name, ml);
1153
1154 /* And encrypt the metadata header */
1155 if (sym_EVP_EncryptUpdate(context, (uint8_t*) output.iov_base + p, &added, (const unsigned char*) m, ALIGN8(offsetof(struct metadata_credential_header, name) + ml)) != 1)
1156 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to encrypt metadata header: %s",
1157 sym_ERR_error_string(sym_ERR_get_error(), NULL));
1158
1159 assert(added >= 0);
1160 assert((size_t) added <= output.iov_len - p);
1161 p += added;
1162
1163 /* Then encrypt the plaintext */
1164 if (sym_EVP_EncryptUpdate(context, (uint8_t*) output.iov_base + p, &added, input->iov_base, input->iov_len) != 1)
1165 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to encrypt data: %s",
1166 sym_ERR_error_string(sym_ERR_get_error(), NULL));
1167
1168 assert(added >= 0);
1169 assert((size_t) added <= output.iov_len - p);
1170 p += added;
1171
1172 /* Finalize */
1173 if (sym_EVP_EncryptFinal_ex(context, (uint8_t*) output.iov_base + p, &added) != 1)
1174 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to finalize data encryption: %s",
1175 sym_ERR_error_string(sym_ERR_get_error(), NULL));
1176
1177 assert(added >= 0);
1178 assert((size_t) added <= output.iov_len - p);
1179 p += added;
1180
1181 assert(p <= output.iov_len - tsz);
1182
1183 /* Append tag */
1184 if (sym_EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_GCM_GET_TAG, tsz, (uint8_t*) output.iov_base + p) != 1)
1185 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to get tag: %s",
1186 sym_ERR_error_string(sym_ERR_get_error(), NULL));
1187
1188 p += tsz;
1189 assert(p <= output.iov_len);
1190 output.iov_len = p;
1191
1192 if (DEBUG_LOGGING && input->iov_len > 0) {
1193 size_t base64_size;
1194
1195 base64_size = DIV_ROUND_UP(output.iov_len * 4, 3); /* Include base64 size increase in debug output */
1196 assert(base64_size >= input->iov_len);
1197 log_debug("Input of %zu bytes grew to output of %zu bytes (+%2zu%%).", input->iov_len, base64_size, base64_size * 100 / input->iov_len - 100);
1198 }
1199
1200 *ret = TAKE_STRUCT(output);
1201 return 0;
1202 }
1203
1204 int decrypt_credential_and_warn(
1205 const char *validate_name,
1206 usec_t validate_timestamp,
1207 const char *tpm2_device,
1208 const char *tpm2_signature_path,
1209 uid_t uid,
1210 const struct iovec *input,
1211 CredentialFlags flags,
1212 struct iovec *ret) {
1213
1214 _cleanup_(iovec_done_erase) struct iovec host_key = {}, plaintext = {}, tpm2_key = {};
1215 _cleanup_(sd_json_variant_unrefp) sd_json_variant *signature_json = NULL;
1216 _cleanup_(EVP_CIPHER_CTX_freep) EVP_CIPHER_CTX *context = NULL;
1217 struct encrypted_credential_header *h;
1218 struct metadata_credential_header *m;
1219 uint8_t md[SHA256_DIGEST_LENGTH];
1220 const EVP_CIPHER *cc;
1221 size_t p, hs;
1222 int r, added;
1223
1224 assert(iovec_is_valid(input));
1225 assert(ret);
1226
1227 /* Only one of these two flags may be set at the same time */
1228 assert(!FLAGS_SET(flags, CREDENTIAL_ALLOW_NULL) || !FLAGS_SET(flags, CREDENTIAL_REFUSE_NULL));
1229
1230 CLEANUP_ERASE(md);
1231
1232 /* Relevant error codes:
1233 *
1234 * -EBADMSG → Corrupted file
1235 * -EOPNOTSUPP → Unsupported file type (could be: requires TPM but we have no TPM)
1236 * -EHOSTDOWN → Need PCR signature file, but couldn't find it
1237 * -EHWPOISON → Attempt to unlock with NULL key and either CREDENTIAL_ALLOW_REFUSE is on, or CREDENTIAL_ALLOW_NULL is off, but the system has a TPM and SecureBoot is on
1238 * -EMEDIUMTYPE → File has unexpected scope, i.e. user-scoped credential is attempted to be unlocked in system scope, or vice versa
1239 * -EDESTADDRREQ → Credential is incorrectly named (i.e. the authenticated name does not match the actual name)
1240 * -ESTALE → Credential's validity has passed
1241 * -ESRCH → User specified for scope does not exist on this system
1242 *
1243 * (plus the various error codes tpm2_unseal() returns) */
1244
1245 h = (struct encrypted_credential_header*) input->iov_base;
1246
1247 /* The ID must fit in, for the current and all future formats */
1248 if (input->iov_len < sizeof(h->id))
1249 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
1250
1251 if (!CRED_KEY_IS_VALID(h->id))
1252 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Unknown encryption format, or corrupted data.");
1253
1254 if (CRED_KEY_REQUIRES_TPM2_PK(h->id)) {
1255 r = tpm2_load_pcr_signature(tpm2_signature_path, &signature_json);
1256 if (r == -ENOENT)
1257 return log_error_errno(SYNTHETIC_ERRNO(EHOSTDOWN), "Couldn't find PCR signature file: %m");
1258 if (r < 0)
1259 return log_error_errno(r, "Failed to load PCR signature: %m");
1260 }
1261
1262 if (sd_id128_equal(h->id, CRED_AES256_GCM_BY_NULL)) {
1263 if (FLAGS_SET(flags, CREDENTIAL_REFUSE_NULL))
1264 return log_error_errno(SYNTHETIC_ERRNO(EHWPOISON),
1265 "Credential uses null key, but that's not allowed, refusing.");
1266
1267 if (!FLAGS_SET(flags, CREDENTIAL_ALLOW_NULL)) {
1268 /* So this is a credential encrypted with a zero length key. We support this to cover for the
1269 * case where neither a host key not a TPM2 are available (specifically: initrd environments
1270 * where the host key is not yet accessible and no TPM2 chip exists at all), to minimize
1271 * different codeflow for TPM2 and non-TPM2 codepaths. Of course, credentials encoded this
1272 * way offer no confidentiality nor authenticity. Because of that it's important we refuse to
1273 * use them on systems that actually *do* have a TPM2 chip – if we are in SecureBoot
1274 * mode. Otherwise an attacker could hand us credentials like this and we'd use them thinking
1275 * they are trusted, even though they are not. */
1276
1277 if (efi_has_tpm2()) {
1278 if (is_efi_secure_boot())
1279 return log_error_errno(SYNTHETIC_ERRNO(EHWPOISON),
1280 "Credential uses null key intended for fallback use when TPM2 is absent — but TPM2 is present, and SecureBoot is enabled, refusing.");
1281
1282 log_warning("Credential uses null key intended for use when TPM2 is absent, but TPM2 is present! Accepting anyway, since SecureBoot is disabled.");
1283 } else
1284 log_debug("Credential uses null key intended for use when TPM2 is absent, and TPM2 indeed is absent. Accepting.");
1285 }
1286 }
1287
1288 if (CRED_KEY_IS_SCOPED(h->id)) {
1289 if (!uid_is_valid(uid))
1290 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "Encrypted file is scoped to a user, but no user selected.");
1291 } else {
1292 /* Refuse to unlock system credentials if user scope is requested. */
1293 if (uid_is_valid(uid) && !FLAGS_SET(flags, CREDENTIAL_ANY_SCOPE))
1294 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "Encrypted file is scoped to the system, but user scope selected.");
1295
1296 uid = UID_INVALID;
1297 }
1298
1299 /* Now we know the minimum header size */
1300 if (input->iov_len < offsetof(struct encrypted_credential_header, iv))
1301 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
1302
1303 /* Verify some basic header values */
1304 if (le32toh(h->key_size) != sizeof(md))
1305 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected key size in header.");
1306 if (le32toh(h->block_size) <= 0 || le32toh(h->block_size) > CREDENTIAL_FIELD_SIZE_MAX)
1307 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected block size in header.");
1308 if (le32toh(h->iv_size) > CREDENTIAL_FIELD_SIZE_MAX)
1309 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "IV size too large.");
1310 if (le32toh(h->tag_size) != 16) /* FIXME: On OpenSSL 3, let's verify via EVP_CIPHER_CTX_get_tag_length() */
1311 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected tag size in header.");
1312
1313 /* Ensure we have space for the full header now (we don't know the size of the name hence this is a
1314 * lower limit only) */
1315 if (input->iov_len <
1316 ALIGN8(offsetof(struct encrypted_credential_header, iv) + le32toh(h->iv_size)) +
1317 ALIGN8(CRED_KEY_REQUIRES_TPM2(h->id) ? offsetof(struct tpm2_credential_header, policy_hash_and_blob) : 0) +
1318 ALIGN8(CRED_KEY_REQUIRES_TPM2_PK(h->id) ? offsetof(struct tpm2_public_key_credential_header, data) : 0) +
1319 ALIGN8(CRED_KEY_IS_SCOPED(h->id) ? sizeof(struct scoped_credential_header) : 0) +
1320 ALIGN8(offsetof(struct metadata_credential_header, name)) +
1321 le32toh(h->tag_size))
1322 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
1323
1324 p = ALIGN8(offsetof(struct encrypted_credential_header, iv) + le32toh(h->iv_size));
1325
1326 if (CRED_KEY_REQUIRES_TPM2(h->id)) {
1327 #if HAVE_TPM2
1328 struct tpm2_credential_header* t = (struct tpm2_credential_header*) ((uint8_t*) input->iov_base + p);
1329 struct tpm2_public_key_credential_header *z = NULL;
1330
1331 if (!TPM2_PCR_MASK_VALID(t->pcr_mask))
1332 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "TPM2 PCR mask out of range.");
1333 if (!tpm2_hash_alg_to_string(le16toh(t->pcr_bank)))
1334 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "TPM2 PCR bank invalid or not supported");
1335 if (!tpm2_asym_alg_to_string(le16toh(t->primary_alg)))
1336 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "TPM2 primary key algorithm invalid or not supported.");
1337 if (le32toh(t->blob_size) > CREDENTIAL_FIELD_SIZE_MAX)
1338 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected TPM2 blob size.");
1339 if (le32toh(t->policy_hash_size) > CREDENTIAL_FIELD_SIZE_MAX)
1340 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected TPM2 policy hash size.");
1341
1342 /* Ensure we have space for the full TPM2 header now (still don't know the name, and its size
1343 * though, hence still just a lower limit test only) */
1344 if (input->iov_len <
1345 p +
1346 ALIGN8(offsetof(struct tpm2_credential_header, policy_hash_and_blob) + le32toh(t->blob_size) + le32toh(t->policy_hash_size)) +
1347 ALIGN8(CRED_KEY_REQUIRES_TPM2_PK(h->id) ? offsetof(struct tpm2_public_key_credential_header, data) : 0) +
1348 ALIGN8(CRED_KEY_IS_SCOPED(h->id) ? sizeof(struct scoped_credential_header) : 0) +
1349 ALIGN8(offsetof(struct metadata_credential_header, name)) +
1350 le32toh(h->tag_size))
1351 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
1352
1353 p += ALIGN8(offsetof(struct tpm2_credential_header, policy_hash_and_blob) +
1354 le32toh(t->blob_size) +
1355 le32toh(t->policy_hash_size));
1356
1357 if (CRED_KEY_REQUIRES_TPM2_PK(h->id)) {
1358 z = (struct tpm2_public_key_credential_header*) ((uint8_t*) input->iov_base + p);
1359
1360 if (!TPM2_PCR_MASK_VALID(le64toh(z->pcr_mask)) || le64toh(z->pcr_mask) == 0)
1361 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "TPM2 PCR mask out of range.");
1362 if (le32toh(z->size) > PUBLIC_KEY_MAX)
1363 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected public key size.");
1364
1365 if (input->iov_len <
1366 p +
1367 ALIGN8(offsetof(struct tpm2_public_key_credential_header, data) + le32toh(z->size)) +
1368 ALIGN8(CRED_KEY_IS_SCOPED(h->id) ? sizeof(struct scoped_credential_header) : 0) +
1369 ALIGN8(offsetof(struct metadata_credential_header, name)) +
1370 le32toh(h->tag_size))
1371 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
1372
1373 p += ALIGN8(offsetof(struct tpm2_public_key_credential_header, data) +
1374 le32toh(z->size));
1375 }
1376
1377 _cleanup_(tpm2_context_unrefp) Tpm2Context *tpm2_context = NULL;
1378 r = tpm2_context_new(tpm2_device, &tpm2_context);
1379 if (r < 0)
1380 return r;
1381
1382 // TODO: Add the SRK data to the credential structure so it can be plumbed
1383 // through and used to verify the TPM session.
1384 r = tpm2_unseal(tpm2_context,
1385 le64toh(t->pcr_mask),
1386 le16toh(t->pcr_bank),
1387 z ? &IOVEC_MAKE(z->data, le32toh(z->size)) : NULL,
1388 z ? le64toh(z->pcr_mask) : 0,
1389 signature_json,
1390 /* pin= */ NULL,
1391 /* pcrlock_policy= */ NULL,
1392 le16toh(t->primary_alg),
1393 &IOVEC_MAKE(t->policy_hash_and_blob, le32toh(t->blob_size)),
1394 /* n_blobs= */ 1,
1395 &IOVEC_MAKE(t->policy_hash_and_blob + le32toh(t->blob_size), le32toh(t->policy_hash_size)),
1396 /* n_known_policy_hash= */ 1,
1397 /* srk= */ NULL,
1398 &tpm2_key);
1399 if (r == -EREMOTE)
1400 return log_error_errno(r, "TPM key integrity check failed. Key most likely does not belong to this TPM.");
1401 if (ERRNO_IS_NEG_TPM2_UNSEAL_BAD_PCR(r))
1402 return log_error_errno(r, "TPM policy does not match current system state. Either system has been tempered with or policy out-of-date: %m");
1403 if (r < 0)
1404 return log_error_errno(r, "Failed to unseal secret using TPM2: %m");
1405 #else
1406 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Credential requires TPM2 support, but TPM2 support not available.");
1407 #endif
1408 }
1409
1410 if (CRED_KEY_IS_SCOPED(h->id)) {
1411 struct scoped_credential_header* sh = (struct scoped_credential_header*) ((uint8_t*) input->iov_base + p);
1412
1413 if (le64toh(sh->flags) != SCOPE_HASH_DATA_BASE_FLAGS)
1414 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Scoped credential with unsupported flags.");
1415
1416 if (input->iov_len <
1417 p +
1418 sizeof(struct scoped_credential_header) +
1419 ALIGN8(offsetof(struct metadata_credential_header, name)) +
1420 le32toh(h->tag_size))
1421 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
1422
1423 p += sizeof(struct scoped_credential_header);
1424 }
1425
1426 if (CRED_KEY_REQUIRES_HOST(h->id)) {
1427 r = get_credential_host_secret(/* flags= */ 0, &host_key);
1428 if (r < 0)
1429 return log_error_errno(r, "Failed to determine local credential key: %m");
1430 }
1431
1432 if (sd_id128_equal(h->id, CRED_AES256_GCM_BY_NULL) && !FLAGS_SET(flags, CREDENTIAL_ALLOW_NULL))
1433 log_warning("Warning: using a null key for decryption and authentication. Confidentiality or authenticity are not provided.");
1434
1435 sha256_hash_host_and_tpm2_key(&host_key, &tpm2_key, md);
1436
1437 if (CRED_KEY_IS_SCOPED(h->id)) {
1438 r = mangle_uid_into_key(uid, md);
1439 if (r < 0)
1440 return r;
1441 }
1442
1443 r = dlopen_libcrypto(LOG_DEBUG);
1444 if (r < 0)
1445 return r;
1446
1447 assert_se(cc = sym_EVP_aes_256_gcm());
1448
1449 /* Make sure cipher expectations match the header */
1450 if (sym_EVP_CIPHER_get_key_length(cc) != (int) le32toh(h->key_size))
1451 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected key size in header.");
1452 if (sym_EVP_CIPHER_get_block_size(cc) != (int) le32toh(h->block_size))
1453 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected block size in header.");
1454
1455 context = sym_EVP_CIPHER_CTX_new();
1456 if (!context)
1457 return log_error_errno(SYNTHETIC_ERRNO(ENOMEM), "Failed to allocate decryption object: %s",
1458 sym_ERR_error_string(sym_ERR_get_error(), NULL));
1459
1460 if (sym_EVP_DecryptInit_ex(context, cc, NULL, NULL, NULL) != 1)
1461 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initialize decryption context: %s",
1462 sym_ERR_error_string(sym_ERR_get_error(), NULL));
1463
1464 if (sym_EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_GCM_SET_IVLEN, le32toh(h->iv_size), NULL) != 1)
1465 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to set IV size on decryption context: %s",
1466 sym_ERR_error_string(sym_ERR_get_error(), NULL));
1467
1468 if (sym_EVP_DecryptInit_ex(context, NULL, NULL, md, h->iv) != 1)
1469 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to set IV and key: %s",
1470 sym_ERR_error_string(sym_ERR_get_error(), NULL));
1471
1472 if (sym_EVP_DecryptUpdate(context, NULL, &added, input->iov_base, p) != 1)
1473 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to write AAD data: %s",
1474 sym_ERR_error_string(sym_ERR_get_error(), NULL));
1475
1476 plaintext.iov_base = malloc(input->iov_len - p - le32toh(h->tag_size));
1477 if (!plaintext.iov_base)
1478 return -ENOMEM;
1479
1480 if (sym_EVP_DecryptUpdate(
1481 context,
1482 plaintext.iov_base,
1483 &added,
1484 (uint8_t*) input->iov_base + p,
1485 input->iov_len - p - le32toh(h->tag_size)) != 1)
1486 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to decrypt data: %s",
1487 sym_ERR_error_string(sym_ERR_get_error(), NULL));
1488
1489 assert(added >= 0);
1490 assert((size_t) added <= input->iov_len - p - le32toh(h->tag_size));
1491 plaintext.iov_len = added;
1492
1493 if (sym_EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_GCM_SET_TAG, le32toh(h->tag_size), (uint8_t*) input->iov_base + input->iov_len - le32toh(h->tag_size)) != 1)
1494 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to set tag: %s",
1495 sym_ERR_error_string(sym_ERR_get_error(), NULL));
1496
1497 if (sym_EVP_DecryptFinal_ex(context, (uint8_t*) plaintext.iov_base + plaintext.iov_len, &added) != 1)
1498 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Decryption failed (incorrect key?): %s",
1499 sym_ERR_error_string(sym_ERR_get_error(), NULL));
1500
1501 plaintext.iov_len += added;
1502
1503 if (plaintext.iov_len < ALIGN8(offsetof(struct metadata_credential_header, name)))
1504 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Metadata header incomplete.");
1505
1506 m = plaintext.iov_base;
1507
1508 if (le64toh(m->timestamp) != USEC_INFINITY &&
1509 le64toh(m->not_after) != USEC_INFINITY &&
1510 le64toh(m->timestamp) >= le64toh(m->not_after))
1511 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Timestamps of credential are not in order, refusing.");
1512
1513 if (le32toh(m->name_size) > CREDENTIAL_NAME_MAX)
1514 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Embedded credential name too long, refusing.");
1515
1516 hs = ALIGN8(offsetof(struct metadata_credential_header, name) + le32toh(m->name_size));
1517 if (plaintext.iov_len < hs)
1518 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Metadata header incomplete.");
1519
1520 if (le32toh(m->name_size) > 0) {
1521 _cleanup_free_ char *embedded_name = NULL;
1522
1523 r = make_cstring(m->name, le32toh(m->name_size), MAKE_CSTRING_REFUSE_TRAILING_NUL, &embedded_name);
1524 if (r < 0)
1525 return log_error_errno(r, "Unable to convert embedded credential name to C string: %m");
1526
1527 if (!credential_name_valid(embedded_name))
1528 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Embedded credential name is not valid, refusing.");
1529
1530 if (validate_name && !streq(embedded_name, validate_name)) {
1531
1532 r = secure_getenv_bool("SYSTEMD_CREDENTIAL_VALIDATE_NAME");
1533 if (r < 0 && r != -ENXIO)
1534 log_debug_errno(r, "Failed to parse $SYSTEMD_CREDENTIAL_VALIDATE_NAME: %m");
1535 if (r != 0)
1536 return log_error_errno(SYNTHETIC_ERRNO(EDESTADDRREQ), "Embedded credential name '%s' does not match filename '%s', refusing.", embedded_name, validate_name);
1537
1538 log_debug("Embedded credential name '%s' does not match expected name '%s', but configured to use credential anyway.", embedded_name, validate_name);
1539 }
1540 }
1541
1542 if (validate_timestamp != USEC_INFINITY) {
1543 if (le64toh(m->timestamp) != USEC_INFINITY && le64toh(m->timestamp) > validate_timestamp)
1544 log_debug("Credential timestamp is from the future, assuming clock skew.");
1545
1546 if (le64toh(m->not_after) != USEC_INFINITY && le64toh(m->not_after) < validate_timestamp) {
1547
1548 r = secure_getenv_bool("SYSTEMD_CREDENTIAL_VALIDATE_NOT_AFTER");
1549 if (r < 0 && r != -ENXIO)
1550 log_debug_errno(r, "Failed to parse $SYSTEMD_CREDENTIAL_VALIDATE_NOT_AFTER: %m");
1551 if (r != 0)
1552 return log_error_errno(SYNTHETIC_ERRNO(ESTALE), "Credential's time passed, refusing to use.");
1553
1554 log_debug("Credential not-after timestamp has passed, but configured to use credential anyway.");
1555 }
1556 }
1557
1558 if (ret) {
1559 _cleanup_(iovec_done_erase) struct iovec without_metadata = {};
1560
1561 without_metadata.iov_len = plaintext.iov_len - hs;
1562 without_metadata.iov_base = memdup_suffix0((uint8_t*) plaintext.iov_base + hs, without_metadata.iov_len);
1563 if (!without_metadata.iov_base)
1564 return log_oom();
1565
1566 *ret = TAKE_STRUCT(without_metadata);
1567 }
1568
1569 return 0;
1570 }
1571
1572 #else
1573
1574 int get_credential_host_secret(CredentialSecretFlags flags, struct iovec *ret) {
1575 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Support for encrypted credentials not available.");
1576 }
1577
1578 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, uid_t uid, const struct iovec *input, CredentialFlags flags, struct iovec *ret) {
1579 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Support for encrypted credentials not available.");
1580 }
1581
1582 int decrypt_credential_and_warn(const char *validate_name, usec_t validate_timestamp, const char *tpm2_device, const char *tpm2_signature_path, uid_t uid, const struct iovec *input, CredentialFlags flags, struct iovec *ret) {
1583 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Support for encrypted credentials not available.");
1584 }
1585
1586 #endif
1587
1588 int ipc_encrypt_credential(const char *name, usec_t timestamp, usec_t not_after, uid_t uid, const struct iovec *input, CredentialFlags flags, struct iovec *ret) {
1589 _cleanup_(sd_varlink_unrefp) sd_varlink *vl = NULL;
1590 int r;
1591
1592 assert(input && iovec_is_valid(input));
1593 assert(ret);
1594
1595 r = sd_varlink_connect_address(&vl, "/run/systemd/io.systemd.Credentials");
1596 if (r < 0)
1597 return log_error_errno(r, "Failed to connect to io.systemd.Credentials: %m");
1598
1599 /* Mark anything we get from the service as sensitive, given that it might use a NULL cypher, at least in theory */
1600 r = sd_varlink_set_input_sensitive(vl);
1601 if (r < 0)
1602 return log_error_errno(r, "Failed to enable sensitive Varlink input: %m");
1603
1604 /* Create the input data blob object separately, so that we can mark it as sensitive */
1605 _cleanup_(sd_json_variant_unrefp) sd_json_variant *jinput = NULL;
1606 r = sd_json_build(&jinput, JSON_BUILD_IOVEC_BASE64(input));
1607 if (r < 0)
1608 return log_error_errno(r, "Failed to create input object: %m");
1609
1610 sd_json_variant_sensitive(jinput);
1611
1612 sd_json_variant *reply = NULL;
1613 const char *error_id = NULL;
1614 r = sd_varlink_callbo(
1615 vl,
1616 "io.systemd.Credentials.Encrypt",
1617 &reply,
1618 &error_id,
1619 SD_JSON_BUILD_PAIR_CONDITION(!!name, "name", SD_JSON_BUILD_STRING(name)),
1620 SD_JSON_BUILD_PAIR_VARIANT("data", jinput),
1621 SD_JSON_BUILD_PAIR_CONDITION(timestamp != USEC_INFINITY, "timestamp", SD_JSON_BUILD_UNSIGNED(timestamp)),
1622 SD_JSON_BUILD_PAIR_CONDITION(not_after != USEC_INFINITY, "notAfter", SD_JSON_BUILD_UNSIGNED(not_after)),
1623 SD_JSON_BUILD_PAIR_CONDITION(!FLAGS_SET(flags, CREDENTIAL_ANY_SCOPE), "scope", SD_JSON_BUILD_STRING(uid_is_valid(uid) ? "user" : "system")),
1624 SD_JSON_BUILD_PAIR_CONDITION(uid_is_valid(uid), "uid", SD_JSON_BUILD_UNSIGNED(uid)),
1625 SD_JSON_BUILD_PAIR_CONDITION((flags & (CREDENTIAL_ALLOW_NULL|CREDENTIAL_REFUSE_NULL)) != 0, "allowNull", SD_JSON_BUILD_BOOLEAN(flags & CREDENTIAL_ALLOW_NULL)),
1626 SD_JSON_BUILD_PAIR_BOOLEAN("allowInteractiveAuthentication", FLAGS_SET(flags, CREDENTIAL_IPC_ALLOW_INTERACTIVE)));
1627 if (r < 0)
1628 return log_error_errno(r, "Failed to call Encrypt() varlink call.");
1629 if (!isempty(error_id)) {
1630 if (streq(error_id, "io.systemd.Credentials.NoSuchUser"))
1631 return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "No such user.");
1632
1633 return log_error_errno(sd_varlink_error_to_errno(error_id, reply), "Failed to encrypt: %s", error_id);
1634 }
1635
1636 static const sd_json_dispatch_field dispatch_table[] = {
1637 { "blob", SD_JSON_VARIANT_STRING, json_dispatch_unbase64_iovec, 0, SD_JSON_MANDATORY },
1638 {},
1639 };
1640
1641 r = sd_json_dispatch(reply, dispatch_table, SD_JSON_LOG|SD_JSON_ALLOW_EXTENSIONS, ret);
1642 if (r < 0)
1643 return r;
1644
1645 return 0;
1646 }
1647
1648 int ipc_decrypt_credential(const char *validate_name, usec_t validate_timestamp, uid_t uid, const struct iovec *input, CredentialFlags flags, struct iovec *ret) {
1649 _cleanup_(sd_varlink_unrefp) sd_varlink *vl = NULL;
1650 int r;
1651
1652 assert(input && iovec_is_valid(input));
1653 assert(ret);
1654
1655 r = sd_varlink_connect_address(&vl, "/run/systemd/io.systemd.Credentials");
1656 if (r < 0)
1657 return log_error_errno(r, "Failed to connect to io.systemd.Credentials: %m");
1658
1659 r = sd_varlink_set_input_sensitive(vl);
1660 if (r < 0)
1661 return log_error_errno(r, "Failed to enable sensitive Varlink input: %m");
1662
1663 /* Create the input data blob object separately, so that we can mark it as sensitive (it's supposed
1664 * to be encrypted, but who knows maybe it uses the NULL cypher). */
1665 _cleanup_(sd_json_variant_unrefp) sd_json_variant *jinput = NULL;
1666 r = sd_json_build(&jinput, JSON_BUILD_IOVEC_BASE64(input));
1667 if (r < 0)
1668 return log_error_errno(r, "Failed to create input object: %m");
1669
1670 sd_json_variant_sensitive(jinput);
1671
1672 sd_json_variant *reply = NULL;
1673 const char *error_id = NULL;
1674 r = sd_varlink_callbo(
1675 vl,
1676 "io.systemd.Credentials.Decrypt",
1677 &reply,
1678 &error_id,
1679 SD_JSON_BUILD_PAIR_CONDITION(!!validate_name, "name", SD_JSON_BUILD_STRING(validate_name)),
1680 SD_JSON_BUILD_PAIR_VARIANT("blob", jinput),
1681 SD_JSON_BUILD_PAIR_CONDITION(validate_timestamp != USEC_INFINITY, "timestamp", SD_JSON_BUILD_UNSIGNED(validate_timestamp)),
1682 SD_JSON_BUILD_PAIR_CONDITION(!FLAGS_SET(flags, CREDENTIAL_ANY_SCOPE), "scope", SD_JSON_BUILD_STRING(uid_is_valid(uid) ? "user" : "system")),
1683 SD_JSON_BUILD_PAIR_CONDITION(uid_is_valid(uid), "uid", SD_JSON_BUILD_UNSIGNED(uid)),
1684 SD_JSON_BUILD_PAIR_BOOLEAN("allowInteractiveAuthentication", FLAGS_SET(flags, CREDENTIAL_IPC_ALLOW_INTERACTIVE)));
1685 if (r < 0)
1686 return log_error_errno(r, "Failed to call Decrypt() varlink call.");
1687 if (!isempty(error_id)) {
1688 const CredentialsVarlinkError *e = credentials_varlink_error_by_id(error_id);
1689 if (e)
1690 return log_error_errno(SYNTHETIC_ERRNO(e->errnum), "%s", e->msg);
1691
1692 return log_error_errno(sd_varlink_error_to_errno(error_id, reply), "Failed to decrypt: %s", error_id);
1693 }
1694
1695 static const sd_json_dispatch_field dispatch_table[] = {
1696 { "data", SD_JSON_VARIANT_STRING, json_dispatch_unbase64_iovec, 0, SD_JSON_MANDATORY },
1697 {},
1698 };
1699
1700 r = sd_json_dispatch(reply, dispatch_table, SD_JSON_LOG|SD_JSON_ALLOW_EXTENSIONS, ret);
1701 if (r < 0)
1702 return r;
1703
1704 return 0;
1705 }
1706
1707 int get_global_boot_credentials_path(char **ret) {
1708 _cleanup_free_ char *path = NULL;
1709 int r;
1710
1711 assert(ret);
1712
1713 /* Determines where to put global boot credentials in. Returns the path to the "/loader/credentials/"
1714 * directory below the XBOOTLDR or ESP partition. Any credentials placed in this directory can be
1715 * picked up later in the initrd. */
1716
1717 r = find_xbootldr_and_warn(
1718 /* root= */ NULL,
1719 /* path= */ NULL,
1720 /* unprivileged_mode= */ false,
1721 &path,
1722 /* ret_fd= */ NULL);
1723 if (r < 0) {
1724 if (r != -ENOKEY)
1725 return log_error_errno(r, "Failed to find XBOOTLDR partition: %m");
1726
1727 r = find_esp_and_warn(
1728 /* root= */ NULL,
1729 /* path= */ NULL,
1730 /* unprivileged_mode= */ false,
1731 &path,
1732 /* ret_fd= */ NULL);
1733 if (r < 0) {
1734 if (r != -ENOKEY)
1735 return log_error_errno(r, "Failed to find ESP partition: %m");
1736
1737 *ret = NULL;
1738 return 0; /* not found! */
1739 }
1740 }
1741
1742 _cleanup_free_ char *joined = path_join(path, "loader/credentials");
1743 if (!joined)
1744 return log_oom();
1745
1746 log_debug("Determined global boot credentials path as: %s", joined);
1747
1748 *ret = TAKE_PTR(joined);
1749 return 1; /* found! */
1750 }
1751
1752 static int pick_up_credential_one(
1753 int credential_dir_fd,
1754 const char *credential_name,
1755 const PickUpCredential *table_entry) {
1756
1757 _cleanup_free_ char *fn = NULL, *target_path = NULL;
1758 const char *e;
1759 int r;
1760
1761 assert(credential_dir_fd >= 0);
1762 assert(credential_name);
1763 assert(table_entry);
1764
1765 e = startswith(credential_name, table_entry->credential_prefix);
1766 if (!e)
1767 return 0; /* unmatched */
1768
1769 fn = strjoin(e, table_entry->filename_suffix);
1770 if (!fn)
1771 return log_oom();
1772
1773 if (!filename_is_valid(fn))
1774 return log_warning_errno(SYNTHETIC_ERRNO(EINVAL),
1775 "Passed credential '%s' would result in invalid filename '%s'.",
1776 credential_name, fn);
1777
1778 r = mkdir_p_label(table_entry->target_dir, 0755);
1779 if (r < 0)
1780 return log_warning_errno(r, "Failed to create '%s': %m", table_entry->target_dir);
1781
1782 target_path = path_join(table_entry->target_dir, fn);
1783 if (!target_path)
1784 return log_oom();
1785
1786 r = copy_file_at(
1787 credential_dir_fd, credential_name,
1788 AT_FDCWD, target_path,
1789 /* open_flags= */ 0,
1790 0644,
1791 /* copy_flags= */ 0);
1792 if (r < 0)
1793 return log_warning_errno(r, "Failed to copy credential %s → file %s: %m",
1794 credential_name, target_path);
1795
1796 log_info("Installed %s from credential.", target_path);
1797 return 1; /* done */
1798 }
1799
1800 int pick_up_credentials(const PickUpCredential *table, size_t n_table_entry) {
1801 _cleanup_close_ int credential_dir_fd = -EBADF;
1802 int r, ret = 0;
1803
1804 assert(table);
1805 assert(n_table_entry > 0);
1806
1807 credential_dir_fd = open_credentials_dir();
1808 if (IN_SET(credential_dir_fd, -ENXIO, -ENOENT)) {
1809 /* Credential env var not set, or dir doesn't exist. */
1810 log_debug("No credentials found.");
1811 return 0;
1812 }
1813 if (credential_dir_fd < 0)
1814 return log_error_errno(credential_dir_fd, "Failed to open credentials directory: %m");
1815
1816 _cleanup_free_ DirectoryEntries *des = NULL;
1817 r = readdir_all(credential_dir_fd, RECURSE_DIR_SORT|RECURSE_DIR_IGNORE_DOT|RECURSE_DIR_ENSURE_TYPE, &des);
1818 if (r < 0)
1819 return log_error_errno(r, "Failed to enumerate credentials: %m");
1820
1821 FOREACH_ARRAY(i, des->entries, des->n_entries) {
1822 struct dirent *de = *i;
1823
1824 if (de->d_type != DT_REG)
1825 continue;
1826
1827 FOREACH_ARRAY(t, table, n_table_entry) {
1828 r = pick_up_credential_one(credential_dir_fd, de->d_name, t);
1829 if (r != 0) {
1830 RET_GATHER(ret, r);
1831 break; /* Done, or failed. Let's move to the next credential. */
1832 }
1833 }
1834 }
1835
1836 return ret;
1837 }
1838
1839 static const CredentialsVarlinkError credentials_varlink_error_table[] = {
1840 { "io.systemd.Credentials.BadFormat", EBADMSG, "Bad credential format." },
1841 { "io.systemd.Credentials.NameMismatch", EDESTADDRREQ, "Name in credential doesn't match expectations." },
1842 { "io.systemd.Credentials.TimeMismatch", ESTALE, "Outside of credential validity time window." },
1843 { "io.systemd.Credentials.NoSuchUser", ESRCH, "No such user." },
1844 { "io.systemd.Credentials.BadScope", EMEDIUMTYPE, "Scope mismatch." },
1845 { "io.systemd.Credentials.CantFindPCRSignature", EHOSTDOWN, "PCR signature required for decryption, but could not be found." },
1846 { "io.systemd.Credentials.NullKeyNotAllowed", EHWPOISON, "The key was encrypted with a null key, but that's now allowed during decryption." },
1847 { "io.systemd.Credentials.KeyBelongsToOtherTPM", EREMOTE, "The TPM integrity check for this key failed, key probably belongs to another TPM, or was corrupted." },
1848 { "io.systemd.Credentials.TPMInDictionaryLockout", ENOLCK, "The TPM is in dictionary lockout mode, cannot operate." },
1849 { "io.systemd.Credentials.UnexpectedPCRState" , EUCLEAN, "Unexpected TPM PCR state of the system." },
1850 };
1851
1852 const CredentialsVarlinkError* credentials_varlink_error_by_id(const char *id) {
1853 assert(id);
1854
1855 FOREACH_ELEMENT(i, credentials_varlink_error_table)
1856 if (streq(id, i->id))
1857 return i;
1858
1859 return NULL;
1860 }
1861
1862 const CredentialsVarlinkError* credentials_varlink_error_by_errno(int errnum) {
1863 assert(errnum != 0);
1864
1865 errnum = ABS(errnum);
1866
1867 FOREACH_ELEMENT(i, credentials_varlink_error_table)
1868 if (errnum == i->errnum)
1869 return i;
1870
1871 return NULL;
1872 }