]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/creds-util.c
Merge pull request #20483 from medhefgo/boot
[thirdparty/systemd.git] / src / shared / creds-util.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <sys/file.h>
4
5 #if HAVE_OPENSSL
6 #include <openssl/err.h>
7 #endif
8
9 #include "sd-id128.h"
10
11 #include "blockdev-util.h"
12 #include "chattr-util.h"
13 #include "creds-util.h"
14 #include "env-util.h"
15 #include "fd-util.h"
16 #include "fileio.h"
17 #include "fs-util.h"
18 #include "io-util.h"
19 #include "memory-util.h"
20 #include "mkdir.h"
21 #include "openssl-util.h"
22 #include "path-util.h"
23 #include "random-util.h"
24 #include "sparse-endian.h"
25 #include "stat-util.h"
26 #include "tpm2-util.h"
27 #include "virt.h"
28
29 bool credential_name_valid(const char *s) {
30 /* We want that credential names are both valid in filenames (since that's our primary way to pass
31 * them around) and as fdnames (which is how we might want to pass them around eventually) */
32 return filename_is_valid(s) && fdname_is_valid(s);
33 }
34
35 int get_credentials_dir(const char **ret) {
36 const char *e;
37
38 assert(ret);
39
40 e = secure_getenv("CREDENTIALS_DIRECTORY");
41 if (!e)
42 return -ENXIO;
43
44 if (!path_is_absolute(e) || !path_is_normalized(e))
45 return -EINVAL;
46
47 *ret = e;
48 return 0;
49 }
50
51 int read_credential(const char *name, void **ret, size_t *ret_size) {
52 _cleanup_free_ char *fn = NULL;
53 const char *d;
54 int r;
55
56 assert(ret);
57
58 if (!credential_name_valid(name))
59 return -EINVAL;
60
61 r = get_credentials_dir(&d);
62 if (r < 0)
63 return r;
64
65 fn = path_join(d, name);
66 if (!fn)
67 return -ENOMEM;
68
69 return read_full_file_full(
70 AT_FDCWD, fn,
71 UINT64_MAX, SIZE_MAX,
72 READ_FULL_FILE_SECURE,
73 NULL,
74 (char**) ret, ret_size);
75 }
76
77 #if HAVE_OPENSSL
78
79 #define CREDENTIAL_HOST_SECRET_SIZE 4096
80
81 static const sd_id128_t credential_app_id =
82 SD_ID128_MAKE(d3,ac,ec,ba,0d,ad,4c,df,b8,c9,38,15,28,93,6c,58);
83
84 struct credential_host_secret_format {
85 /* The hashed machine ID of the machine this belongs to. Why? We want to ensure that each machine
86 * gets its own secret, even if people forget to flush out this secret file. Hence we bind it to the
87 * machine ID, for which there's hopefully a better chance it will be flushed out. We use a hashed
88 * machine ID instead of the literal one, because it's trivial to, and it might be a good idea not
89 * being able to directly associate a secret key file with a host. */
90 sd_id128_t machine_id;
91
92 /* The actual secret key */
93 uint8_t data[CREDENTIAL_HOST_SECRET_SIZE];
94 } _packed_;
95
96 static int make_credential_host_secret(
97 int dfd,
98 const sd_id128_t machine_id,
99 const char *fn,
100 void **ret_data,
101 size_t *ret_size) {
102
103 struct credential_host_secret_format buf;
104 _cleanup_free_ char *t = NULL;
105 _cleanup_close_ int fd = -1;
106 int r;
107
108 assert(dfd >= 0);
109 assert(fn);
110
111 fd = openat(dfd, ".", O_CLOEXEC|O_WRONLY|O_TMPFILE, 0400);
112 if (fd < 0) {
113 log_debug_errno(errno, "Failed to create temporary credential file with O_TMPFILE, proceeding without: %m");
114
115 if (asprintf(&t, "credential.secret.%016" PRIx64, random_u64()) < 0)
116 return -ENOMEM;
117
118 fd = openat(dfd, t, O_CLOEXEC|O_WRONLY|O_CREAT|O_EXCL|O_NOFOLLOW, 0400);
119 if (fd < 0)
120 return -errno;
121 }
122
123 r = chattr_secret(fd, 0);
124 if (r < 0)
125 log_debug_errno(r, "Failed to set file attributes for secrets file, ignoring: %m");
126
127 buf = (struct credential_host_secret_format) {
128 .machine_id = machine_id,
129 };
130
131 r = genuine_random_bytes(buf.data, sizeof(buf.data), RANDOM_BLOCK);
132 if (r < 0)
133 goto finish;
134
135 r = loop_write(fd, &buf, sizeof(buf), false);
136 if (r < 0)
137 goto finish;
138
139 if (fsync(fd) < 0) {
140 r = -errno;
141 goto finish;
142 }
143
144 if (t) {
145 r = rename_noreplace(dfd, t, dfd, fn);
146 if (r < 0)
147 goto finish;
148
149 t = mfree(t);
150 } else if (linkat(fd, "", dfd, fn, AT_EMPTY_PATH) < 0) {
151 r = -errno;
152 goto finish;
153 }
154
155 if (fsync(dfd) < 0) {
156 r = -errno;
157 goto finish;
158 }
159
160 if (ret_data) {
161 void *copy;
162
163 copy = memdup(buf.data, sizeof(buf.data));
164 if (!copy) {
165 r = -ENOMEM;
166 goto finish;
167 }
168
169 *ret_data = copy;
170 }
171
172 if (ret_size)
173 *ret_size = sizeof(buf.data);
174
175 r = 0;
176
177 finish:
178 if (t && unlinkat(dfd, t, 0) < 0)
179 log_debug_errno(errno, "Failed to remove temporary credential key: %m");
180
181 explicit_bzero_safe(&buf, sizeof(buf));
182 return r;
183 }
184
185 int get_credential_host_secret(CredentialSecretFlags flags, void **ret, size_t *ret_size) {
186 _cleanup_free_ char *efn = NULL, *ep = NULL;
187 _cleanup_close_ int dfd = -1;
188 sd_id128_t machine_id;
189 const char *e, *fn, *p;
190 int r;
191
192 r = sd_id128_get_machine_app_specific(credential_app_id, &machine_id);
193 if (r < 0)
194 return r;
195
196 e = secure_getenv("SYSTEMD_CREDENTIAL_SECRET");
197 if (e) {
198 if (!path_is_normalized(e))
199 return -EINVAL;
200 if (!path_is_absolute(e))
201 return -EINVAL;
202
203 r = path_extract_directory(e, &ep);
204 if (r < 0)
205 return r;
206
207 r = path_extract_filename(e, &efn);
208 if (r < 0)
209 return r;
210
211 p = ep;
212 fn = efn;
213 } else {
214 p = "/var/lib/systemd";
215 fn = "credential.secret";
216 }
217
218 (void) mkdir_p(p, 0755);
219 dfd = open(p, O_CLOEXEC|O_DIRECTORY|O_RDONLY);
220 if (dfd < 0)
221 return -errno;
222
223 if (FLAGS_SET(flags, CREDENTIAL_SECRET_FAIL_ON_TEMPORARY_FS)) {
224 r = fd_is_temporary_fs(dfd);
225 if (r < 0)
226 return r;
227 if (r > 0)
228 return -ENOMEDIUM;
229 }
230
231 for (unsigned attempt = 0;; attempt++) {
232 _cleanup_(erase_and_freep) struct credential_host_secret_format *f = NULL;
233 _cleanup_close_ int fd = -1;
234 size_t l = 0;
235 ssize_t n = 0;
236 struct stat st;
237
238 if (attempt >= 3) /* Somebody is playing games with us */
239 return -EIO;
240
241 fd = openat(dfd, fn, O_CLOEXEC|O_RDONLY|O_NOCTTY|O_NOFOLLOW);
242 if (fd < 0) {
243 if (errno != ENOENT || !FLAGS_SET(flags, CREDENTIAL_SECRET_GENERATE))
244 return -errno;
245
246 r = make_credential_host_secret(dfd, machine_id, fn, ret, ret_size);
247 if (r == -EEXIST) {
248 log_debug_errno(r, "Credential secret was created while we were creating it. Trying to read new secret.");
249 continue;
250 }
251 if (r < 0)
252 return r;
253
254 return 0;
255 }
256
257 if (fstat(fd, &st) < 0)
258 return -errno;
259
260 r = stat_verify_regular(&st);
261 if (r < 0)
262 return r;
263 if (st.st_nlink == 0) /* Deleted by now, try again */
264 continue;
265 if (st.st_nlink > 1)
266 return -EPERM; /* Our deletion check won't work if hardlinked somewhere else */
267 if ((st.st_mode & 07777) != 0400) /* Don't use file if not 0400 access mode */
268 return -EPERM;
269 if (st.st_size > 16*1024*1024)
270 return -E2BIG;
271 l = st.st_size;
272 if (l < offsetof(struct credential_host_secret_format, data) + 1)
273 return -EINVAL;
274
275 f = malloc(l+1);
276 if (!f)
277 return -ENOMEM;
278
279 n = read(fd, f, l+1);
280 if (n < 0)
281 return -errno;
282 if ((size_t) n != l) /* What? The size changed? */
283 return -EIO;
284
285 if (sd_id128_equal(machine_id, f->machine_id)) {
286 size_t sz;
287
288 if (FLAGS_SET(flags, CREDENTIAL_SECRET_WARN_NOT_ENCRYPTED)) {
289 r = fd_is_encrypted(fd);
290 if (r < 0)
291 log_debug_errno(r, "Failed to determine if credential secret file '%s/%s' is encrypted.", p, fn);
292 else if (r == 0)
293 log_warning("Credential secret file '%s/%s' is not located on encrypted media, using anyway.", p, fn);
294 }
295
296 sz = l - offsetof(struct credential_host_secret_format, data);
297 assert(sz > 0);
298
299 if (ret) {
300 void *copy;
301
302 assert(sz <= sizeof(f->data)); /* Ensure we don't read past f->data bounds */
303
304 copy = memdup(f->data, sz);
305 if (!copy)
306 return -ENOMEM;
307
308 *ret = copy;
309 }
310
311 if (ret_size)
312 *ret_size = sz;
313
314 return 0;
315 }
316
317 /* Hmm, this secret is from somewhere else. Let's delete the file. Let's first acquire a lock
318 * to ensure we are the only ones accessing the file while we delete it. */
319
320 if (flock(fd, LOCK_EX) < 0)
321 return -errno;
322
323 /* Before we delete it check that the file is still linked into the file system */
324 if (fstat(fd, &st) < 0)
325 return -errno;
326 if (st.st_nlink == 0) /* Already deleted by now? */
327 continue;
328 if (st.st_nlink != 1) /* Safety check, someone is playing games with us */
329 return -EPERM;
330
331 if (unlinkat(dfd, fn, 0) < 0)
332 return -errno;
333
334 /* And now try again */
335 }
336 }
337
338 /* Construction is like this:
339 *
340 * A symmetric encryption key is derived from:
341 *
342 * 1. Either the "host" key (a key stored in /var/lib/credential.secret)
343 *
344 * 2. A key generated by letting the TPM2 calculate an HMAC hash of some nonce we pass to it, keyed
345 * by a key derived from its internal seed key.
346 *
347 * 3. The concatenation of the above.
348 *
349 * The above is hashed with SHA256 which is then used as encryption key for AES256-GCM. The encrypted
350 * credential is a short (unencrypted) header describing which of the three keys to use, the IV to use for
351 * AES256-GCM and some more meta information (sizes of certain objects) that is strictly speaking redundant,
352 * but kinda nice to have since we can have a more generic parser. If the TPM2 key is used this is followed
353 * by another (unencrypted) header, with information about the TPM2 policy used (specifically: the PCR mask
354 * to bind against, and a hash of the resulting policy — the latter being redundant, but speeding up things a
355 * bit, since we can more quickly refuse PCR state), followed by a sealed/exported TPM2 HMAC key. This is
356 * then followed by the encrypted data, which begins with a metadata header (which contains validity
357 * timestamps as well as the credential name), followed by the actual credential payload. The file ends in
358 * the AES256-GCM tag. To make things simple, the AES256-GCM AAD covers the main and the TPM2 header in
359 * full. This means the whole file is either protected by AAD, or is ciphertext, or is the tag. No
360 * unprotected data is included.
361 */
362
363 struct _packed_ encrypted_credential_header {
364 sd_id128_t id;
365 le32_t key_size;
366 le32_t block_size;
367 le32_t iv_size;
368 le32_t tag_size;
369 uint8_t iv[];
370 /* Followed by NUL bytes until next 8 byte boundary */
371 };
372
373 struct _packed_ tpm2_credential_header {
374 le64_t pcr_mask; /* Note that the spec for PC Clients only mandates 24 PCRs, and that's what systems
375 * generally have. But keep the door open for more. */
376 le16_t pcr_bank; /* For now, either TPM2_ALG_SHA256 or TPM2_ALG_SHA1 */
377 le16_t primary_alg; /* Primary key algorithm (either TPM2_ALG_RSA or TPM2_ALG_ECC for now) */
378 le32_t blob_size;
379 le32_t policy_hash_size;
380 uint8_t policy_hash_and_blob[];
381 /* Followed by NUL bytes until next 8 byte boundary */
382 };
383
384 struct _packed_ metadata_credential_header {
385 le64_t timestamp;
386 le64_t not_after;
387 le32_t name_size;
388 char name[];
389 /* Followed by NUL bytes until next 8 byte boundary */
390 };
391
392 /* Some generic limit for parts of the encrypted credential for which we don't know the right size ahead of
393 * time, but where we are really sure it won't be larger than this. Should be larger than any possible IV,
394 * padding, tag size and so on. This is purely used for early filtering out of invalid sizes. */
395 #define CREDENTIAL_FIELD_SIZE_MAX (16U*1024U)
396
397 static int sha256_hash_host_and_tpm2_key(
398 const void *host_key,
399 size_t host_key_size,
400 const void *tpm2_key,
401 size_t tpm2_key_size,
402 uint8_t ret[static SHA256_DIGEST_LENGTH]) {
403
404 SHA256_CTX sha256_context;
405
406 assert(host_key_size == 0 || host_key);
407 assert(tpm2_key_size == 0 || tpm2_key);
408 assert(ret);
409
410 /* Combines the host key and the TPM2 HMAC hash into a SHA256 hash value we'll use as symmetric encryption key. */
411
412 if (SHA256_Init(&sha256_context) != 1)
413 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initial SHA256 context.");
414
415 if (host_key && SHA256_Update(&sha256_context, host_key, host_key_size) != 1)
416 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to hash host key.");
417
418 if (tpm2_key && SHA256_Update(&sha256_context, tpm2_key, tpm2_key_size) != 1)
419 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to hash TPM2 key.");
420
421 if (SHA256_Final(ret, &sha256_context) != 1)
422 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to finalize SHA256 hash.");
423
424 return 0;
425 }
426
427 int encrypt_credential_and_warn(
428 sd_id128_t with_key,
429 const char *name,
430 usec_t timestamp,
431 usec_t not_after,
432 const char *tpm2_device,
433 uint32_t tpm2_pcr_mask,
434 const void *input,
435 size_t input_size,
436 void **ret,
437 size_t *ret_size) {
438
439 _cleanup_(EVP_CIPHER_CTX_freep) EVP_CIPHER_CTX *context = NULL;
440 _cleanup_(erase_and_freep) void *host_key = NULL, *tpm2_key = NULL;
441 size_t host_key_size = 0, tpm2_key_size = 0, tpm2_blob_size = 0, tpm2_policy_hash_size = 0, output_size, p, ml;
442 _cleanup_free_ void *tpm2_blob = NULL, *tpm2_policy_hash = NULL, *iv = NULL, *output = NULL;
443 _cleanup_free_ struct metadata_credential_header *m = NULL;
444 uint16_t tpm2_pcr_bank = 0, tpm2_primary_alg = 0;
445 struct encrypted_credential_header *h;
446 int ksz, bsz, ivsz, tsz, added, r;
447 uint8_t md[SHA256_DIGEST_LENGTH];
448 const EVP_CIPHER *cc;
449 #if HAVE_TPM2
450 bool try_tpm2 = false;
451 #endif
452 sd_id128_t id;
453
454 assert(input || input_size == 0);
455 assert(ret);
456 assert(ret_size);
457
458 if (name && !credential_name_valid(name))
459 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid credential name: %s", name);
460
461 if (not_after != USEC_INFINITY && timestamp != USEC_INFINITY && not_after < timestamp)
462 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Credential is invalidated before it is valid (" USEC_FMT " < " USEC_FMT ").", not_after, timestamp);
463
464 if (DEBUG_LOGGING) {
465 char buf[FORMAT_TIMESTAMP_MAX];
466
467 if (name)
468 log_debug("Including credential name '%s' in encrypted credential.", name);
469 if (timestamp != USEC_INFINITY)
470 log_debug("Including timestamp '%s' in encrypted credential.", format_timestamp(buf, sizeof(buf), timestamp));
471 if (not_after != USEC_INFINITY)
472 log_debug("Including not-after timestamp '%s' in encrypted credential.", format_timestamp(buf, sizeof(buf), not_after));
473 }
474
475 if (sd_id128_is_null(with_key) ||
476 sd_id128_in_set(with_key, CRED_AES256_GCM_BY_HOST, CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC)) {
477
478 r = get_credential_host_secret(
479 CREDENTIAL_SECRET_GENERATE|
480 CREDENTIAL_SECRET_WARN_NOT_ENCRYPTED|
481 (sd_id128_is_null(with_key) ? CREDENTIAL_SECRET_FAIL_ON_TEMPORARY_FS : 0),
482 &host_key,
483 &host_key_size);
484 if (r == -ENOMEDIUM && sd_id128_is_null(with_key))
485 log_debug_errno(r, "Credential host secret location on temporary file system, not using.");
486 else if (r < 0)
487 return log_error_errno(r, "Failed to determine local credential host secret: %m");
488 }
489
490 #if HAVE_TPM2
491 if (sd_id128_is_null(with_key)) {
492 /* If automatic mode is selected and we are running in a container, let's not try TPM2. OTOH
493 * if user picks TPM2 explicitly, let's always honour the request and try. */
494
495 r = detect_container();
496 if (r < 0)
497 log_debug_errno(r, "Failed to determine whether we are running in a container, ignoring: %m");
498 else if (r > 0)
499 log_debug("Running in container, not attempting to use TPM2.");
500
501 try_tpm2 = r <= 0;
502 }
503
504 if (try_tpm2 ||
505 sd_id128_in_set(with_key, CRED_AES256_GCM_BY_TPM2_HMAC, CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC)) {
506
507 r = tpm2_seal(tpm2_device,
508 tpm2_pcr_mask,
509 &tpm2_key,
510 &tpm2_key_size,
511 &tpm2_blob,
512 &tpm2_blob_size,
513 &tpm2_policy_hash,
514 &tpm2_policy_hash_size,
515 &tpm2_pcr_bank,
516 &tpm2_primary_alg);
517 if (r < 0) {
518 if (!sd_id128_is_null(with_key))
519 return r;
520
521 log_debug_errno(r, "TPM2 sealing didn't work, not using: %m");
522 }
523
524 assert(tpm2_blob_size <= CREDENTIAL_FIELD_SIZE_MAX);
525 assert(tpm2_policy_hash_size <= CREDENTIAL_FIELD_SIZE_MAX);
526 }
527 #endif
528
529 if (sd_id128_is_null(with_key)) {
530 /* Let's settle the key type in auto mode now. */
531
532 if (host_key && tpm2_key)
533 id = CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC;
534 else if (tpm2_key)
535 id = CRED_AES256_GCM_BY_TPM2_HMAC;
536 else if (host_key)
537 id = CRED_AES256_GCM_BY_HOST;
538 else
539 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
540 "TPM2 not available and host key located on temporary file system, no encryption key available.");
541 } else
542 id = with_key;
543
544 /* Let's now take the host key and the TPM2 key and hash it together, to use as encryption key for the data */
545 r = sha256_hash_host_and_tpm2_key(host_key, host_key_size, tpm2_key, tpm2_key_size, md);
546 if (r < 0)
547 return r;
548
549 assert_se(cc = EVP_aes_256_gcm());
550
551 ksz = EVP_CIPHER_key_length(cc);
552 assert(ksz == sizeof(md));
553
554 bsz = EVP_CIPHER_block_size(cc);
555 assert(bsz > 0);
556 assert((size_t) bsz <= CREDENTIAL_FIELD_SIZE_MAX);
557
558 ivsz = EVP_CIPHER_iv_length(cc);
559 if (ivsz > 0) {
560 assert((size_t) ivsz <= CREDENTIAL_FIELD_SIZE_MAX);
561
562 iv = malloc(ivsz);
563 if (!iv)
564 return log_oom();
565
566 r = genuine_random_bytes(iv, ivsz, RANDOM_BLOCK);
567 if (r < 0)
568 return log_error_errno(r, "Failed to acquired randomized IV: %m");
569 }
570
571 tsz = 16; /* FIXME: On OpenSSL 3 there is EVP_CIPHER_CTX_get_tag_length(), until then let's hardcode this */
572
573 context = EVP_CIPHER_CTX_new();
574 if (!context)
575 return log_error_errno(SYNTHETIC_ERRNO(ENOMEM), "Failed to allocate encryption object: %s",
576 ERR_error_string(ERR_get_error(), NULL));
577
578 if (EVP_EncryptInit_ex(context, cc, NULL, md, iv) != 1)
579 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initialize encryption context: %s",
580 ERR_error_string(ERR_get_error(), NULL));
581
582 /* Just an upper estimate */
583 output_size =
584 ALIGN8(offsetof(struct encrypted_credential_header, iv) + ivsz) +
585 ALIGN8(tpm2_key ? offsetof(struct tpm2_credential_header, policy_hash_and_blob) + tpm2_blob_size + tpm2_policy_hash_size : 0) +
586 ALIGN8(offsetof(struct metadata_credential_header, name) + strlen_ptr(name)) +
587 input_size + 2U * (size_t) bsz +
588 tsz;
589
590 output = malloc0(output_size);
591 if (!output)
592 return log_oom();
593
594 h = (struct encrypted_credential_header*) output;
595 h->id = id;
596 h->block_size = htole32(bsz);
597 h->key_size = htole32(ksz);
598 h->tag_size = htole32(tsz);
599 h->iv_size = htole32(ivsz);
600 memcpy(h->iv, iv, ivsz);
601
602 p = ALIGN8(offsetof(struct encrypted_credential_header, iv) + ivsz);
603
604 if (tpm2_key) {
605 struct tpm2_credential_header *t;
606
607 t = (struct tpm2_credential_header*) ((uint8_t*) output + p);
608 t->pcr_mask = htole64(tpm2_pcr_mask);
609 t->pcr_bank = htole16(tpm2_pcr_bank);
610 t->primary_alg = htole16(tpm2_primary_alg);
611 t->blob_size = htole32(tpm2_blob_size);
612 t->policy_hash_size = htole32(tpm2_policy_hash_size);
613 memcpy(t->policy_hash_and_blob, tpm2_blob, tpm2_blob_size);
614 memcpy(t->policy_hash_and_blob + tpm2_blob_size, tpm2_policy_hash, tpm2_policy_hash_size);
615
616 p += ALIGN8(offsetof(struct tpm2_credential_header, policy_hash_and_blob) + tpm2_blob_size + tpm2_policy_hash_size);
617 }
618
619 /* Pass the encrypted + TPM2 header as AAD */
620 if (EVP_EncryptUpdate(context, NULL, &added, output, p) != 1)
621 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to write AAD data: %s",
622 ERR_error_string(ERR_get_error(), NULL));
623
624 /* Now construct the metadata header */
625 ml = strlen_ptr(name);
626 m = malloc0(ALIGN8(offsetof(struct metadata_credential_header, name) + ml));
627 if (!m)
628 return log_oom();
629
630 m->timestamp = htole64(timestamp);
631 m->not_after = htole64(not_after);
632 m->name_size = htole32(ml);
633 memcpy_safe(m->name, name, ml);
634
635 /* And encrypt the metadata header */
636 if (EVP_EncryptUpdate(context, (uint8_t*) output + p, &added, (const unsigned char*) m, ALIGN8(offsetof(struct metadata_credential_header, name) + ml)) != 1)
637 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to encrypt metadata header: %s",
638 ERR_error_string(ERR_get_error(), NULL));
639
640 assert(added >= 0);
641 assert((size_t) added <= output_size - p);
642 p += added;
643
644 /* Then encrypt the plaintext */
645 if (EVP_EncryptUpdate(context, (uint8_t*) output + p, &added, input, input_size) != 1)
646 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to encrypt data: %s",
647 ERR_error_string(ERR_get_error(), NULL));
648
649 assert(added >= 0);
650 assert((size_t) added <= output_size - p);
651 p += added;
652
653 /* Finalize */
654 if (EVP_EncryptFinal_ex(context, (uint8_t*) output + p, &added) != 1)
655 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to finalize data encryption: %s",
656 ERR_error_string(ERR_get_error(), NULL));
657
658 assert(added >= 0);
659 assert((size_t) added <= output_size - p);
660 p += added;
661
662 assert(p <= output_size - tsz);
663
664 /* Append tag */
665 if (EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_GCM_GET_TAG, tsz, (uint8_t*) output + p) != 1)
666 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to get tag: %s",
667 ERR_error_string(ERR_get_error(), NULL));
668
669 p += tsz;
670 assert(p <= output_size);
671
672 if (DEBUG_LOGGING && input_size > 0) {
673 size_t base64_size;
674
675 base64_size = DIV_ROUND_UP(p * 4, 3); /* Include base64 size increase in debug output */
676 assert(base64_size >= input_size);
677 log_debug("Input of %zu bytes grew to output of %zu bytes (+%2zu%%).", input_size, base64_size, base64_size * 100 / input_size - 100);
678 }
679
680 *ret = TAKE_PTR(output);
681 *ret_size = p;
682
683 return 0;
684 }
685
686 int decrypt_credential_and_warn(
687 const char *validate_name,
688 usec_t validate_timestamp,
689 const char *tpm2_device,
690 const void *input,
691 size_t input_size,
692 void **ret,
693 size_t *ret_size) {
694
695 _cleanup_(erase_and_freep) void *host_key = NULL, *tpm2_key = NULL, *plaintext = NULL;
696 _cleanup_(EVP_CIPHER_CTX_freep) EVP_CIPHER_CTX *context = NULL;
697 size_t host_key_size = 0, tpm2_key_size = 0, plaintext_size, p, hs;
698 struct encrypted_credential_header *h;
699 struct metadata_credential_header *m;
700 uint8_t md[SHA256_DIGEST_LENGTH];
701 bool with_tpm2, with_host_key;
702 const EVP_CIPHER *cc;
703 int r, added;
704
705 assert(input || input_size == 0);
706 assert(ret);
707 assert(ret_size);
708
709 h = (struct encrypted_credential_header*) input;
710
711 /* The ID must fit in, for the current and all future formats */
712 if (input_size < sizeof(h->id))
713 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
714
715 with_host_key = sd_id128_in_set(h->id, CRED_AES256_GCM_BY_HOST, CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC);
716 with_tpm2 = sd_id128_in_set(h->id, CRED_AES256_GCM_BY_TPM2_HMAC, CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC);
717
718 if (!with_host_key && !with_tpm2)
719 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Unknown encryption format, or corrupted data: %m");
720
721 /* Now we know the minimum header size */
722 if (input_size < offsetof(struct encrypted_credential_header, iv))
723 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
724
725 /* Verify some basic header values */
726 if (le32toh(h->key_size) != sizeof(md))
727 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected key size in header.");
728 if (le32toh(h->block_size) <= 0 || le32toh(h->block_size) > CREDENTIAL_FIELD_SIZE_MAX)
729 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected block size in header.");
730 if (le32toh(h->iv_size) > CREDENTIAL_FIELD_SIZE_MAX)
731 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "IV size too large.");
732 if (le32toh(h->tag_size) != 16) /* FIXME: On OpenSSL 3, let's verify via EVP_CIPHER_CTX_get_tag_length() */
733 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected tag size in header.");
734
735 /* Ensure we have space for the full header now (we don't know the size of the name hence this is a
736 * lower limit only) */
737 if (input_size <
738 ALIGN8(offsetof(struct encrypted_credential_header, iv) + le32toh(h->iv_size)) +
739 ALIGN8((with_tpm2 ? offsetof(struct tpm2_credential_header, policy_hash_and_blob) : 0)) +
740 ALIGN8(offsetof(struct metadata_credential_header, name)) +
741 le32toh(h->tag_size))
742 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
743
744 p = ALIGN8(offsetof(struct encrypted_credential_header, iv) + le32toh(h->iv_size));
745
746 if (with_tpm2) {
747 #if HAVE_TPM2
748 struct tpm2_credential_header* t = (struct tpm2_credential_header*) ((uint8_t*) input + p);
749
750 if (le64toh(t->pcr_mask) >= (UINT64_C(1) << TPM2_PCRS_MAX))
751 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "TPM2 PCR mask out of range.");
752 if (!tpm2_pcr_bank_to_string(le16toh(t->pcr_bank)))
753 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "TPM2 PCR bank invalid or not supported");
754 if (!tpm2_primary_alg_to_string(le16toh(t->primary_alg)))
755 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "TPM2 primary key algorithm invalid or not supported.");
756 if (le32toh(t->blob_size) > CREDENTIAL_FIELD_SIZE_MAX)
757 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected TPM2 blob size.");
758 if (le32toh(t->policy_hash_size) > CREDENTIAL_FIELD_SIZE_MAX)
759 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected TPM2 policy hash size.");
760
761 /* Ensure we have space for the full TPM2 header now (still don't know the name, and its size
762 * though, hence still just a lower limit test only) */
763 if (input_size <
764 ALIGN8(offsetof(struct encrypted_credential_header, iv) + le32toh(h->iv_size)) +
765 ALIGN8(offsetof(struct tpm2_credential_header, policy_hash_and_blob) + le32toh(t->blob_size) + le32toh(t->policy_hash_size)) +
766 ALIGN8(offsetof(struct metadata_credential_header, name)) +
767 le32toh(h->tag_size))
768 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
769
770 r = tpm2_unseal(tpm2_device,
771 le64toh(t->pcr_mask),
772 le16toh(t->pcr_bank),
773 le16toh(t->primary_alg),
774 t->policy_hash_and_blob,
775 le32toh(t->blob_size),
776 t->policy_hash_and_blob + le32toh(t->blob_size),
777 le32toh(t->policy_hash_size),
778 &tpm2_key,
779 &tpm2_key_size);
780 if (r < 0)
781 return r;
782
783 p += ALIGN8(offsetof(struct tpm2_credential_header, policy_hash_and_blob) +
784 le32toh(t->blob_size) +
785 le32toh(t->policy_hash_size));
786 #else
787 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Credential requires TPM2 support, but TPM2 support not available.");
788 #endif
789 }
790
791 if (with_host_key) {
792 r = get_credential_host_secret(
793 0,
794 &host_key,
795 &host_key_size);
796 if (r < 0)
797 return log_error_errno(r, "Failed to determine local credential key: %m");
798 }
799
800 sha256_hash_host_and_tpm2_key(host_key, host_key_size, tpm2_key, tpm2_key_size, md);
801
802 assert_se(cc = EVP_aes_256_gcm());
803
804 /* Make sure cipher expectations match the header */
805 if (EVP_CIPHER_key_length(cc) != (int) le32toh(h->key_size))
806 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected key size in header.");
807 if (EVP_CIPHER_block_size(cc) != (int) le32toh(h->block_size))
808 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected block size in header.");
809
810 context = EVP_CIPHER_CTX_new();
811 if (!context)
812 return log_error_errno(SYNTHETIC_ERRNO(ENOMEM), "Failed to allocate decryption object: %s",
813 ERR_error_string(ERR_get_error(), NULL));
814
815 if (EVP_DecryptInit_ex(context, cc, NULL, NULL, NULL) != 1)
816 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initialize decryption context: %s",
817 ERR_error_string(ERR_get_error(), NULL));
818
819 if (EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_GCM_SET_IVLEN, le32toh(h->iv_size), NULL) != 1)
820 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to set IV size on decryption context: %s",
821 ERR_error_string(ERR_get_error(), NULL));
822
823 if (EVP_DecryptInit_ex(context, NULL, NULL, md, h->iv) != 1)
824 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to set IV and key: %s",
825 ERR_error_string(ERR_get_error(), NULL));
826
827 if (EVP_DecryptUpdate(context, NULL, &added, input, p) != 1)
828 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to write AAD data: %s",
829 ERR_error_string(ERR_get_error(), NULL));
830
831 plaintext = malloc(input_size - p - le32toh(h->tag_size));
832 if (!plaintext)
833 return -ENOMEM;
834
835 if (EVP_DecryptUpdate(
836 context,
837 plaintext,
838 &added,
839 (uint8_t*) input + p,
840 input_size - p - le32toh(h->tag_size)) != 1)
841 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to decrypt data: %s",
842 ERR_error_string(ERR_get_error(), NULL));
843
844 assert(added >= 0);
845 assert((size_t) added <= input_size - p - le32toh(h->tag_size));
846 plaintext_size = added;
847
848 if (EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_GCM_SET_TAG, le32toh(h->tag_size), (uint8_t*) input + input_size - le32toh(h->tag_size)) != 1)
849 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to set tag: %s",
850 ERR_error_string(ERR_get_error(), NULL));
851
852 if (EVP_DecryptFinal_ex(context, (uint8_t*) plaintext + plaintext_size, &added) != 1)
853 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Decryption failed (incorrect key?): %s",
854 ERR_error_string(ERR_get_error(), NULL));
855
856 plaintext_size += added;
857
858 if (plaintext_size < ALIGN8(offsetof(struct metadata_credential_header, name)))
859 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Metadata header incomplete.");
860
861 m = plaintext;
862
863 if (le64toh(m->timestamp) != USEC_INFINITY &&
864 le64toh(m->not_after) != USEC_INFINITY &&
865 le64toh(m->timestamp) >= le64toh(m->not_after))
866 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Timestamps of credential are not in order, refusing.");
867
868 if (le32toh(m->name_size) > CREDENTIAL_NAME_MAX)
869 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Embedded credential name too long, refusing.");
870
871 hs = ALIGN8(offsetof(struct metadata_credential_header, name) + le32toh(m->name_size));
872 if (plaintext_size < hs)
873 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Metadata header incomplete.");
874
875 if (le32toh(m->name_size) > 0) {
876 _cleanup_free_ char *embedded_name = NULL;
877
878 if (memchr(m->name, 0, le32toh(m->name_size)))
879 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Embedded credential name contains NUL byte, refusing.");
880
881 embedded_name = memdup_suffix0(m->name, le32toh(m->name_size));
882 if (!embedded_name)
883 return log_oom();
884
885 if (!credential_name_valid(embedded_name))
886 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Embedded credential name is not valid, refusing.");
887
888 if (validate_name && !streq(embedded_name, validate_name)) {
889
890 r = getenv_bool_secure("SYSTEMD_CREDENTIAL_VALIDATE_NAME");
891 if (r < 0 && r != -ENXIO)
892 log_debug_errno(r, "Failed to parse $SYSTEMD_CREDENTIAL_VALIDATE_NAME: %m");
893 if (r != 0)
894 return log_error_errno(SYNTHETIC_ERRNO(EREMOTE), "Embedded credential name '%s' does not match filename '%s', refusing.", embedded_name, validate_name);
895
896 log_debug("Embedded credential name '%s' does not match expected name '%s', but configured to use credential anyway.", embedded_name, validate_name);
897 }
898 }
899
900 if (validate_timestamp != USEC_INFINITY) {
901 if (le64toh(m->timestamp) != USEC_INFINITY && le64toh(m->timestamp) > validate_timestamp)
902 log_debug("Credential timestamp is from the future, assuming clock skew.");
903
904 if (le64toh(m->not_after) != USEC_INFINITY && le64toh(m->not_after) < validate_timestamp) {
905
906 r = getenv_bool_secure("SYSTEMD_CREDENTIAL_VALIDATE_NOT_AFTER");
907 if (r < 0 && r != -ENXIO)
908 log_debug_errno(r, "Failed to parse $SYSTEMD_CREDENTIAL_VALIDATE_NOT_AFTER: %m");
909 if (r != 0)
910 return log_error_errno(SYNTHETIC_ERRNO(ESTALE), "Credential's time passed, refusing to use.");
911
912 log_debug("Credential not-after timestamp has passed, but configured to use credential anyway.");
913 }
914 }
915
916 if (ret) {
917 char *without_metadata;
918
919 without_metadata = memdup((uint8_t*) plaintext + hs, plaintext_size - hs);
920 if (!without_metadata)
921 return log_oom();
922
923 *ret = without_metadata;
924 }
925
926 if (ret_size)
927 *ret_size = plaintext_size - hs;
928
929 return 0;
930 }
931
932 #else
933
934 int get_credential_host_secret(CredentialSecretFlags flags, void **ret, size_t *ret_size) {
935 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Support for encrypted credentials not available.");
936 }
937
938 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_pcr_mask, const void *input, size_t input_size, void **ret, size_t *ret_size) {
939 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Support for encrypted credentials not available.");
940 }
941
942 int decrypt_credential_and_warn(const char *validate_name, usec_t validate_timestamp, const char *tpm2_device, const void *input, size_t input_size, void **ret, size_t *ret_size) {
943 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Support for encrypted credentials not available.");
944 }
945
946 #endif