Debian Codegraph @

src/creds/creds.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <linux/magic.h>
4 #include <unistd.h>
5
6 #include "sd-json.h"
7 #include "sd-varlink.h"
8
9 #include "alloc-util.h"
10 #include "build.h"
11 #include "bus-polkit.h"
12 #include "bus-util.h"
13 #include "creds-util.h"
14 #include "dirent-util.h"
15 #include "errno-util.h"
16 #include "escape.h"
17 #include "fileio.h"
18 #include "format-table.h"
19 #include "hashmap.h"
20 #include "hexdecoct.h"
21 #include "json-util.h"
22 #include "libmount-util.h"
23 #include "log.h"
24 #include "main-func.h"
25 #include "memory-util.h"
26 #include "options.h"
27 #include "pager.h"
28 #include "parse-argument.h"
29 #include "parse-util.h"
30 #include "polkit-agent.h"
31 #include "pretty-print.h"
32 #include "stat-util.h"
33 #include "string-table.h"
34 #include "string-util.h"
35 #include "strv.h"
36 #include "terminal-util.h"
37 #include "time-util.h"
38 #include "tpm2-pcr.h"
39 #include "tpm2-util.h"
40 #include "user-util.h"
41 #include "varlink-io.systemd.Credentials.h"
42 #include "varlink-util.h"
43 #include "verbs.h"
44
45 typedef enum TranscodeMode {
46 TRANSCODE_OFF,
47 TRANSCODE_BASE64,
48 TRANSCODE_UNBASE64,
49 TRANSCODE_HEX,
50 TRANSCODE_UNHEX,
51 _TRANSCODE_MAX,
52 _TRANSCODE_INVALID = -EINVAL,
53 } TranscodeMode;
54
55 static sd_json_format_flags_t arg_json_format_flags = SD_JSON_FORMAT_OFF;
56 static PagerFlags arg_pager_flags = 0;
57 static bool arg_legend = true;
58 static bool arg_system = false;
59 static TranscodeMode arg_transcode = TRANSCODE_OFF;
60 static int arg_newline = -1;
61 static sd_id128_t arg_with_key = _CRED_AUTO;
62 static const char *arg_tpm2_device = NULL;
63 static uint32_t arg_tpm2_pcr_mask = UINT32_MAX;
64 static char *arg_tpm2_public_key = NULL;
65 static uint32_t arg_tpm2_public_key_pcr_mask = UINT32_MAX;
66 static char *arg_tpm2_signature = NULL;
67 static const char *arg_name = NULL;
68 static bool arg_name_any = false;
69 static usec_t arg_timestamp = USEC_INFINITY;
70 static usec_t arg_not_after = USEC_INFINITY;
71 static bool arg_pretty = false;
72 static bool arg_quiet = false;
73 static bool arg_varlink = false;
74 static uid_t arg_uid = UID_INVALID;
75 static CredentialFlags arg_credential_flags = 0;
76 static bool arg_ask_password = true;
77
78 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_public_key, freep);
79 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_signature, freep);
80
81 static const char* transcode_mode_table[_TRANSCODE_MAX] = {
82 [TRANSCODE_OFF] = "off",
83 [TRANSCODE_BASE64] = "base64",
84 [TRANSCODE_UNBASE64] = "unbase64",
85 [TRANSCODE_HEX] = "hex",
86 [TRANSCODE_UNHEX] = "unhex",
87 };
88
89 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(transcode_mode, TranscodeMode);
90
91 typedef enum CredKeyType {
92 CRED_KEY_TYPE_AUTO,
93 CRED_KEY_TYPE_AUTO_INITRD,
94 CRED_KEY_TYPE_HOST,
95 CRED_KEY_TYPE_TPM2,
96 CRED_KEY_TYPE_TPM2_PUBLIC,
97 CRED_KEY_TYPE_HOST_TPM2,
98 CRED_KEY_TYPE_TPM2_HOST,
99 CRED_KEY_TYPE_HOST_TPM2_PUBLIC,
100 CRED_KEY_TYPE_TPM2_PUBLIC_HOST,
101 CRED_KEY_TYPE_NULL,
102 CRED_KEY_TYPE_TPM2_ABSENT,
103 _CRED_KEY_TYPE_MAX,
104 _CRED_KEY_TYPE_INVALID = -EINVAL,
105 } CredKeyType;
106
107 static const char* cred_key_type_table[_CRED_KEY_TYPE_MAX] = {
108 [CRED_KEY_TYPE_AUTO] = "auto",
109 [CRED_KEY_TYPE_AUTO_INITRD] = "auto-initrd",
110 [CRED_KEY_TYPE_HOST] = "host",
111 [CRED_KEY_TYPE_TPM2] = "tpm2",
112 [CRED_KEY_TYPE_TPM2_PUBLIC] = "tpm2-with-public-key",
113 [CRED_KEY_TYPE_HOST_TPM2] = "host+tpm2",
114 [CRED_KEY_TYPE_TPM2_HOST] = "tpm2+host",
115 [CRED_KEY_TYPE_HOST_TPM2_PUBLIC] = "host+tpm2-with-public-key",
116 [CRED_KEY_TYPE_TPM2_PUBLIC_HOST] = "tpm2-with-public-key+host",
117 [CRED_KEY_TYPE_NULL] = "null",
118 [CRED_KEY_TYPE_TPM2_ABSENT] = "tpm2-absent", /* legacy alias */
119 };
120
121 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(cred_key_type, CredKeyType);
122
123 static sd_id128_t cred_key_id[_CRED_KEY_TYPE_MAX] = {
124 [CRED_KEY_TYPE_AUTO] = _CRED_AUTO,
125 [CRED_KEY_TYPE_AUTO_INITRD] = _CRED_AUTO_INITRD,
126 [CRED_KEY_TYPE_HOST] = CRED_AES256_GCM_BY_HOST,
127 [CRED_KEY_TYPE_TPM2] = CRED_AES256_GCM_BY_TPM2_HMAC,
128 [CRED_KEY_TYPE_TPM2_PUBLIC] = CRED_AES256_GCM_BY_TPM2_HMAC_WITH_PK,
129 [CRED_KEY_TYPE_HOST_TPM2] = CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC,
130 [CRED_KEY_TYPE_TPM2_HOST] = CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC,
131 [CRED_KEY_TYPE_HOST_TPM2_PUBLIC] = CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK,
132 [CRED_KEY_TYPE_TPM2_PUBLIC_HOST] = CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK,
133 [CRED_KEY_TYPE_NULL] = CRED_AES256_GCM_BY_NULL,
134 [CRED_KEY_TYPE_TPM2_ABSENT] = CRED_AES256_GCM_BY_NULL,
135 };
136
137 static int open_credential_directory(
138 bool encrypted,
139 DIR **ret_dir,
140 const char **ret_prefix) {
141
142 const char *p;
143 DIR *d;
144 int r;
145
146 assert(ret_dir);
147
148 if (arg_system)
149 /* PID 1 ensures that system credentials are always accessible under the same fixed path. It
150 * will create symlinks if necessary to guarantee that. */
151 r = (encrypted ? get_encrypted_system_credentials_dir : get_system_credentials_dir)(&p);
152 else
153 /* Otherwise take the dirs from the env vars we got passed */
154 r = (encrypted ? get_encrypted_credentials_dir : get_credentials_dir)(&p);
155 if (r == -ENXIO) /* No environment variable? */
156 goto not_found;
157 if (r < 0)
158 return log_error_errno(r, "Failed to get credentials directory: %m");
159
160 d = opendir(p);
161 if (!d) {
162 /* No such dir? Then no creds where passed. (We conditionalize this on arg_system, since for
163 * the per-service case a non-existing path would indicate an issue since the env var would
164 * be set incorrectly in that case.) */
165 if (arg_system && errno == ENOENT)
166 goto not_found;
167
168 return log_error_errno(errno, "Failed to open credentials directory '%s': %m", p);
169 }
170
171 *ret_dir = d;
172
173 if (ret_prefix)
174 *ret_prefix = p;
175
176 return 1;
177
178 not_found:
179 *ret_dir = NULL;
180
181 if (ret_prefix)
182 *ret_prefix = NULL;
183
184 return 0;
185 }
186
187 static int is_tmpfs_with_noswap(dev_t devno) {
188 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
189 int r;
190
191 r = DLOPEN_LIBMOUNT(LOG_DEBUG, SD_ELF_NOTE_DLOPEN_PRIORITY_RECOMMENDED);
192 if (r < 0)
193 return r;
194
195 table = sym_mnt_new_table();
196 if (!table)
197 return -ENOMEM;
198
199 r = sym_mnt_table_parse_mtab(table, /* filename= */ NULL);
200 if (r < 0)
201 return r;
202
203 struct libmnt_fs *fs = sym_mnt_table_find_devno(table, devno, MNT_ITER_FORWARD);
204 if (!fs)
205 return -ENODEV;
206
207 r = sym_mnt_fs_get_option(fs, "noswap", /* value= */ NULL, /* valuesz= */ NULL);
208 if (r < 0)
209 return r;
210
211 return r == 0;
212 }
213
214 static int add_credentials_to_table(Table *t, bool encrypted) {
215 _cleanup_closedir_ DIR *d = NULL;
216 const char *prefix;
217 int r;
218
219 assert(t);
220
221 r = open_credential_directory(encrypted, &d, &prefix);
222 if (r < 0)
223 return r;
224 if (!d)
225 return 0; /* No creds dir set */
226
227 for (;;) {
228 _cleanup_free_ char *j = NULL;
229 const char *secure, *secure_color = NULL;
230 _cleanup_close_ int fd = -EBADF;
231 struct dirent *de;
232 struct stat st;
233
234 errno = 0;
235 de = readdir_no_dot(d);
236 if (!de) {
237 if (errno == 0)
238 break;
239
240 return log_error_errno(errno, "Failed to read credentials directory: %m");
241 }
242
243 if (!IN_SET(de->d_type, DT_REG, DT_UNKNOWN))
244 continue;
245
246 if (!credential_name_valid(de->d_name))
247 continue;
248
249 fd = openat(dirfd(d), de->d_name, O_PATH|O_CLOEXEC|O_NOFOLLOW);
250 if (fd < 0) {
251 if (errno == ENOENT) /* Vanished by now? */
252 continue;
253
254 return log_error_errno(errno, "Failed to open credential '%s': %m", de->d_name);
255 }
256
257 if (fstat(fd, &st) < 0)
258 return log_error_errno(errno, "Failed to stat credential '%s': %m", de->d_name);
259
260 if (!S_ISREG(st.st_mode))
261 continue;
262
263 if (encrypted) {
264 secure = "encrypted";
265 secure_color = ansi_highlight_green();
266 } else if ((st.st_mode & 0377) != 0) {
267 secure = "insecure"; /* Anything that is accessible more than read-only to its owner is insecure */
268 secure_color = ansi_highlight_red();
269 } else {
270 struct statfs sfs;
271 if (fstatfs(fd, &sfs) < 0)
272 return log_error_errno(r, "fstatfs() failed on '%s': %m", de->d_name);
273
274 bool is_secure;
275 if (is_fs_type(&sfs, RAMFS_MAGIC))
276 is_secure = true; /* ramfs is not swappable, hence "secure" */
277 else if (is_fs_type(&sfs, TMPFS_MAGIC)) {
278 r = is_tmpfs_with_noswap(st.st_dev);
279 if (r < 0)
280 log_debug_errno(r, "Failed to determine if file system of '%s' has 'noswap' enabled, assuming not: %m", de->d_name);
281
282 is_secure = r > 0;
283 } else
284 is_secure = false; /* everything else we assume is not "secure" */
285
286 secure = is_secure ? "secure" : "weak";
287 secure_color = is_secure ? ansi_highlight_green() : ansi_highlight_yellow4();
288 }
289
290 j = path_join(prefix, de->d_name);
291 if (!j)
292 return log_oom();
293
294 r = table_add_many(
295 t,
296 TABLE_STRING, de->d_name,
297 TABLE_STRING, secure,
298 TABLE_SET_COLOR, secure_color,
299 TABLE_SIZE, (uint64_t) st.st_size,
300 TABLE_STRING, j);
301 if (r < 0)
302 return table_log_add_error(r);
303 }
304
305 return 1; /* Creds dir set */
306 }
307
308 VERB_DEFAULT_NOARG(verb_list, "list", "Show list of passed credentials");
309 static int verb_list(int argc, char *argv[], uintptr_t _data, void *userdata) {
310 _cleanup_(table_unrefp) Table *t = NULL;
311 int r, q;
312
313 t = table_new("name", "secure", "size", "path");
314 if (!t)
315 return log_oom();
316
317 (void) table_set_align_percent(t, table_get_cell(t, 0, 2), 100);
318
319 r = add_credentials_to_table(t, /* encrypted= */ true);
320 if (r < 0)
321 return r;
322
323 q = add_credentials_to_table(t, /* encrypted= */ false);
324 if (q < 0)
325 return q;
326
327 if (r == 0 && q == 0) {
328 if (arg_system)
329 return log_error_errno(SYNTHETIC_ERRNO(ENXIO), "No credentials passed to system.");
330
331 return log_error_errno(SYNTHETIC_ERRNO(ENXIO), "No credentials passed. (i.e. $CREDENTIALS_DIRECTORY not set.)");
332 }
333
334 if (table_isempty(t) && !sd_json_format_enabled(arg_json_format_flags)) {
335 log_info("No credentials");
336 return 0;
337 }
338
339 return table_print_with_pager(t, arg_json_format_flags, arg_pager_flags, arg_legend);
340 }
341
342 static int transcode(
343 const void *input,
344 size_t input_size,
345 void **ret_output,
346 size_t *ret_output_size) {
347
348 int r;
349
350 assert(input);
351 assert(input_size);
352 assert(ret_output);
353 assert(ret_output_size);
354
355 switch (arg_transcode) {
356
357 case TRANSCODE_BASE64: {
358 char *buf;
359 ssize_t l;
360
361 l = base64mem_full(input, input_size, 79, &buf);
362 if (l < 0)
363 return l;
364
365 *ret_output = buf;
366 *ret_output_size = l;
367 return 0;
368 }
369
370 case TRANSCODE_UNBASE64:
371 r = unbase64mem_full(input, input_size, true, ret_output, ret_output_size);
372 if (r == -EPIPE) /* Uneven number of chars */
373 return -EINVAL;
374
375 return r;
376
377 case TRANSCODE_HEX: {
378 char *buf;
379
380 buf = hexmem(input, input_size);
381 if (!buf)
382 return -ENOMEM;
383
384 *ret_output = buf;
385 *ret_output_size = input_size * 2;
386 return 0;
387 }
388
389 case TRANSCODE_UNHEX:
390 r = unhexmem_full(input, input_size, true, ret_output, ret_output_size);
391 if (r == -EPIPE) /* Uneven number of chars */
392 return -EINVAL;
393
394 return r;
395
396 default:
397 assert_not_reached();
398 }
399 }
400
401 static int print_newline(FILE *f, const char *data, size_t l) {
402 assert(f);
403 assert(data || l == 0);
404
405 /* If turned off explicitly, don't print newline */
406 if (arg_newline == 0)
407 return 0;
408
409 /* If data already has newline, don't print either */
410 if (l > 0 && data[l-1] == '\n')
411 return 0;
412
413 /* If not explicitly requested, don't bother if the output is not a tty */
414 if (arg_newline < 0) {
415 int fd = fileno(f);
416 if (fd >= 0 && !isatty_safe(fd))
417 return 0;
418 }
419
420 if (fputc('\n', f) == EOF)
421 return log_error_errno(errno, "Failed to write trailing newline: %m");
422
423 return 1;
424 }
425
426 static int write_blob(FILE *f, const void *data, size_t size) {
427 _cleanup_(erase_and_freep) void *transcoded = NULL;
428 int r;
429
430 if (arg_transcode == TRANSCODE_OFF &&
431 sd_json_format_enabled(arg_json_format_flags)) {
432 _cleanup_(erase_and_freep) char *suffixed = NULL;
433 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
434
435 r = make_cstring(data, size, MAKE_CSTRING_REFUSE_TRAILING_NUL, &suffixed);
436 if (r < 0)
437 return log_error_errno(r, "Unable to convert binary string to C string: %m");
438
439 r = sd_json_parse(suffixed, SD_JSON_PARSE_SENSITIVE, &v, NULL, NULL);
440 if (r < 0)
441 return log_error_errno(r, "Failed to parse JSON: %m");
442
443 sd_json_variant_dump(v, arg_json_format_flags, f, NULL);
444 return 0;
445 }
446
447 if (arg_transcode != TRANSCODE_OFF) {
448 r = transcode(data, size, &transcoded, &size);
449 if (r < 0)
450 return log_error_errno(r, "Failed to transcode data: %m");
451
452 data = transcoded;
453 }
454
455 if (fwrite(data, 1, size, f) != size)
456 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to write credential data.");
457
458 r = print_newline(f, data, size);
459 if (r < 0)
460 return r;
461
462 r = fflush_and_check(f);
463 if (r < 0)
464 return log_error_errno(r, "Failed to flush output: %m");
465
466 return 0;
467 }
468
469 VERB(verb_cat, "cat", "CREDENTIAL...", 2, VERB_ANY, 0,
470 "Show contents of specified credentials");
471 static int verb_cat(int argc, char *argv[], uintptr_t _data, void *userdata) {
472 usec_t timestamp;
473 int r, ret = 0;
474
475 timestamp = arg_timestamp != USEC_INFINITY ? arg_timestamp : now(CLOCK_REALTIME);
476
477 STRV_FOREACH(cn, strv_skip(argv, 1)) {
478 _cleanup_(erase_and_freep) void *content = NULL;
479 size_t size = 0;
480 int encrypted;
481
482 if (!credential_name_valid(*cn)) {
483 RET_GATHER(ret, log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Credential name '%s' is not valid.", *cn));
484 continue;
485 }
486
487 /* Look both in regular and in encrypted credentials */
488 for (encrypted = 0; encrypted < 2; encrypted++) {
489 _cleanup_closedir_ DIR *d = NULL;
490
491 r = open_credential_directory(encrypted, &d, NULL);
492 if (r < 0)
493 return log_error_errno(r, "Failed to open credentials directory: %m");
494 if (!d) /* Not set */
495 continue;
496
497 ReadFullFileFlags flags = READ_FULL_FILE_SECURE|READ_FULL_FILE_WARN_WORLD_READABLE;
498 if (encrypted)
499 flags |= READ_FULL_FILE_UNBASE64;
500
501 r = read_full_file_full(
502 dirfd(d), *cn,
503 UINT64_MAX, SIZE_MAX,
504 flags,
505 NULL,
506 (char**) &content, &size);
507 if (r == -ENOENT) /* Not found */
508 continue;
509 if (r >= 0) /* Found */
510 break;
511
512 RET_GATHER(ret, log_error_errno(r, "Failed to read credential '%s': %m", *cn));
513 }
514
515 if (encrypted >= 2) { /* Found nowhere */
516 RET_GATHER(ret, log_error_errno(SYNTHETIC_ERRNO(ENOENT), "Credential '%s' not set.", *cn));
517 continue;
518 }
519
520 if (encrypted) {
521 _cleanup_(iovec_done_erase) struct iovec plaintext = {};
522
523 if (geteuid() != 0)
524 r = ipc_decrypt_credential(
525 *cn,
526 timestamp,
527 uid_is_valid(arg_uid) ? arg_uid : getuid(),
528 &IOVEC_MAKE(content, size),
529 arg_credential_flags | CREDENTIAL_ANY_SCOPE,
530 &plaintext);
531 else
532 r = decrypt_credential_and_warn(
533 *cn,
534 timestamp,
535 arg_tpm2_device,
536 arg_tpm2_signature,
537 uid_is_valid(arg_uid) ? arg_uid : getuid(),
538 &IOVEC_MAKE(content, size),
539 arg_credential_flags | CREDENTIAL_ANY_SCOPE,
540 &plaintext);
541 if (r < 0)
542 return r;
543
544 erase_and_free(content);
545 content = TAKE_PTR(plaintext.iov_base);
546 size = plaintext.iov_len;
547 }
548
549 r = write_blob(stdout, content, size);
550 if (r < 0)
551 return r;
552 }
553
554 return ret;
555 }
556
557 VERB(verb_encrypt, "encrypt", "INPUT OUTPUT", 3, 3, 0,
558 "Encrypt plaintext credential file and write to ciphertext credential file");
559 static int verb_encrypt(int argc, char *argv[], uintptr_t _data, void *userdata) {
560 _cleanup_(iovec_done_erase) struct iovec plaintext = {}, output = {};
561 _cleanup_free_ char *base64_buf = NULL, *fname = NULL;
562 const char *input_path, *output_path, *name;
563 ssize_t base64_size;
564 usec_t timestamp;
565 int r;
566
567 assert(argc == 3);
568
569 input_path = empty_or_dash(argv[1]) ? NULL : argv[1];
570
571 if (input_path)
572 r = read_full_file_full(AT_FDCWD, input_path, UINT64_MAX, CREDENTIAL_SIZE_MAX, READ_FULL_FILE_SECURE|READ_FULL_FILE_FAIL_WHEN_LARGER, NULL, (char**) &plaintext.iov_base, &plaintext.iov_len);
573 else
574 r = read_full_stream_full(stdin, NULL, UINT64_MAX, CREDENTIAL_SIZE_MAX, READ_FULL_FILE_SECURE|READ_FULL_FILE_FAIL_WHEN_LARGER, (char**) &plaintext.iov_base, &plaintext.iov_len);
575 if (r == -E2BIG)
576 return log_error_errno(r, "Plaintext too long for credential (allowed size: %zu).", (size_t) CREDENTIAL_SIZE_MAX);
577 if (r < 0)
578 return log_error_errno(r, "Failed to read plaintext: %m");
579
580 output_path = empty_or_dash(argv[2]) ? NULL : argv[2];
581
582 if (arg_name_any)
583 name = NULL;
584 else if (arg_name)
585 name = arg_name;
586 else if (output_path) {
587 r = path_extract_filename(output_path, &fname);
588 if (r < 0)
589 return log_error_errno(r, "Failed to extract filename from '%s': %m", output_path);
590 if (r == O_DIRECTORY)
591 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Path '%s' refers to directory, refusing.", output_path);
592
593 name = fname;
594 } else {
595 log_warning("No credential name specified, not embedding credential name in encrypted data. (Disable this warning with --name=)");
596 name = NULL;
597 }
598
599 timestamp = arg_timestamp != USEC_INFINITY ? arg_timestamp : now(CLOCK_REALTIME);
600
601 if (arg_not_after != USEC_INFINITY && arg_not_after < timestamp)
602 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Credential is invalidated before it is valid.");
603
604 if (geteuid() != 0) {
605 (void) polkit_agent_open_if_enabled(BUS_TRANSPORT_LOCAL, arg_ask_password);
606
607 r = ipc_encrypt_credential(
608 name,
609 timestamp,
610 arg_not_after,
611 arg_uid,
612 &plaintext,
613 arg_credential_flags,
614 &output);
615 } else
616 r = encrypt_credential_and_warn(
617 arg_with_key,
618 name,
619 timestamp,
620 arg_not_after,
621 arg_tpm2_device,
622 arg_tpm2_pcr_mask,
623 arg_tpm2_public_key,
624 arg_tpm2_public_key_pcr_mask,
625 arg_uid,
626 &plaintext,
627 arg_credential_flags,
628 &output);
629 if (r < 0)
630 return r;
631
632 base64_size = base64mem_full(output.iov_base, output.iov_len, arg_pretty ? 69 : 79, &base64_buf);
633 if (base64_size < 0)
634 return base64_size;
635
636 /* Pretty print makes sense only if we're printing stuff to stdout
637 * and if a cred name is provided via --name= (since we can't use
638 * the output file name as the cred name here) */
639 if (arg_pretty && !output_path && name) {
640 _cleanup_free_ char *escaped = NULL, *indented = NULL, *j = NULL;
641
642 escaped = cescape(name);
643 if (!escaped)
644 return log_oom();
645
646 indented = strreplace(base64_buf, "\n", " \\\n ");
647 if (!indented)
648 return log_oom();
649
650 j = strjoin("SetCredentialEncrypted=", escaped, ": \\\n ", indented, "\n");
651 if (!j)
652 return log_oom();
653
654 free_and_replace(base64_buf, j);
655 }
656
657 if (output_path)
658 r = write_string_file(output_path, base64_buf, WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_CREATE);
659 else
660 r = write_string_stream(stdout, base64_buf, 0);
661 if (r < 0)
662 return log_error_errno(r, "Failed to write result: %m");
663
664 return EXIT_SUCCESS;
665 }
666
667 VERB(verb_decrypt, "decrypt", "INPUT [OUTPUT]", 2, 3, 0,
668 "Decrypt ciphertext credential file and write to plaintext credential file");
669 static int verb_decrypt(int argc, char *argv[], uintptr_t _data, void *userdata) {
670 _cleanup_(iovec_done_erase) struct iovec input = {}, plaintext = {};
671 _cleanup_free_ char *fname = NULL;
672 _cleanup_fclose_ FILE *output_file = NULL;
673 const char *input_path, *output_path, *name;
674 usec_t timestamp;
675 FILE *f;
676 int r;
677
678 assert(IN_SET(argc, 2, 3));
679
680 input_path = empty_or_dash(argv[1]) ? NULL : argv[1];
681
682 if (input_path)
683 r = read_full_file_full(AT_FDCWD, argv[1], UINT64_MAX, CREDENTIAL_ENCRYPTED_SIZE_MAX, READ_FULL_FILE_UNBASE64|READ_FULL_FILE_FAIL_WHEN_LARGER, NULL, (char**) &input, &input.iov_len);
684 else
685 r = read_full_stream_full(stdin, NULL, UINT64_MAX, CREDENTIAL_ENCRYPTED_SIZE_MAX, READ_FULL_FILE_UNBASE64|READ_FULL_FILE_FAIL_WHEN_LARGER, (char**) &input, &input.iov_len);
686 if (r == -E2BIG)
687 return log_error_errno(r, "Data too long for encrypted credential (allowed size: %zu).", (size_t) CREDENTIAL_ENCRYPTED_SIZE_MAX);
688 if (r < 0)
689 return log_error_errno(r, "Failed to read encrypted credential data: %m");
690
691 output_path = (argc < 3 || empty_or_dash(argv[2])) ? NULL : argv[2];
692
693 if (arg_name_any)
694 name = NULL;
695 else if (arg_name)
696 name = arg_name;
697 else if (input_path) {
698 r = path_extract_filename(input_path, &fname);
699 if (r < 0)
700 return log_error_errno(r, "Failed to extract filename from '%s': %m", input_path);
701 if (r == O_DIRECTORY)
702 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Path '%s' refers to directory, refusing.", input_path);
703
704 name = fname;
705 } else {
706 log_warning("No credential name specified, not validating credential name embedded in encrypted data. (Disable this warning with --name=.)");
707 name = NULL;
708 }
709
710 timestamp = arg_timestamp != USEC_INFINITY ? arg_timestamp : now(CLOCK_REALTIME);
711
712 if (geteuid() != 0) {
713 (void) polkit_agent_open_if_enabled(BUS_TRANSPORT_LOCAL, arg_ask_password);
714
715 r = ipc_decrypt_credential(
716 name,
717 timestamp,
718 arg_uid,
719 &input,
720 arg_credential_flags,
721 &plaintext);
722 } else
723 r = decrypt_credential_and_warn(
724 name,
725 timestamp,
726 arg_tpm2_device,
727 arg_tpm2_signature,
728 arg_uid,
729 &input,
730 arg_credential_flags,
731 &plaintext);
732 if (r < 0)
733 return r;
734
735 if (output_path) {
736 output_file = fopen(output_path, "we");
737 if (!output_file)
738 return log_error_errno(errno, "Failed to create output file '%s': %m", output_path);
739
740 f = output_file;
741 } else
742 f = stdout;
743
744 r = write_blob(f, plaintext.iov_base, plaintext.iov_len);
745 if (r < 0)
746 return r;
747
748 return EXIT_SUCCESS;
749 }
750
751 VERB_NOARG(verb_setup, "setup",
752 "Generate credentials host key, if not existing yet");
753 static int verb_setup(int argc, char *argv[], uintptr_t _data, void *userdata) {
754 _cleanup_(iovec_done_erase) struct iovec host_key = {};
755 int r;
756
757 r = get_credential_host_secret(CREDENTIAL_SECRET_GENERATE|CREDENTIAL_SECRET_WARN_NOT_ENCRYPTED, &host_key);
758 if (r < 0)
759 return log_error_errno(r, "Failed to setup credentials host key: %m");
760
761 log_info("%zu byte credentials host key set up.", host_key.iov_len);
762
763 return EXIT_SUCCESS;
764 }
765
766 /* For backward compatibility. Hidden from help. */
767 VERB(verb_has_tpm2, "has-tpm2", NULL, VERB_ANY, 1, 0, /* help= */ NULL);
768 static int verb_has_tpm2(int argc, char *argv[], uintptr_t _data, void *userdata) {
769 if (!arg_quiet)
770 log_notice("The 'systemd-creds %1$s' command has been replaced by 'systemd-analyze %1$s'. Redirecting invocation.", argv[0]);
771
772 return verb_has_tpm2_generic(arg_quiet);
773 }
774
775 static int help(void) {
776 _cleanup_free_ char *link = NULL;
777 _cleanup_(table_unrefp) Table *options = NULL, *verbs = NULL;
778 int r;
779
780 r = terminal_urlify_man("systemd-creds", "1", &link);
781 if (r < 0)
782 return log_oom();
783
784 r = verbs_get_help_table(&verbs);
785 if (r < 0)
786 return r;
787
788 r = option_parser_get_help_table(&options);
789 if (r < 0)
790 return r;
791
792 (void) table_sync_column_widths(0, verbs, options);
793
794 printf("%s [OPTIONS...] COMMAND ...\n\n"
795 "%sDisplay and Process Credentials.%s\n"
796 "\n%sCommands:%s\n",
797 program_invocation_short_name,
798 ansi_highlight(),
799 ansi_normal(),
800 ansi_underline(),
801 ansi_normal());
802
803 r = table_print_or_warn(verbs);
804 if (r < 0)
805 return r;
806
807 printf("\n%sOptions:%s\n",
808 ansi_underline(),
809 ansi_normal());
810
811 r = table_print_or_warn(options);
812 if (r < 0)
813 return r;
814
815 printf("\nSee the %s for details.\n", link);
816 return 0;
817 }
818
819 VERB_COMMON_HELP(help);
820
821 static int parse_argv(int argc, char *argv[], char ***ret_args) {
822 assert(argc >= 0);
823 assert(argv);
824
825 OptionParser opts = { argc, argv };
826 int r;
827
828 FOREACH_OPTION_OR_RETURN(c, &opts)
829 switch (c) {
830
831 OPTION_COMMON_HELP:
832 return help();
833
834 OPTION_COMMON_VERSION:
835 return version();
836
837 OPTION_COMMON_NO_PAGER:
838 arg_pager_flags |= PAGER_DISABLE;
839 break;
840
841 OPTION_COMMON_NO_LEGEND:
842 arg_legend = false;
843 break;
844
845 OPTION_COMMON_JSON:
846 r = parse_json_argument(opts.arg, &arg_json_format_flags);
847 if (r <= 0)
848 return r;
849 break;
850
851 OPTION_LONG("system", NULL, "Show credentials passed to system"):
852 arg_system = true;
853 break;
854
855 OPTION_LONG("transcode", "METHOD",
856 "Transcode credential data (base64, unbase64, hex, unhex)"):
857 if (streq(opts.arg, "help")) {
858 if (arg_legend)
859 puts("Supported transcode types:");
860
861 return DUMP_STRING_TABLE(transcode_mode, TranscodeMode, _TRANSCODE_MAX);
862 }
863
864 if (parse_boolean(opts.arg) == 0) /* If specified as "false", turn transcoding off */
865 arg_transcode = TRANSCODE_OFF;
866 else {
867 TranscodeMode m;
868
869 m = transcode_mode_from_string(opts.arg);
870 if (m < 0)
871 return log_error_errno(m, "Failed to parse transcode mode: %m");
872
873 arg_transcode = m;
874 }
875 break;
876
877 OPTION_LONG("newline", "auto|yes|no", "Suffix output with newline"):
878 r = parse_tristate_argument_with_auto("--newline=", opts.arg, &arg_newline);
879 if (r < 0)
880 return r;
881 break;
882
883 OPTION('p', "pretty", NULL, "Output as SetCredentialEncrypted= line"):
884 arg_pretty = true;
885 break;
886
887 OPTION_LONG("name", "NAME",
888 "Override filename included in encrypted credential"):
889 if (isempty(opts.arg)) {
890 arg_name = NULL;
891 arg_name_any = true;
892 break;
893 }
894
895 if (!credential_name_valid(opts.arg))
896 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid credential name: %s", opts.arg);
897
898 arg_name = opts.arg;
899 arg_name_any = false;
900 break;
901
902 OPTION_LONG("timestamp", "TIME",
903 "Include specified timestamp in encrypted credential"):
904 r = parse_timestamp(opts.arg, &arg_timestamp);
905 if (r < 0)
906 return log_error_errno(r, "Failed to parse timestamp: %s", opts.arg);
907 break;
908
909 OPTION_LONG("not-after", "TIME",
910 "Include specified invalidation time in encrypted credential"):
911 r = parse_timestamp(opts.arg, &arg_not_after);
912 if (r < 0)
913 return log_error_errno(r, "Failed to parse --not-after= timestamp: %s", opts.arg);
914 break;
915
916 OPTION_LONG("with-key", "KEY",
917 "Which keys to encrypt with (host, tpm2, host+tpm2, null, auto, auto-initrd)"):
918 if (streq(opts.arg, "help")) {
919 if (arg_legend)
920 puts("Supported key types:");
921 return DUMP_STRING_TABLE(cred_key_type, CredKeyType, _CRED_KEY_TYPE_MAX);
922 }
923
924 if (isempty(opts.arg))
925 arg_with_key = _CRED_AUTO;
926 else {
927 CredKeyType t = cred_key_type_from_string(opts.arg);
928 if (t < 0)
929 return log_error_errno(t, "Failed to parse key type: %m");
930
931 arg_with_key = cred_key_id[t];
932 }
933 break;
934
935 OPTION_SHORT('H', NULL, "Shortcut for --with-key=host"):
936 arg_with_key = CRED_AES256_GCM_BY_HOST;
937 break;
938
939 OPTION_SHORT('T', NULL, "Shortcut for --with-key=tpm2"):
940 arg_with_key = _CRED_AUTO_TPM2;
941 break;
942
943 OPTION_LONG("tpm2-device", "PATH", "Pick TPM2 device"):
944 if (streq(opts.arg, "list"))
945 return tpm2_list_devices(arg_legend, arg_quiet);
946
947 arg_tpm2_device = streq(opts.arg, "auto") ? NULL : opts.arg;
948 break;
949
950 OPTION_LONG("tpm2-pcrs", "PCR1+PCR2+PCR3+…",
951 "Specify TPM2 PCRs to seal against (fixed hash)"):
952 /* For fixed hash PCR policies only */
953 r = tpm2_parse_pcr_argument_to_mask(opts.arg, &arg_tpm2_pcr_mask);
954 if (r < 0)
955 return r;
956 break;
957
958 OPTION_LONG("tpm2-public-key", "PATH",
959 "Specify PEM certificate to seal against"):
960 r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_tpm2_public_key);
961 if (r < 0)
962 return r;
963 break;
964
965 OPTION_LONG("tpm2-public-key-pcrs", "PCR1+PCR2+…",
966 "Specify TPM2 PCRs to seal against (public key)"):
967 /* For public key PCR policies only */
968 r = tpm2_parse_pcr_argument_to_mask(opts.arg, &arg_tpm2_public_key_pcr_mask);
969 if (r < 0)
970 return r;
971 break;
972
973 OPTION_LONG("tpm2-signature", "PATH",
974 "Specify signature for public key PCR policy"):
975 r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_tpm2_signature);
976 if (r < 0)
977 return r;
978 break;
979
980 OPTION_LONG("user", NULL, "Select user-scoped credential encryption"):
981 if (!uid_is_valid(arg_uid))
982 arg_uid = getuid();
983 break;
984
985 OPTION_LONG("uid", "UID", "Select user for scoped credentials"):
986 if (isempty(opts.arg))
987 arg_uid = UID_INVALID;
988 else if (streq(opts.arg, "self"))
989 arg_uid = getuid();
990 else {
991 r = get_user_creds(
992 opts.arg,
993 /* flags= */ 0,
994 /* ret_username= */ NULL,
995 &arg_uid,
996 /* ret_gid= */ NULL,
997 /* ret_home= */ NULL,
998 /* ret_shell= */ NULL);
999 if (r < 0)
1000 return log_error_errno(r, "Failed to resolve user '%s': %s",
1001 opts.arg, STRERROR_USER(r));
1002 }
1003 break;
1004
1005 OPTION_LONG("allow-null", NULL,
1006 "Allow decrypting credentials with null key"):
1007 arg_credential_flags &= ~CREDENTIAL_REFUSE_NULL;
1008 arg_credential_flags |= CREDENTIAL_ALLOW_NULL;
1009 break;
1010
1011 OPTION_LONG("refuse-null", NULL,
1012 "Refuse decrypting credentials with null key"):
1013 arg_credential_flags |= CREDENTIAL_REFUSE_NULL;
1014 arg_credential_flags &= ~CREDENTIAL_ALLOW_NULL;
1015 break;
1016
1017 OPTION_COMMON_NO_ASK_PASSWORD:
1018 arg_ask_password = false;
1019 break;
1020
1021 OPTION('q', "quiet", NULL, "Suppress informational messages"):
1022 arg_quiet = true;
1023 break;
1024 }
1025
1026 SET_FLAG(arg_credential_flags, CREDENTIAL_IPC_ALLOW_INTERACTIVE, arg_ask_password);
1027
1028 if (uid_is_valid(arg_uid)) {
1029 /* If a UID is specified, then switch to scoped credentials */
1030
1031 if (sd_id128_equal(arg_with_key, _CRED_AUTO))
1032 arg_with_key = _CRED_AUTO_SCOPED;
1033 else if (sd_id128_in_set(arg_with_key, CRED_AES256_GCM_BY_HOST, CRED_AES256_GCM_BY_HOST_SCOPED))
1034 arg_with_key = CRED_AES256_GCM_BY_HOST_SCOPED;
1035 else if (sd_id128_in_set(arg_with_key, CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC, CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_SCOPED))
1036 arg_with_key = CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_SCOPED;
1037 else if (sd_id128_in_set(arg_with_key, CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK, CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK_SCOPED))
1038 arg_with_key = CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK_SCOPED;
1039 else
1040 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Selected key not available in --uid= scoped mode, refusing.");
1041 }
1042
1043 if (arg_tpm2_pcr_mask == UINT32_MAX)
1044 arg_tpm2_pcr_mask = 0;
1045 if (arg_tpm2_public_key_pcr_mask == UINT32_MAX)
1046 arg_tpm2_public_key_pcr_mask = UINT32_C(1) << TPM2_PCR_KERNEL_BOOT;
1047
1048 r = sd_varlink_invocation(SD_VARLINK_ALLOW_ACCEPT);
1049 if (r < 0)
1050 return log_error_errno(r, "Failed to check if invoked in Varlink mode: %m");
1051 arg_varlink = r;
1052
1053 *ret_args = option_parser_get_args(&opts);
1054 return 1;
1055 }
1056
1057 #define TIMESTAMP_FRESH_MAX (30*USEC_PER_SEC)
1058
1059 static bool timestamp_is_fresh(usec_t x) {
1060 usec_t n = now(CLOCK_REALTIME);
1061
1062 /* We'll only allow unprivileged encryption/decryption for somehwhat "fresh" timestamps */
1063
1064 if (x > n)
1065 return x - n <= TIMESTAMP_FRESH_MAX;
1066 else
1067 return n - x <= TIMESTAMP_FRESH_MAX;
1068 }
1069
1070 typedef enum CredentialScope {
1071 CREDENTIAL_SYSTEM,
1072 CREDENTIAL_USER,
1073 /* One day we should add more here, for example, per-app/per-service credentials */
1074 _CREDENTIAL_SCOPE_MAX,
1075 _CREDENTIAL_SCOPE_INVALID = -EINVAL,
1076 } CredentialScope;
1077
1078 static const char* credential_scope_table[_CREDENTIAL_SCOPE_MAX] = {
1079 [CREDENTIAL_SYSTEM] = "system",
1080 [CREDENTIAL_USER] = "user",
1081 };
1082
1083 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(credential_scope, CredentialScope);
1084 static JSON_DISPATCH_ENUM_DEFINE(dispatch_credential_scope, CredentialScope, credential_scope_from_string);
1085
1086 typedef struct MethodEncryptParameters {
1087 const char *name;
1088 const char *text;
1089 struct iovec data;
1090 uint64_t timestamp;
1091 uint64_t not_after;
1092 CredentialScope scope;
1093 sd_id128_t with_key;
1094 uid_t uid;
1095 } MethodEncryptParameters;
1096
1097 static void method_encrypt_parameters_done(MethodEncryptParameters *p) {
1098 assert(p);
1099
1100 iovec_done_erase(&p->data);
1101 }
1102
1103 static int settle_scope(
1104 sd_varlink *link,
1105 CredentialScope *scope,
1106 uid_t *uid,
1107 CredentialFlags *flags,
1108 bool *any_scope_after_polkit) {
1109
1110 uid_t peer_uid;
1111 int r;
1112
1113 assert(link);
1114 assert(scope);
1115 assert(uid);
1116 assert(flags);
1117
1118 r = sd_varlink_get_peer_uid(link, &peer_uid);
1119 if (r < 0)
1120 return r;
1121
1122 if (*scope < 0) {
1123 if (uid_is_valid(*uid))
1124 *scope = CREDENTIAL_USER;
1125 else {
1126 *scope = CREDENTIAL_SYSTEM; /* When encrypting, we spit out a system credential */
1127 *uid = peer_uid; /* When decrypting a user credential, use this UID */
1128 }
1129
1130 if (peer_uid == 0)
1131 *flags |= CREDENTIAL_ANY_SCOPE;
1132
1133 if (any_scope_after_polkit)
1134 *any_scope_after_polkit = true;
1135 } else if (*scope == CREDENTIAL_USER) {
1136 if (!uid_is_valid(*uid))
1137 *uid = peer_uid;
1138 } else {
1139 assert(*scope == CREDENTIAL_SYSTEM);
1140 if (uid_is_valid(*uid))
1141 return sd_varlink_error_invalid_parameter_name(link, "uid");
1142 }
1143
1144 return 0;
1145 }
1146
1147 static char normalize_separator(char c) {
1148 if (IN_SET(c, '-', '+', '_'))
1149 return '_';
1150
1151 return c;
1152 }
1153
1154 static bool enum_name_equal(const char *x, const char *y) {
1155 if (x == y)
1156 return true;
1157 if (!x || !y)
1158 return false;
1159
1160 for (;; x++, y++) {
1161 char a = normalize_separator(*x), b = normalize_separator(*y);
1162 if (a != b)
1163 return false;
1164 if (a == 0)
1165 return true;
1166 }
1167 }
1168
1169 static CredKeyType cred_key_type_from_string_harder(const char *s) {
1170 if (!s)
1171 return _CRED_KEY_TYPE_INVALID;
1172
1173 CredKeyType t = cred_key_type_from_string(s);
1174 if (t >= 0)
1175 return t;
1176
1177 /* Varlink doesn't like dashes and plusses in enum names. Try to match when considering them equal to underscores */
1178 for (t = 0; t < _CRED_KEY_TYPE_MAX; t++)
1179 if (enum_name_equal(cred_key_type_table[t], s))
1180 return t;
1181
1182 return _CRED_KEY_TYPE_INVALID;
1183 }
1184
1185 static int dispatch_credential_key_type(
1186 const char *name,
1187 sd_json_variant *variant,
1188 sd_json_dispatch_flags_t flags,
1189 void *userdata) {
1190
1191 sd_id128_t *id = ASSERT_PTR(userdata);
1192
1193 if (sd_json_variant_is_null(variant)) {
1194 *id = SD_ID128_NULL;
1195 return 0;
1196 }
1197
1198 const char *s = sd_json_variant_string(variant);
1199 if (isempty(s)) {
1200 *id = SD_ID128_NULL;
1201 return 0;
1202 }
1203
1204 CredKeyType t = cred_key_type_from_string_harder(s);
1205 if (t < 0)
1206 return json_log(variant, flags, t, "JSON field '%s' is not a valid key type.", strna(name));
1207
1208 *id = cred_key_id[t];
1209 return 0;
1210 }
1211
1212 static int vl_method_encrypt(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
1213
1214 static const sd_json_dispatch_field dispatch_table[] = {
1215 { "name", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, offsetof(MethodEncryptParameters, name), 0 },
1216 { "text", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, offsetof(MethodEncryptParameters, text), 0 },
1217 { "data", SD_JSON_VARIANT_STRING, json_dispatch_unbase64_iovec, offsetof(MethodEncryptParameters, data), 0 },
1218 { "timestamp", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64, offsetof(MethodEncryptParameters, timestamp), 0 },
1219 { "notAfter", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64, offsetof(MethodEncryptParameters, not_after), 0 },
1220 { "scope", SD_JSON_VARIANT_STRING, dispatch_credential_scope, offsetof(MethodEncryptParameters, scope), 0 },
1221 { "withKey", SD_JSON_VARIANT_STRING, dispatch_credential_key_type, offsetof(MethodEncryptParameters, with_key), SD_JSON_NULLABLE },
1222 { "uid", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uid_gid, offsetof(MethodEncryptParameters, uid), 0 },
1223 VARLINK_DISPATCH_POLKIT_FIELD,
1224 {}
1225 };
1226 _cleanup_(method_encrypt_parameters_done) MethodEncryptParameters p = {
1227 .timestamp = UINT64_MAX,
1228 .not_after = UINT64_MAX,
1229 .scope = _CREDENTIAL_SCOPE_INVALID,
1230 .uid = UID_INVALID,
1231 };
1232 _cleanup_(iovec_done) struct iovec output = {};
1233 Hashmap **polkit_registry = ASSERT_PTR(userdata);
1234 CredentialFlags cflags = 0;
1235 bool timestamp_fresh;
1236 uid_t peer_uid;
1237 int r;
1238
1239 assert(link);
1240
1241 r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
1242 if (r != 0)
1243 return r;
1244
1245 if (p.name && !credential_name_valid(p.name))
1246 return sd_varlink_error_invalid_parameter_name(link, "name");
1247 /* Specifying both or neither the text string and the binary data is not allowed */
1248 if (!!p.text == !!p.data.iov_base)
1249 return sd_varlink_error_invalid_parameter_name(link, "data");
1250 if (p.timestamp == UINT64_MAX) {
1251 p.timestamp = now(CLOCK_REALTIME);
1252 timestamp_fresh = true;
1253 } else
1254 timestamp_fresh = timestamp_is_fresh(p.timestamp);
1255 if (p.not_after != UINT64_MAX && p.not_after < p.timestamp)
1256 return sd_varlink_error_invalid_parameter_name(link, "notAfter");
1257
1258 r = settle_scope(link, &p.scope, &p.uid, &cflags, /* any_scope_after_polkit= */ NULL);
1259 if (r < 0)
1260 return r;
1261
1262 r = sd_varlink_get_peer_uid(link, &peer_uid);
1263 if (r < 0)
1264 return r;
1265
1266 /* Relax security requirements if peer wants to encrypt credentials for themselves */
1267 bool own_scope = p.scope == CREDENTIAL_USER && p.uid == peer_uid;
1268
1269 if (!own_scope || !timestamp_fresh) {
1270 /* Insist on PK if client wants to encrypt for another user or the system, or if the timestamp was explicitly overridden. */
1271 r = varlink_verify_polkit_async(
1272 link,
1273 /* bus= */ NULL,
1274 "io.systemd.credentials.encrypt",
1275 /* details= */ NULL,
1276 polkit_registry);
1277 if (r <= 0)
1278 return r;
1279 }
1280
1281 r = encrypt_credential_and_warn(
1282 sd_id128_is_null(p.with_key) ? (p.scope == CREDENTIAL_USER ? _CRED_AUTO_SCOPED : _CRED_AUTO) : p.with_key,
1283 p.name,
1284 p.timestamp,
1285 p.not_after,
1286 arg_tpm2_device,
1287 arg_tpm2_pcr_mask,
1288 arg_tpm2_public_key,
1289 arg_tpm2_public_key_pcr_mask,
1290 p.uid,
1291 p.text ? &IOVEC_MAKE_STRING(p.text) : &p.data,
1292 cflags,
1293 &output);
1294 if (r == -ESRCH)
1295 return sd_varlink_error(link, "io.systemd.Credentials.NoSuchUser", NULL);
1296 if (r < 0)
1297 return r;
1298
1299 _cleanup_(sd_json_variant_unrefp) sd_json_variant *reply = NULL;
1300
1301 r = sd_json_buildo(&reply, JSON_BUILD_PAIR_IOVEC_BASE64("blob", &output));
1302 if (r < 0)
1303 return r;
1304
1305 /* Let's also mark the (theoretically encrypted) reply as sensitive, in case the NULL encryption scheme was used. */
1306 sd_json_variant_sensitive(reply);
1307
1308 return sd_varlink_reply(link, reply);
1309 }
1310
1311 typedef struct MethodDecryptParameters {
1312 const char *name;
1313 struct iovec blob;
1314 uint64_t timestamp;
1315 CredentialScope scope;
1316 uid_t uid;
1317 int allow_null;
1318 } MethodDecryptParameters;
1319
1320 static void method_decrypt_parameters_done(MethodDecryptParameters *p) {
1321 assert(p);
1322
1323 iovec_done_erase(&p->blob);
1324 }
1325
1326 static int vl_method_decrypt(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
1327
1328 static const sd_json_dispatch_field dispatch_table[] = {
1329 { "name", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, offsetof(MethodDecryptParameters, name), 0 },
1330 { "blob", SD_JSON_VARIANT_STRING, json_dispatch_unbase64_iovec, offsetof(MethodDecryptParameters, blob), SD_JSON_MANDATORY },
1331 { "timestamp", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64, offsetof(MethodDecryptParameters, timestamp), 0 },
1332 { "scope", SD_JSON_VARIANT_STRING, dispatch_credential_scope, offsetof(MethodDecryptParameters, scope), 0 },
1333 { "uid", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uid_gid, offsetof(MethodDecryptParameters, uid), 0 },
1334 { "allowNull", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_tristate, offsetof(MethodDecryptParameters, allow_null), SD_JSON_NULLABLE },
1335 VARLINK_DISPATCH_POLKIT_FIELD,
1336 {}
1337 };
1338 _cleanup_(method_decrypt_parameters_done) MethodDecryptParameters p = {
1339 .timestamp = UINT64_MAX,
1340 .scope = _CREDENTIAL_SCOPE_INVALID,
1341 .uid = UID_INVALID,
1342 .allow_null = -1,
1343 };
1344 bool timestamp_fresh, any_scope_after_polkit = false;
1345 _cleanup_(iovec_done_erase) struct iovec output = {};
1346 Hashmap **polkit_registry = ASSERT_PTR(userdata);
1347 CredentialFlags cflags = 0;
1348 uid_t peer_uid;
1349 int r;
1350
1351 assert(link);
1352
1353 r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
1354 if (r != 0)
1355 return r;
1356
1357 if (p.name && !credential_name_valid(p.name))
1358 return sd_varlink_error_invalid_parameter_name(link, "name");
1359 if (p.timestamp == UINT64_MAX) {
1360 p.timestamp = now(CLOCK_REALTIME);
1361 timestamp_fresh = true;
1362 } else
1363 timestamp_fresh = timestamp_is_fresh(p.timestamp);
1364
1365 r = settle_scope(link, &p.scope, &p.uid, &cflags, &any_scope_after_polkit);
1366 if (r < 0)
1367 return r;
1368
1369 if (p.allow_null > 0)
1370 cflags |= CREDENTIAL_ALLOW_NULL;
1371 else if (p.allow_null == 0)
1372 cflags |= CREDENTIAL_REFUSE_NULL;
1373
1374 r = sd_varlink_get_peer_uid(link, &peer_uid);
1375 if (r < 0)
1376 return r;
1377
1378 /* Relax security requirements if peer wants to encrypt credentials for themselves */
1379 bool own_scope = p.scope == CREDENTIAL_USER && p.uid == peer_uid;
1380 bool ask_polkit = !own_scope || !timestamp_fresh;
1381 for (;;) {
1382 if (ask_polkit) {
1383 r = varlink_verify_polkit_async(
1384 link,
1385 /* bus= */ NULL,
1386 "io.systemd.credentials.decrypt",
1387 /* details= */ NULL,
1388 polkit_registry);
1389 if (r <= 0)
1390 return r;
1391
1392 /* Now that we have authenticated, it's fine to allow unpriv clients access to system secrets */
1393 if (any_scope_after_polkit)
1394 cflags |= CREDENTIAL_ANY_SCOPE;
1395 }
1396
1397 r = decrypt_credential_and_warn(
1398 p.name,
1399 p.timestamp,
1400 arg_tpm2_device,
1401 arg_tpm2_signature,
1402 p.uid,
1403 &p.blob,
1404 cflags,
1405 &output);
1406 if (r != -EMEDIUMTYPE || ask_polkit || !any_scope_after_polkit)
1407 break;
1408
1409 /* So the secret was apparently intended for the system. Let's retry decrypting it after
1410 * acquiring polkit's permission. */
1411 ask_polkit = true;
1412 }
1413
1414 if (IN_SET(r, -EREMCHG, -ENOANO, -EUCLEAN, -EPERM))
1415 return sd_varlink_error(link, "io.systemd.Credentials.UnexpectedPCRState", NULL);
1416 if (r < 0) {
1417 const CredentialsVarlinkError *e = credentials_varlink_error_by_errno(r);
1418 if (e)
1419 return sd_varlink_error(link, e->id, NULL);
1420
1421 return r;
1422 }
1423
1424 _cleanup_(sd_json_variant_unrefp) sd_json_variant *reply = NULL;
1425
1426 r = sd_json_buildo(&reply, JSON_BUILD_PAIR_IOVEC_BASE64("data", &output));
1427 if (r < 0)
1428 return r;
1429
1430 sd_json_variant_sensitive(reply);
1431
1432 return sd_varlink_reply(link, reply);
1433 }
1434
1435 static int vl_server(void) {
1436 _cleanup_(sd_varlink_server_unrefp) sd_varlink_server *varlink_server = NULL;
1437 _cleanup_hashmap_free_ Hashmap *polkit_registry = NULL;
1438 int r;
1439
1440 /* Invocation as Varlink service */
1441
1442 r = varlink_server_new(
1443 &varlink_server,
1444 SD_VARLINK_SERVER_ACCOUNT_UID|SD_VARLINK_SERVER_INHERIT_USERDATA|SD_VARLINK_SERVER_INPUT_SENSITIVE,
1445 &polkit_registry);
1446 if (r < 0)
1447 return log_error_errno(r, "Failed to allocate Varlink server: %m");
1448
1449 r = sd_varlink_server_add_interface(varlink_server, &vl_interface_io_systemd_Credentials);
1450 if (r < 0)
1451 return log_error_errno(r, "Failed to add Varlink interface: %m");
1452
1453 r = sd_varlink_server_bind_method_many(
1454 varlink_server,
1455 "io.systemd.Credentials.Encrypt", vl_method_encrypt,
1456 "io.systemd.Credentials.Decrypt", vl_method_decrypt);
1457 if (r < 0)
1458 return log_error_errno(r, "Failed to bind Varlink methods: %m");
1459
1460 r = sd_varlink_server_loop_auto(varlink_server);
1461 if (r < 0)
1462 return log_error_errno(r, "Failed to run Varlink event loop: %m");
1463
1464 return 0;
1465 }
1466
1467 static int run(int argc, char *argv[]) {
1468 int r;
1469
1470 log_setup();
1471
1472 char **args = NULL;
1473 r = parse_argv(argc, argv, &args);
1474 if (r <= 0)
1475 return r;
1476
1477 if (arg_varlink)
1478 return vl_server();
1479
1480 return dispatch_verb(args, NULL);
1481 }
1482
1483 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);