1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
6 #include <openssl/err.h>
11 #include "blockdev-util.h"
12 #include "capability-util.h"
13 #include "chattr-util.h"
14 #include "constants.h"
15 #include "creds-util.h"
22 #include "memory-util.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"
33 #define PUBLIC_KEY_MAX (UINT32_C(1024) * UINT32_C(1024))
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
);
41 bool credential_glob_valid(const char *s
) {
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. */
56 /* Find first glob (or NUL byte) */
57 n
= strcspn(s
, "*?[]");
60 /* For now, only allow asterisk wildcards, and only at the end of the string. If it's anything else, refuse. */
62 return credential_name_valid(s
);
64 if (!streq(e
, "*")) /* only allow trailing "*", no other globs */
67 if (n
== 0) /* Explicitly allow the complete wildcard. */
70 if (n
> NAME_MAX
+ strlen(e
)) /* before we make a copy on the stack, let's check this is not overly large */
73 /* Make a copy of the string without the '*' suffix */
74 a
= strndupa_safe(s
, n
);
76 return credential_name_valid(a
);
79 static int get_credentials_dir_internal(const char *envvar
, const char **ret
) {
84 e
= secure_getenv(envvar
);
88 if (!path_is_absolute(e
) || !path_is_normalized(e
))
95 int get_credentials_dir(const char **ret
) {
96 return get_credentials_dir_internal("CREDENTIALS_DIRECTORY", ret
);
99 int get_encrypted_credentials_dir(const char **ret
) {
100 return get_credentials_dir_internal("ENCRYPTED_CREDENTIALS_DIRECTORY", ret
);
103 int open_credentials_dir(void) {
107 r
= get_credentials_dir(&d
);
111 return RET_NERRNO(open(d
, O_CLOEXEC
|O_DIRECTORY
));
114 int read_credential(const char *name
, void **ret
, size_t *ret_size
) {
115 _cleanup_free_
char *fn
= NULL
;
121 if (!credential_name_valid(name
))
124 r
= get_credentials_dir(&d
);
128 fn
= path_join(d
, name
);
132 return read_full_file_full(
134 UINT64_MAX
, SIZE_MAX
,
135 READ_FULL_FILE_SECURE
,
137 (char**) ret
, ret_size
);
140 int read_credential_with_decryption(const char *name
, void **ret
, size_t *ret_size
) {
141 _cleanup_(iovec_done_erase
) struct iovec ret_iovec
= {};
142 _cleanup_(erase_and_freep
) void *data
= NULL
;
143 _cleanup_free_
char *fn
= NULL
;
148 /* Just like read_credential() but will also look for encrypted credentials. Note that services only
149 * receive decrypted credentials, hence use read_credential() for those. This helper here is for
150 * generators, i.e. code that runs outside of service context, and thus has no decrypted credentials
153 * Note that read_credential_harder_and_warn() logs on its own, while read_credential() does not!
154 * (It's a lot more complex and error prone given its TPM2 connectivity, and is generally called from
155 * generators only where logging is OK).
157 * Error handling is also a bit different: if we can't find a credential we'll return 0 and NULL
158 * pointers/zero size, rather than -ENXIO/-ENOENT. */
160 if (!credential_name_valid(name
))
161 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid credential name: %s", name
);
163 r
= read_credential(name
, ret
, ret_size
);
165 return 1; /* found */
166 if (!IN_SET(r
, -ENXIO
, -ENOENT
))
167 return log_error_errno(r
, "Failed read unencrypted credential '%s': %m", name
);
169 r
= get_encrypted_credentials_dir(&d
);
173 return log_error_errno(r
, "Failed to determine encrypted credentials directory: %m");
175 fn
= path_join(d
, name
);
179 r
= read_full_file_full(
181 UINT64_MAX
, SIZE_MAX
,
182 READ_FULL_FILE_SECURE
,
184 (char**) &data
, &sz
);
188 return log_error_errno(r
, "Failed to read encrypted credential data: %m");
190 r
= decrypt_credential_and_warn(
193 /* tpm2_device = */ NULL
,
194 /* tpm2_signature_path = */ NULL
,
195 &IOVEC_MAKE(data
, sz
),
201 *ret
= TAKE_PTR(ret_iovec
.iov_base
);
203 *ret_size
= ret_iovec
.iov_len
;
205 return 1; /* found */
213 return 0; /* not found */
216 int read_credential_strings_many_internal(
217 const char *first_name
, char **first_value
,
220 _cleanup_free_
void *b
= NULL
;
223 /* Reads a bunch of credentials into the specified buffers. If the specified buffers are already
224 * non-NULL frees them if a credential is found. Only supports string-based credentials
225 * (i.e. refuses embedded NUL bytes).
227 * 0 is returned when some or all credentials are missing.
233 r
= read_credential(first_name
, &b
, NULL
);
234 if (r
== -ENXIO
) /* No creds passed at all? Bail immediately. */
240 free_and_replace(*first_value
, b
);
243 va_start(ap
, first_value
);
246 _cleanup_free_
void *bb
= NULL
;
250 name
= va_arg(ap
, const char *);
254 value
= va_arg(ap
, char **);
258 r
= read_credential(name
, &bb
, NULL
);
260 if (ret
>= 0 && r
!= -ENOENT
)
263 free_and_replace(*value
, bb
);
270 int read_credential_bool(const char *name
) {
271 _cleanup_free_
void *data
= NULL
;
274 r
= read_credential(name
, &data
, NULL
);
276 return IN_SET(r
, -ENXIO
, -ENOENT
) ? 0 : r
;
278 return parse_boolean(data
);
281 int get_credential_user_password(const char *username
, char **ret_password
, bool *ret_is_hashed
) {
282 _cleanup_(erase_and_freep
) char *creds_password
= NULL
;
283 _cleanup_free_
char *cn
= NULL
;
286 /* Try to pick up the password for this account via the credentials logic */
287 cn
= strjoin("passwd.hashed-password.", username
);
291 r
= read_credential(cn
, (void**) &creds_password
, NULL
);
294 cn
= strjoin("passwd.plaintext-password.", username
);
298 r
= read_credential(cn
, (void**) &creds_password
, NULL
);
300 log_debug_errno(r
, "Couldn't read credential '%s', ignoring: %m", cn
);
302 *ret_is_hashed
= false;
304 log_debug_errno(r
, "Couldn't read credential '%s', ignoring: %m", cn
);
306 *ret_is_hashed
= true;
308 *ret_password
= TAKE_PTR(creds_password
);
315 #define CREDENTIAL_HOST_SECRET_SIZE 4096
317 static const sd_id128_t credential_app_id
=
318 SD_ID128_MAKE(d3
,ac
,ec
,ba
,0d
,ad
,4c
,df
,b8
,c9
,38,15,28,93,6c
,58);
320 struct credential_host_secret_format
{
321 /* The hashed machine ID of the machine this belongs to. Why? We want to ensure that each machine
322 * gets its own secret, even if people forget to flush out this secret file. Hence we bind it to the
323 * machine ID, for which there's hopefully a better chance it will be flushed out. We use a hashed
324 * machine ID instead of the literal one, because it's trivial to, and it might be a good idea not
325 * being able to directly associate a secret key file with a host. */
326 sd_id128_t machine_id
;
328 /* The actual secret key */
329 uint8_t data
[CREDENTIAL_HOST_SECRET_SIZE
];
332 static void warn_not_encrypted(int fd
, CredentialSecretFlags flags
, const char *dirname
, const char *filename
) {
339 if (!FLAGS_SET(flags
, CREDENTIAL_SECRET_WARN_NOT_ENCRYPTED
))
342 r
= fd_is_encrypted(fd
);
344 log_debug_errno(r
, "Failed to determine if credential secret file '%s/%s' is encrypted.",
347 log_warning("Credential secret file '%s/%s' is not located on encrypted media, using anyway.",
351 static int make_credential_host_secret(
353 const sd_id128_t machine_id
,
354 CredentialSecretFlags flags
,
359 _cleanup_free_
char *t
= NULL
;
360 _cleanup_close_
int fd
= -EBADF
;
366 /* For non-root users creating a temporary file using the openat(2) over "." will fail later, in the
367 * linkat(2) step at the end. The reason is that linkat(2) requires the CAP_DAC_READ_SEARCH
368 * capability when it uses the AT_EMPTY_PATH flag. */
369 if (have_effective_cap(CAP_DAC_READ_SEARCH
) > 0) {
370 fd
= openat(dfd
, ".", O_CLOEXEC
|O_WRONLY
|O_TMPFILE
, 0400);
372 log_debug_errno(errno
, "Failed to create temporary credential file with O_TMPFILE, proceeding without: %m");
375 if (asprintf(&t
, "credential.secret.%016" PRIx64
, random_u64()) < 0)
378 fd
= openat(dfd
, t
, O_CLOEXEC
|O_WRONLY
|O_CREAT
|O_EXCL
|O_NOFOLLOW
, 0400);
383 r
= chattr_secret(fd
, 0);
385 log_debug_errno(r
, "Failed to set file attributes for secrets file, ignoring: %m");
387 struct credential_host_secret_format buf
= {
388 .machine_id
= machine_id
,
393 r
= crypto_random_bytes(buf
.data
, sizeof(buf
.data
));
397 r
= loop_write(fd
, &buf
, sizeof(buf
));
406 warn_not_encrypted(fd
, flags
, dirname
, fn
);
409 r
= rename_noreplace(dfd
, t
, dfd
, fn
);
414 } else if (linkat(fd
, "", dfd
, fn
, AT_EMPTY_PATH
) < 0) {
419 if (fsync(dfd
) < 0) {
427 copy
= memdup(buf
.data
, sizeof(buf
.data
));
433 *ret
= IOVEC_MAKE(copy
, sizeof(buf
.data
));
439 if (t
&& unlinkat(dfd
, t
, 0) < 0)
440 log_debug_errno(errno
, "Failed to remove temporary credential key: %m");
445 int get_credential_host_secret(CredentialSecretFlags flags
, struct iovec
*ret
) {
446 _cleanup_free_
char *_dirname
= NULL
, *_filename
= NULL
;
447 _cleanup_close_
int dfd
= -EBADF
;
448 sd_id128_t machine_id
;
449 const char *dirname
, *filename
;
452 r
= sd_id128_get_machine_app_specific(credential_app_id
, &machine_id
);
456 const char *e
= secure_getenv("SYSTEMD_CREDENTIAL_SECRET");
458 if (!path_is_normalized(e
))
460 if (!path_is_absolute(e
))
463 r
= path_extract_directory(e
, &_dirname
);
467 r
= path_extract_filename(e
, &_filename
);
472 filename
= _filename
;
474 dirname
= "/var/lib/systemd";
475 filename
= "credential.secret";
481 mkdir_parents(dirname
, 0755);
482 dfd
= open_mkdir_at(AT_FDCWD
, dirname
, O_CLOEXEC
, 0755);
484 return log_debug_errno(dfd
, "Failed to create or open directory '%s': %m", dirname
);
486 if (FLAGS_SET(flags
, CREDENTIAL_SECRET_FAIL_ON_TEMPORARY_FS
)) {
487 r
= fd_is_temporary_fs(dfd
);
489 return log_debug_errno(r
, "Failed to check directory '%s': %m", dirname
);
491 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM
),
492 "Directory '%s' is on a temporary file system, refusing.", dirname
);
495 for (unsigned attempt
= 0;; attempt
++) {
496 _cleanup_(erase_and_freep
) struct credential_host_secret_format
*f
= NULL
;
497 _cleanup_close_
int fd
= -EBADF
;
502 if (attempt
>= 3) /* Somebody is playing games with us */
503 return log_debug_errno(SYNTHETIC_ERRNO(EIO
),
504 "All attempts to create secret store in %s failed.", dirname
);
506 fd
= openat(dfd
, filename
, O_CLOEXEC
|O_RDONLY
|O_NOCTTY
|O_NOFOLLOW
);
508 if (errno
!= ENOENT
|| !FLAGS_SET(flags
, CREDENTIAL_SECRET_GENERATE
))
509 return log_debug_errno(errno
,
510 "Failed to open %s/%s: %m", dirname
, filename
);
513 r
= make_credential_host_secret(dfd
, machine_id
, flags
, dirname
, filename
, ret
);
515 log_debug_errno(r
, "Credential secret %s/%s appeared while we were creating it, rereading.",
520 return log_debug_errno(r
, "Failed to create credential secret %s/%s: %m",
525 if (fstat(fd
, &st
) < 0)
526 return log_debug_errno(errno
, "Failed to stat %s/%s: %m", dirname
, filename
);
528 r
= stat_verify_regular(&st
);
530 return log_debug_errno(r
, "%s/%s is not a regular file: %m", dirname
, filename
);
531 if (st
.st_nlink
== 0) /* Deleted by now, try again */
534 /* Our deletion check won't work if hardlinked somewhere else */
535 return log_debug_errno(SYNTHETIC_ERRNO(EPERM
),
536 "%s/%s has too many links, refusing.",
538 if ((st
.st_mode
& 07777) != 0400)
539 /* Don't use file if not 0400 access mode */
540 return log_debug_errno(SYNTHETIC_ERRNO(EPERM
),
541 "%s/%s has permissive access mode, refusing.",
544 if (l
< offsetof(struct credential_host_secret_format
, data
) + 1)
545 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
546 "%s/%s is too small, refusing.", dirname
, filename
);
547 if (l
> 16*1024*1024)
548 return log_debug_errno(SYNTHETIC_ERRNO(E2BIG
),
549 "%s/%s is too big, refusing.", dirname
, filename
);
553 return log_oom_debug();
555 n
= read(fd
, f
, l
+1);
557 return log_debug_errno(errno
,
558 "Failed to read %s/%s: %m", dirname
, filename
);
559 if ((size_t) n
!= l
) /* What? The size changed? */
560 return log_debug_errno(SYNTHETIC_ERRNO(EIO
),
561 "Failed to read %s/%s: %m", dirname
, filename
);
563 if (sd_id128_equal(machine_id
, f
->machine_id
)) {
566 warn_not_encrypted(fd
, flags
, dirname
, filename
);
568 sz
= l
- offsetof(struct credential_host_secret_format
, data
);
574 assert(sz
<= sizeof(f
->data
)); /* Ensure we don't read past f->data bounds */
576 copy
= memdup(f
->data
, sz
);
578 return log_oom_debug();
580 *ret
= IOVEC_MAKE(copy
, sz
);
586 /* Hmm, this secret is from somewhere else. Let's delete the file. Let's first acquire a lock
587 * to ensure we are the only ones accessing the file while we delete it. */
589 if (flock(fd
, LOCK_EX
) < 0)
590 return log_debug_errno(errno
,
591 "Failed to flock %s/%s: %m", dirname
, filename
);
593 /* Before we delete it check that the file is still linked into the file system */
594 if (fstat(fd
, &st
) < 0)
595 return log_debug_errno(errno
, "Failed to stat %s/%s: %m", dirname
, filename
);
596 if (st
.st_nlink
== 0) /* Already deleted by now? */
598 if (st
.st_nlink
!= 1) /* Safety check, someone is playing games with us */
599 return log_debug_errno(SYNTHETIC_ERRNO(EPERM
),
600 "%s/%s unexpectedly has too many links.",
602 if (unlinkat(dfd
, filename
, 0) < 0)
603 return log_debug_errno(errno
, "Failed to unlink %s/%s: %m", dirname
, filename
);
605 /* And now try again */
609 /* Construction is like this:
611 * A symmetric encryption key is derived from:
613 * 1. Either the "host" key (a key stored in /var/lib/credential.secret)
615 * 2. A key generated by letting the TPM2 calculate an HMAC hash of some nonce we pass to it, keyed
616 * by a key derived from its internal seed key.
618 * 3. The concatenation of the above.
620 * 4. Or a fixed "empty" key. This will not provide confidentiality or authenticity, of course, but is
621 * useful to encode credentials for the initrd on TPM-less systems, where we simply have no better
622 * concept to bind things to. Note that decryption of a key set up like this will be refused on
623 * systems that have a TPM and have SecureBoot enabled.
625 * The above is hashed with SHA256 which is then used as encryption key for AES256-GCM. The encrypted
626 * credential is a short (unencrypted) header describing which of the three keys to use, the IV to use for
627 * AES256-GCM and some more meta information (sizes of certain objects) that is strictly speaking redundant,
628 * but kinda nice to have since we can have a more generic parser. If the TPM2 key is used this is followed
629 * by another (unencrypted) header, with information about the TPM2 policy used (specifically: the PCR mask
630 * to bind against, and a hash of the resulting policy — the latter being redundant, but speeding up things a
631 * bit, since we can more quickly refuse PCR state), followed by a sealed/exported TPM2 HMAC key. This is
632 * then followed by the encrypted data, which begins with a metadata header (which contains validity
633 * timestamps as well as the credential name), followed by the actual credential payload. The file ends in
634 * the AES256-GCM tag. To make things simple, the AES256-GCM AAD covers the main and the TPM2 header in
635 * full. This means the whole file is either protected by AAD, or is ciphertext, or is the tag. No
636 * unprotected data is included.
639 struct _packed_ encrypted_credential_header
{
646 /* Followed by NUL bytes until next 8 byte boundary */
649 struct _packed_ tpm2_credential_header
{
650 le64_t pcr_mask
; /* Note that the spec for PC Clients only mandates 24 PCRs, and that's what systems
651 * generally have. But keep the door open for more. */
652 le16_t pcr_bank
; /* For now, either TPM2_ALG_SHA256 or TPM2_ALG_SHA1 */
653 le16_t primary_alg
; /* Primary key algorithm (either TPM2_ALG_RSA or TPM2_ALG_ECC for now) */
655 le32_t policy_hash_size
;
656 uint8_t policy_hash_and_blob
[];
657 /* Followed by NUL bytes until next 8 byte boundary */
660 struct _packed_ tpm2_public_key_credential_header
{
661 le64_t pcr_mask
; /* PCRs used for the public key PCR policy (usually just PCR 11, i.e. the unified kernel) */
662 le32_t size
; /* Size of DER public key */
663 uint8_t data
[]; /* DER public key */
664 /* Followed by NUL bytes until next 8 byte boundary */
667 struct _packed_ metadata_credential_header
{
672 /* Followed by NUL bytes until next 8 byte boundary */
675 /* Some generic limit for parts of the encrypted credential for which we don't know the right size ahead of
676 * time, but where we are really sure it won't be larger than this. Should be larger than any possible IV,
677 * padding, tag size and so on. This is purely used for early filtering out of invalid sizes. */
678 #define CREDENTIAL_FIELD_SIZE_MAX (16U*1024U)
680 static int sha256_hash_host_and_tpm2_key(
681 const struct iovec
*host_key
,
682 const struct iovec
*tpm2_key
,
683 uint8_t ret
[static SHA256_DIGEST_LENGTH
]) {
685 _cleanup_(EVP_MD_CTX_freep
) EVP_MD_CTX
*md
= NULL
;
688 assert(iovec_is_valid(host_key
));
689 assert(iovec_is_valid(tpm2_key
));
692 /* Combines the host key and the TPM2 HMAC hash into a SHA256 hash value we'll use as symmetric encryption key. */
694 md
= EVP_MD_CTX_new();
698 if (EVP_DigestInit_ex(md
, EVP_sha256(), NULL
) != 1)
699 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initial SHA256 context.");
701 if (iovec_is_set(host_key
) && EVP_DigestUpdate(md
, host_key
->iov_base
, host_key
->iov_len
) != 1)
702 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to hash host key.");
704 if (iovec_is_set(tpm2_key
) && EVP_DigestUpdate(md
, tpm2_key
->iov_base
, tpm2_key
->iov_len
) != 1)
705 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to hash TPM2 key.");
707 assert(EVP_MD_CTX_size(md
) == SHA256_DIGEST_LENGTH
);
709 if (EVP_DigestFinal_ex(md
, ret
, &l
) != 1)
710 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finalize SHA256 hash.");
712 assert(l
== SHA256_DIGEST_LENGTH
);
716 int encrypt_credential_and_warn(
721 const char *tpm2_device
,
722 uint32_t tpm2_hash_pcr_mask
,
723 const char *tpm2_pubkey_path
,
724 uint32_t tpm2_pubkey_pcr_mask
,
725 const struct iovec
*input
,
728 _cleanup_(iovec_done
) struct iovec tpm2_blob
= {}, tpm2_policy_hash
= {}, iv
= {}, pubkey
= {};
729 _cleanup_(iovec_done_erase
) struct iovec tpm2_key
= {}, output
= {}, host_key
= {};
730 _cleanup_(EVP_CIPHER_CTX_freep
) EVP_CIPHER_CTX
*context
= NULL
;
731 _cleanup_free_
struct metadata_credential_header
*m
= NULL
;
732 uint16_t tpm2_pcr_bank
= 0, tpm2_primary_alg
= 0;
733 struct encrypted_credential_header
*h
;
734 int ksz
, bsz
, ivsz
, tsz
, added
, r
;
735 uint8_t md
[SHA256_DIGEST_LENGTH
];
736 const EVP_CIPHER
*cc
;
740 assert(iovec_is_valid(input
));
743 if (!sd_id128_in_set(with_key
,
746 CRED_AES256_GCM_BY_HOST
,
747 CRED_AES256_GCM_BY_TPM2_HMAC
,
748 CRED_AES256_GCM_BY_TPM2_HMAC_WITH_PK
,
749 CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC
,
750 CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK
,
751 CRED_AES256_GCM_BY_NULL
))
752 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid key type: " SD_ID128_FORMAT_STR
, SD_ID128_FORMAT_VAL(with_key
));
754 if (name
&& !credential_name_valid(name
))
755 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid credential name: %s", name
);
757 if (not_after
!= USEC_INFINITY
&& timestamp
!= USEC_INFINITY
&& not_after
< timestamp
)
758 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Credential is invalidated before it is valid (" USEC_FMT
" < " USEC_FMT
").", not_after
, timestamp
);
761 char buf
[FORMAT_TIMESTAMP_MAX
];
764 log_debug("Including credential name '%s' in encrypted credential.", name
);
765 if (timestamp
!= USEC_INFINITY
)
766 log_debug("Including timestamp '%s' in encrypted credential.", format_timestamp(buf
, sizeof(buf
), timestamp
));
767 if (not_after
!= USEC_INFINITY
)
768 log_debug("Including not-after timestamp '%s' in encrypted credential.", format_timestamp(buf
, sizeof(buf
), not_after
));
771 if (sd_id128_in_set(with_key
,
773 CRED_AES256_GCM_BY_HOST
,
774 CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC
,
775 CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK
)) {
777 r
= get_credential_host_secret(
778 CREDENTIAL_SECRET_GENERATE
|
779 CREDENTIAL_SECRET_WARN_NOT_ENCRYPTED
|
780 (sd_id128_equal(with_key
, _CRED_AUTO
) ? CREDENTIAL_SECRET_FAIL_ON_TEMPORARY_FS
: 0),
782 if (r
== -ENOMEDIUM
&& sd_id128_equal(with_key
, _CRED_AUTO
))
783 log_debug_errno(r
, "Credential host secret location on temporary file system, not using.");
785 return log_error_errno(r
, "Failed to determine local credential host secret: %m");
790 if (sd_id128_in_set(with_key
, _CRED_AUTO
, _CRED_AUTO_INITRD
)) {
791 /* If automatic mode is selected lets see if a TPM2 it is present. If we are running in a
792 * container tpm2_support will detect this, and will return a different flag combination of
793 * TPM2_SUPPORT_FULL, effectively skipping the use of TPM2 when inside one. */
795 try_tpm2
= tpm2_support() == TPM2_SUPPORT_FULL
;
797 log_debug("System lacks TPM2 support or running in a container, not attempting to use TPM2.");
799 try_tpm2
= sd_id128_in_set(with_key
,
800 CRED_AES256_GCM_BY_TPM2_HMAC
,
801 CRED_AES256_GCM_BY_TPM2_HMAC_WITH_PK
,
802 CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC
,
803 CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK
);
806 if (sd_id128_in_set(with_key
,
809 CRED_AES256_GCM_BY_TPM2_HMAC_WITH_PK
,
810 CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK
)) {
812 /* Load public key for PCR policies, if one is specified, or explicitly requested */
814 r
= tpm2_load_pcr_public_key(tpm2_pubkey_path
, &pubkey
.iov_base
, &pubkey
.iov_len
);
816 if (tpm2_pubkey_path
|| r
!= -ENOENT
|| !sd_id128_in_set(with_key
, _CRED_AUTO
, _CRED_AUTO_INITRD
))
817 return log_error_errno(r
, "Failed read TPM PCR public key: %m");
819 log_debug_errno(r
, "Failed to read TPM2 PCR public key, proceeding without: %m");
823 if (!iovec_is_set(&pubkey
))
824 tpm2_pubkey_pcr_mask
= 0;
826 _cleanup_(tpm2_context_unrefp
) Tpm2Context
*tpm2_context
= NULL
;
827 r
= tpm2_context_new(tpm2_device
, &tpm2_context
);
829 return log_error_errno(r
, "Failed to create TPM2 context: %m");
831 r
= tpm2_get_best_pcr_bank(tpm2_context
, tpm2_hash_pcr_mask
| tpm2_pubkey_pcr_mask
, &tpm2_pcr_bank
);
833 return log_error_errno(r
, "Could not find best pcr bank: %m");
835 TPML_PCR_SELECTION tpm2_hash_pcr_selection
;
836 tpm2_tpml_pcr_selection_from_mask(tpm2_hash_pcr_mask
, tpm2_pcr_bank
, &tpm2_hash_pcr_selection
);
838 _cleanup_free_ Tpm2PCRValue
*tpm2_hash_pcr_values
= NULL
;
839 size_t tpm2_n_hash_pcr_values
;
840 r
= tpm2_pcr_read(tpm2_context
, &tpm2_hash_pcr_selection
, &tpm2_hash_pcr_values
, &tpm2_n_hash_pcr_values
);
842 return log_error_errno(r
, "Could not read PCR values: %m");
845 if (iovec_is_set(&pubkey
)) {
846 r
= tpm2_tpm2b_public_from_pem(pubkey
.iov_base
, pubkey
.iov_len
, &public);
848 return log_error_errno(r
, "Could not convert public key to TPM2B_PUBLIC: %m");
851 TPM2B_DIGEST tpm2_policy
= TPM2B_DIGEST_MAKE(NULL
, TPM2_SHA256_DIGEST_SIZE
);
852 r
= tpm2_calculate_sealing_policy(
853 tpm2_hash_pcr_values
,
854 tpm2_n_hash_pcr_values
,
855 iovec_is_set(&pubkey
) ? &public : NULL
,
856 /* use_pin= */ false,
857 /* pcrlock_policy= */ NULL
,
860 return log_error_errno(r
, "Could not calculate sealing policy digest: %m");
862 r
= tpm2_seal(tpm2_context
,
863 /* seal_key_handle= */ 0,
869 /* ret_srk= */ NULL
);
871 if (sd_id128_equal(with_key
, _CRED_AUTO_INITRD
))
872 log_warning("TPM2 present and used, but we didn't manage to talk to it. Credential will be refused if SecureBoot is enabled.");
873 else if (!sd_id128_equal(with_key
, _CRED_AUTO
))
874 return log_error_errno(r
, "Failed to seal to TPM2: %m");
876 log_notice_errno(r
, "TPM2 sealing didn't work, continuing without TPM2: %m");
879 if (!iovec_memdup(&IOVEC_MAKE(tpm2_policy
.buffer
, tpm2_policy
.size
), &tpm2_policy_hash
))
882 assert(tpm2_blob
.iov_len
<= CREDENTIAL_FIELD_SIZE_MAX
);
883 assert(tpm2_policy_hash
.iov_len
<= CREDENTIAL_FIELD_SIZE_MAX
);
887 if (sd_id128_in_set(with_key
, _CRED_AUTO
, _CRED_AUTO_INITRD
)) {
888 /* Let's settle the key type in auto mode now. */
890 if (iovec_is_set(&host_key
) && iovec_is_set(&tpm2_key
))
891 id
= iovec_is_set(&pubkey
) ? CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK
: CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC
;
892 else if (iovec_is_set(&tpm2_key
))
893 id
= iovec_is_set(&pubkey
) ? CRED_AES256_GCM_BY_TPM2_HMAC_WITH_PK
: CRED_AES256_GCM_BY_TPM2_HMAC
;
894 else if (iovec_is_set(&host_key
))
895 id
= CRED_AES256_GCM_BY_HOST
;
896 else if (sd_id128_equal(with_key
, _CRED_AUTO_INITRD
))
897 id
= CRED_AES256_GCM_BY_NULL
;
899 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
900 "TPM2 not available and host key located on temporary file system, no encryption key available.");
904 if (sd_id128_equal(id
, CRED_AES256_GCM_BY_NULL
))
905 log_warning("Using a null key for encryption and signing. Confidentiality or authenticity will not be provided.");
907 /* Let's now take the host key and the TPM2 key and hash it together, to use as encryption key for the data */
908 r
= sha256_hash_host_and_tpm2_key(&host_key
, &tpm2_key
, md
);
912 assert_se(cc
= EVP_aes_256_gcm());
914 ksz
= EVP_CIPHER_key_length(cc
);
915 assert(ksz
== sizeof(md
));
917 bsz
= EVP_CIPHER_block_size(cc
);
919 assert((size_t) bsz
<= CREDENTIAL_FIELD_SIZE_MAX
);
921 ivsz
= EVP_CIPHER_iv_length(cc
);
923 assert((size_t) ivsz
<= CREDENTIAL_FIELD_SIZE_MAX
);
925 iv
.iov_base
= malloc(ivsz
);
931 r
= crypto_random_bytes(iv
.iov_base
, iv
.iov_len
);
933 return log_error_errno(r
, "Failed to acquired randomized IV: %m");
936 tsz
= 16; /* FIXME: On OpenSSL 3 there is EVP_CIPHER_CTX_get_tag_length(), until then let's hardcode this */
938 context
= EVP_CIPHER_CTX_new();
940 return log_error_errno(SYNTHETIC_ERRNO(ENOMEM
), "Failed to allocate encryption object: %s",
941 ERR_error_string(ERR_get_error(), NULL
));
943 if (EVP_EncryptInit_ex(context
, cc
, NULL
, md
, iv
.iov_base
) != 1)
944 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initialize encryption context: %s",
945 ERR_error_string(ERR_get_error(), NULL
));
947 /* Just an upper estimate */
949 ALIGN8(offsetof(struct encrypted_credential_header
, iv
) + ivsz
) +
950 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) +
951 ALIGN8(iovec_is_set(&pubkey
) ? offsetof(struct tpm2_public_key_credential_header
, data
) + pubkey
.iov_len
: 0) +
952 ALIGN8(offsetof(struct metadata_credential_header
, name
) + strlen_ptr(name
)) +
953 input
->iov_len
+ 2U * (size_t) bsz
+
956 output
.iov_base
= malloc0(output
.iov_len
);
957 if (!output
.iov_base
)
960 h
= (struct encrypted_credential_header
*) output
.iov_base
;
962 h
->block_size
= htole32(bsz
);
963 h
->key_size
= htole32(ksz
);
964 h
->tag_size
= htole32(tsz
);
965 h
->iv_size
= htole32(ivsz
);
966 memcpy(h
->iv
, iv
.iov_base
, ivsz
);
968 p
= ALIGN8(offsetof(struct encrypted_credential_header
, iv
) + ivsz
);
970 if (iovec_is_set(&tpm2_key
)) {
971 struct tpm2_credential_header
*t
;
973 t
= (struct tpm2_credential_header
*) ((uint8_t*) output
.iov_base
+ p
);
974 t
->pcr_mask
= htole64(tpm2_hash_pcr_mask
);
975 t
->pcr_bank
= htole16(tpm2_pcr_bank
);
976 t
->primary_alg
= htole16(tpm2_primary_alg
);
977 t
->blob_size
= htole32(tpm2_blob
.iov_len
);
978 t
->policy_hash_size
= htole32(tpm2_policy_hash
.iov_len
);
979 memcpy(t
->policy_hash_and_blob
, tpm2_blob
.iov_base
, tpm2_blob
.iov_len
);
980 memcpy(t
->policy_hash_and_blob
+ tpm2_blob
.iov_len
, tpm2_policy_hash
.iov_base
, tpm2_policy_hash
.iov_len
);
982 p
+= ALIGN8(offsetof(struct tpm2_credential_header
, policy_hash_and_blob
) + tpm2_blob
.iov_len
+ tpm2_policy_hash
.iov_len
);
985 if (iovec_is_set(&pubkey
)) {
986 struct tpm2_public_key_credential_header
*z
;
988 z
= (struct tpm2_public_key_credential_header
*) ((uint8_t*) output
.iov_base
+ p
);
989 z
->pcr_mask
= htole64(tpm2_pubkey_pcr_mask
);
990 z
->size
= htole32(pubkey
.iov_len
);
991 memcpy(z
->data
, pubkey
.iov_base
, pubkey
.iov_len
);
993 p
+= ALIGN8(offsetof(struct tpm2_public_key_credential_header
, data
) + pubkey
.iov_len
);
996 /* Pass the encrypted + TPM2 header as AAD */
997 if (EVP_EncryptUpdate(context
, NULL
, &added
, output
.iov_base
, p
) != 1)
998 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to write AAD data: %s",
999 ERR_error_string(ERR_get_error(), NULL
));
1001 /* Now construct the metadata header */
1002 ml
= strlen_ptr(name
);
1003 m
= malloc0(ALIGN8(offsetof(struct metadata_credential_header
, name
) + ml
));
1007 m
->timestamp
= htole64(timestamp
);
1008 m
->not_after
= htole64(not_after
);
1009 m
->name_size
= htole32(ml
);
1010 memcpy_safe(m
->name
, name
, ml
);
1012 /* And encrypt the metadata header */
1013 if (EVP_EncryptUpdate(context
, (uint8_t*) output
.iov_base
+ p
, &added
, (const unsigned char*) m
, ALIGN8(offsetof(struct metadata_credential_header
, name
) + ml
)) != 1)
1014 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to encrypt metadata header: %s",
1015 ERR_error_string(ERR_get_error(), NULL
));
1018 assert((size_t) added
<= output
.iov_len
- p
);
1021 /* Then encrypt the plaintext */
1022 if (EVP_EncryptUpdate(context
, (uint8_t*) output
.iov_base
+ p
, &added
, input
->iov_base
, input
->iov_len
) != 1)
1023 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to encrypt data: %s",
1024 ERR_error_string(ERR_get_error(), NULL
));
1027 assert((size_t) added
<= output
.iov_len
- p
);
1031 if (EVP_EncryptFinal_ex(context
, (uint8_t*) output
.iov_base
+ p
, &added
) != 1)
1032 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finalize data encryption: %s",
1033 ERR_error_string(ERR_get_error(), NULL
));
1036 assert((size_t) added
<= output
.iov_len
- p
);
1039 assert(p
<= output
.iov_len
- tsz
);
1042 if (EVP_CIPHER_CTX_ctrl(context
, EVP_CTRL_GCM_GET_TAG
, tsz
, (uint8_t*) output
.iov_base
+ p
) != 1)
1043 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to get tag: %s",
1044 ERR_error_string(ERR_get_error(), NULL
));
1047 assert(p
<= output
.iov_len
);
1050 if (DEBUG_LOGGING
&& input
->iov_len
> 0) {
1053 base64_size
= DIV_ROUND_UP(output
.iov_len
* 4, 3); /* Include base64 size increase in debug output */
1054 assert(base64_size
>= input
->iov_len
);
1055 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);
1058 *ret
= TAKE_STRUCT(output
);
1062 int decrypt_credential_and_warn(
1063 const char *validate_name
,
1064 usec_t validate_timestamp
,
1065 const char *tpm2_device
,
1066 const char *tpm2_signature_path
,
1067 const struct iovec
*input
,
1068 struct iovec
*ret
) {
1070 _cleanup_(iovec_done_erase
) struct iovec host_key
= {}, plaintext
= {}, tpm2_key
= {};
1071 _cleanup_(json_variant_unrefp
) JsonVariant
*signature_json
= NULL
;
1072 _cleanup_(EVP_CIPHER_CTX_freep
) EVP_CIPHER_CTX
*context
= NULL
;
1073 struct encrypted_credential_header
*h
;
1074 struct metadata_credential_header
*m
;
1075 uint8_t md
[SHA256_DIGEST_LENGTH
];
1076 bool with_tpm2
, with_tpm2_pk
, with_host_key
, with_null
;
1077 const EVP_CIPHER
*cc
;
1081 assert(iovec_is_valid(input
));
1084 h
= (struct encrypted_credential_header
*) input
->iov_base
;
1086 /* The ID must fit in, for the current and all future formats */
1087 if (input
->iov_len
< sizeof(h
->id
))
1088 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Encrypted file too short.");
1090 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
);
1091 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
);
1092 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
;
1093 with_null
= sd_id128_equal(h
->id
, CRED_AES256_GCM_BY_NULL
);
1095 if (!with_host_key
&& !with_tpm2
&& !with_null
)
1096 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "Unknown encryption format, or corrupted data: %m");
1099 r
= tpm2_load_pcr_signature(tpm2_signature_path
, &signature_json
);
1101 return log_error_errno(r
, "Failed to load pcr signature: %m");
1105 /* So this is a credential encrypted with a zero length key. We support this to cover for the
1106 * case where neither a host key not a TPM2 are available (specifically: initrd environments
1107 * where the host key is not yet accessible and no TPM2 chip exists at all), to minimize
1108 * different codeflow for TPM2 and non-TPM2 codepaths. Of course, credentials encoded this
1109 * way offer no confidentiality nor authenticity. Because of that it's important we refuse to
1110 * use them on systems that actually *do* have a TPM2 chip – if we are in SecureBoot
1111 * mode. Otherwise an attacker could hand us credentials like this and we'd use them thinking
1112 * they are trusted, even though they are not. */
1114 if (efi_has_tpm2()) {
1115 if (is_efi_secure_boot())
1116 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
1117 "Credential uses fixed key for fallback use when TPM2 is absent — but TPM2 is present, and SecureBoot is enabled, refusing.");
1119 log_warning("Credential uses fixed key for use when TPM2 is absent, but TPM2 is present! Accepting anyway, since SecureBoot is disabled.");
1121 log_debug("Credential uses fixed key for use when TPM2 is absent, and TPM2 indeed is absent. Accepting.");
1124 /* Now we know the minimum header size */
1125 if (input
->iov_len
< offsetof(struct encrypted_credential_header
, iv
))
1126 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Encrypted file too short.");
1128 /* Verify some basic header values */
1129 if (le32toh(h
->key_size
) != sizeof(md
))
1130 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Unexpected key size in header.");
1131 if (le32toh(h
->block_size
) <= 0 || le32toh(h
->block_size
) > CREDENTIAL_FIELD_SIZE_MAX
)
1132 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Unexpected block size in header.");
1133 if (le32toh(h
->iv_size
) > CREDENTIAL_FIELD_SIZE_MAX
)
1134 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "IV size too large.");
1135 if (le32toh(h
->tag_size
) != 16) /* FIXME: On OpenSSL 3, let's verify via EVP_CIPHER_CTX_get_tag_length() */
1136 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Unexpected tag size in header.");
1138 /* Ensure we have space for the full header now (we don't know the size of the name hence this is a
1139 * lower limit only) */
1140 if (input
->iov_len
<
1141 ALIGN8(offsetof(struct encrypted_credential_header
, iv
) + le32toh(h
->iv_size
)) +
1142 ALIGN8(with_tpm2
? offsetof(struct tpm2_credential_header
, policy_hash_and_blob
) : 0) +
1143 ALIGN8(with_tpm2_pk
? offsetof(struct tpm2_public_key_credential_header
, data
) : 0) +
1144 ALIGN8(offsetof(struct metadata_credential_header
, name
)) +
1145 le32toh(h
->tag_size
))
1146 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Encrypted file too short.");
1148 p
= ALIGN8(offsetof(struct encrypted_credential_header
, iv
) + le32toh(h
->iv_size
));
1152 struct tpm2_credential_header
* t
= (struct tpm2_credential_header
*) ((uint8_t*) input
->iov_base
+ p
);
1153 struct tpm2_public_key_credential_header
*z
= NULL
;
1155 if (!TPM2_PCR_MASK_VALID(t
->pcr_mask
))
1156 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "TPM2 PCR mask out of range.");
1157 if (!tpm2_hash_alg_to_string(le16toh(t
->pcr_bank
)))
1158 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "TPM2 PCR bank invalid or not supported");
1159 if (!tpm2_asym_alg_to_string(le16toh(t
->primary_alg
)))
1160 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "TPM2 primary key algorithm invalid or not supported.");
1161 if (le32toh(t
->blob_size
) > CREDENTIAL_FIELD_SIZE_MAX
)
1162 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Unexpected TPM2 blob size.");
1163 if (le32toh(t
->policy_hash_size
) > CREDENTIAL_FIELD_SIZE_MAX
)
1164 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Unexpected TPM2 policy hash size.");
1166 /* Ensure we have space for the full TPM2 header now (still don't know the name, and its size
1167 * though, hence still just a lower limit test only) */
1168 if (input
->iov_len
<
1169 ALIGN8(offsetof(struct encrypted_credential_header
, iv
) + le32toh(h
->iv_size
)) +
1170 ALIGN8(offsetof(struct tpm2_credential_header
, policy_hash_and_blob
) + le32toh(t
->blob_size
) + le32toh(t
->policy_hash_size
)) +
1171 ALIGN8(with_tpm2_pk
? offsetof(struct tpm2_public_key_credential_header
, data
) : 0) +
1172 ALIGN8(offsetof(struct metadata_credential_header
, name
)) +
1173 le32toh(h
->tag_size
))
1174 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Encrypted file too short.");
1176 p
+= ALIGN8(offsetof(struct tpm2_credential_header
, policy_hash_and_blob
) +
1177 le32toh(t
->blob_size
) +
1178 le32toh(t
->policy_hash_size
));
1181 z
= (struct tpm2_public_key_credential_header
*) ((uint8_t*) input
->iov_base
+ p
);
1183 if (!TPM2_PCR_MASK_VALID(le64toh(z
->pcr_mask
)) || le64toh(z
->pcr_mask
) == 0)
1184 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "TPM2 PCR mask out of range.");
1185 if (le32toh(z
->size
) > PUBLIC_KEY_MAX
)
1186 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Unexpected public key size.");
1188 if (input
->iov_len
<
1189 ALIGN8(offsetof(struct encrypted_credential_header
, iv
) + le32toh(h
->iv_size
)) +
1190 ALIGN8(offsetof(struct tpm2_credential_header
, policy_hash_and_blob
) + le32toh(t
->blob_size
) + le32toh(t
->policy_hash_size
)) +
1191 ALIGN8(offsetof(struct tpm2_public_key_credential_header
, data
) + le32toh(z
->size
)) +
1192 ALIGN8(offsetof(struct metadata_credential_header
, name
)) +
1193 le32toh(h
->tag_size
))
1194 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Encrypted file too short.");
1196 p
+= ALIGN8(offsetof(struct tpm2_public_key_credential_header
, data
) +
1200 _cleanup_(tpm2_context_unrefp
) Tpm2Context
*tpm2_context
= NULL
;
1201 r
= tpm2_context_new(tpm2_device
, &tpm2_context
);
1205 // TODO: Add the SRK data to the credential structure so it can be plumbed
1206 // through and used to verify the TPM session.
1207 r
= tpm2_unseal(tpm2_context
,
1208 le64toh(t
->pcr_mask
),
1209 le16toh(t
->pcr_bank
),
1210 z
? &IOVEC_MAKE(z
->data
, le32toh(z
->size
)) : NULL
,
1211 z
? le64toh(z
->pcr_mask
) : 0,
1214 /* pcrlock_policy= */ NULL
,
1215 le16toh(t
->primary_alg
),
1216 &IOVEC_MAKE(t
->policy_hash_and_blob
, le32toh(t
->blob_size
)),
1217 &IOVEC_MAKE(t
->policy_hash_and_blob
+ le32toh(t
->blob_size
), le32toh(t
->policy_hash_size
)),
1221 return log_error_errno(r
, "Failed to unseal secret using TPM2: %m");
1223 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "Credential requires TPM2 support, but TPM2 support not available.");
1227 if (with_host_key
) {
1228 r
= get_credential_host_secret(/* flags= */ 0, &host_key
);
1230 return log_error_errno(r
, "Failed to determine local credential key: %m");
1234 log_warning("Warning: using a null key for decryption and authentication. Confidentiality or authenticity are not provided.");
1236 sha256_hash_host_and_tpm2_key(&host_key
, &tpm2_key
, md
);
1238 assert_se(cc
= EVP_aes_256_gcm());
1240 /* Make sure cipher expectations match the header */
1241 if (EVP_CIPHER_key_length(cc
) != (int) le32toh(h
->key_size
))
1242 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Unexpected key size in header.");
1243 if (EVP_CIPHER_block_size(cc
) != (int) le32toh(h
->block_size
))
1244 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Unexpected block size in header.");
1246 context
= EVP_CIPHER_CTX_new();
1248 return log_error_errno(SYNTHETIC_ERRNO(ENOMEM
), "Failed to allocate decryption object: %s",
1249 ERR_error_string(ERR_get_error(), NULL
));
1251 if (EVP_DecryptInit_ex(context
, cc
, NULL
, NULL
, NULL
) != 1)
1252 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initialize decryption context: %s",
1253 ERR_error_string(ERR_get_error(), NULL
));
1255 if (EVP_CIPHER_CTX_ctrl(context
, EVP_CTRL_GCM_SET_IVLEN
, le32toh(h
->iv_size
), NULL
) != 1)
1256 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to set IV size on decryption context: %s",
1257 ERR_error_string(ERR_get_error(), NULL
));
1259 if (EVP_DecryptInit_ex(context
, NULL
, NULL
, md
, h
->iv
) != 1)
1260 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to set IV and key: %s",
1261 ERR_error_string(ERR_get_error(), NULL
));
1263 if (EVP_DecryptUpdate(context
, NULL
, &added
, input
->iov_base
, p
) != 1)
1264 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to write AAD data: %s",
1265 ERR_error_string(ERR_get_error(), NULL
));
1267 plaintext
.iov_base
= malloc(input
->iov_len
- p
- le32toh(h
->tag_size
));
1268 if (!plaintext
.iov_base
)
1271 if (EVP_DecryptUpdate(
1275 (uint8_t*) input
->iov_base
+ p
,
1276 input
->iov_len
- p
- le32toh(h
->tag_size
)) != 1)
1277 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to decrypt data: %s",
1278 ERR_error_string(ERR_get_error(), NULL
));
1281 assert((size_t) added
<= input
->iov_len
- p
- le32toh(h
->tag_size
));
1282 plaintext
.iov_len
= added
;
1284 if (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)
1285 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to set tag: %s",
1286 ERR_error_string(ERR_get_error(), NULL
));
1288 if (EVP_DecryptFinal_ex(context
, (uint8_t*) plaintext
.iov_base
+ plaintext
.iov_len
, &added
) != 1)
1289 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Decryption failed (incorrect key?): %s",
1290 ERR_error_string(ERR_get_error(), NULL
));
1292 plaintext
.iov_len
+= added
;
1294 if (plaintext
.iov_len
< ALIGN8(offsetof(struct metadata_credential_header
, name
)))
1295 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Metadata header incomplete.");
1297 m
= plaintext
.iov_base
;
1299 if (le64toh(m
->timestamp
) != USEC_INFINITY
&&
1300 le64toh(m
->not_after
) != USEC_INFINITY
&&
1301 le64toh(m
->timestamp
) >= le64toh(m
->not_after
))
1302 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Timestamps of credential are not in order, refusing.");
1304 if (le32toh(m
->name_size
) > CREDENTIAL_NAME_MAX
)
1305 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Embedded credential name too long, refusing.");
1307 hs
= ALIGN8(offsetof(struct metadata_credential_header
, name
) + le32toh(m
->name_size
));
1308 if (plaintext
.iov_len
< hs
)
1309 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Metadata header incomplete.");
1311 if (le32toh(m
->name_size
) > 0) {
1312 _cleanup_free_
char *embedded_name
= NULL
;
1314 r
= make_cstring(m
->name
, le32toh(m
->name_size
), MAKE_CSTRING_REFUSE_TRAILING_NUL
, &embedded_name
);
1316 return log_error_errno(r
, "Unable to convert embedded credential name to C string: %m");
1318 if (!credential_name_valid(embedded_name
))
1319 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Embedded credential name is not valid, refusing.");
1321 if (validate_name
&& !streq(embedded_name
, validate_name
)) {
1323 r
= getenv_bool_secure("SYSTEMD_CREDENTIAL_VALIDATE_NAME");
1324 if (r
< 0 && r
!= -ENXIO
)
1325 log_debug_errno(r
, "Failed to parse $SYSTEMD_CREDENTIAL_VALIDATE_NAME: %m");
1327 return log_error_errno(SYNTHETIC_ERRNO(EREMOTE
), "Embedded credential name '%s' does not match filename '%s', refusing.", embedded_name
, validate_name
);
1329 log_debug("Embedded credential name '%s' does not match expected name '%s', but configured to use credential anyway.", embedded_name
, validate_name
);
1333 if (validate_timestamp
!= USEC_INFINITY
) {
1334 if (le64toh(m
->timestamp
) != USEC_INFINITY
&& le64toh(m
->timestamp
) > validate_timestamp
)
1335 log_debug("Credential timestamp is from the future, assuming clock skew.");
1337 if (le64toh(m
->not_after
) != USEC_INFINITY
&& le64toh(m
->not_after
) < validate_timestamp
) {
1339 r
= getenv_bool_secure("SYSTEMD_CREDENTIAL_VALIDATE_NOT_AFTER");
1340 if (r
< 0 && r
!= -ENXIO
)
1341 log_debug_errno(r
, "Failed to parse $SYSTEMD_CREDENTIAL_VALIDATE_NOT_AFTER: %m");
1343 return log_error_errno(SYNTHETIC_ERRNO(ESTALE
), "Credential's time passed, refusing to use.");
1345 log_debug("Credential not-after timestamp has passed, but configured to use credential anyway.");
1350 _cleanup_(iovec_done_erase
) struct iovec without_metadata
= {};
1352 without_metadata
.iov_len
= plaintext
.iov_len
- hs
;
1353 without_metadata
.iov_base
= memdup_suffix0((uint8_t*) plaintext
.iov_base
+ hs
, without_metadata
.iov_len
);
1354 if (!without_metadata
.iov_base
)
1357 *ret
= TAKE_STRUCT(without_metadata
);
1365 int get_credential_host_secret(CredentialSecretFlags flags
, struct iovec
*ret
) {
1366 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "Support for encrypted credentials not available.");
1369 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 struct iovec
*input
, struct iovec
*ret
) {
1370 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "Support for encrypted credentials not available.");
1373 int decrypt_credential_and_warn(const char *validate_name
, usec_t validate_timestamp
, const char *tpm2_device
, const char *tpm2_signature_path
, const struct iovec
*input
, struct iovec
*ret
) {
1374 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "Support for encrypted credentials not available.");