]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/ask-password-api.c
io-util: split out "struct iovec" related calls into their own .c/.h files
[thirdparty/systemd.git] / src / shared / ask-password-api.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
00843602 2
7f4e0805
LP
3#include <errno.h>
4#include <fcntl.h>
a8fbdf54
TA
5#include <inttypes.h>
6#include <limits.h>
00843602 7#include <stdbool.h>
7f4e0805 8#include <stddef.h>
a8fbdf54
TA
9#include <stdint.h>
10#include <stdio.h>
11#include <stdlib.h>
00843602 12#include <sys/inotify.h>
7f4e0805 13#include <sys/signalfd.h>
a8fbdf54
TA
14#include <sys/stat.h>
15#include <sys/time.h>
16#include <sys/uio.h>
00843602
LP
17#include <sys/un.h>
18#include <termios.h>
19#include <unistd.h>
7f4e0805 20
b5efdb8a 21#include "alloc-util.h"
3ffd4af2 22#include "ask-password-api.h"
28db6fbf 23#include "constants.h"
8806bb4b 24#include "creds-util.h"
3ffd4af2 25#include "fd-util.h"
0d39fa9c 26#include "fileio.h"
f97b34a6 27#include "format-util.h"
c7b7d74e 28#include "fs-util.h"
d8e32c47 29#include "glyph-util.h"
c004493c 30#include "io-util.h"
bd1ae178 31#include "iovec-util.h"
cbae575e 32#include "keyring-util.h"
a8fbdf54
TA
33#include "log.h"
34#include "macro.h"
0a970718 35#include "memory-util.h"
f5947a5e 36#include "missing_syscall.h"
35cd0ba5 37#include "mkdir-label.h"
08af3cc5 38#include "nulstr-util.h"
df0ff127 39#include "process-util.h"
3df3e884 40#include "random-util.h"
24882e06 41#include "signal-util.h"
00843602 42#include "socket-util.h"
07630cea 43#include "string-util.h"
00843602
LP
44#include "strv.h"
45#include "terminal-util.h"
a8fbdf54 46#include "time-util.h"
e4de7287 47#include "tmpfile-util.h"
affb60b1 48#include "umask-util.h"
f3149d57 49#include "utf8.h"
7f4e0805 50
e287086b
LP
51#define KEYRING_TIMEOUT_USEC ((5 * USEC_PER_MINUTE) / 2)
52
53static int lookup_key(const char *keyname, key_serial_t *ret) {
54 key_serial_t serial;
55
56 assert(keyname);
57 assert(ret);
58
59 serial = request_key("user", keyname, NULL, 0);
60 if (serial == -1)
9c4615fb 61 return negative_errno();
e287086b
LP
62
63 *ret = serial;
64 return 0;
65}
66
67static int retrieve_key(key_serial_t serial, char ***ret) {
cbae575e 68 _cleanup_(erase_and_freep) void *p = NULL;
e287086b 69 char **l;
cbae575e
LP
70 size_t n;
71 int r;
e287086b
LP
72
73 assert(ret);
74
cbae575e
LP
75 r = keyring_read(serial, &p, &n);
76 if (r < 0)
77 return r;
78
79 l = strv_parse_nulstr(p, n);
e287086b
LP
80 if (!l)
81 return -ENOMEM;
82
83 *ret = l;
84 return 0;
85}
86
87static int add_to_keyring(const char *keyname, AskPasswordFlags flags, char **passwords) {
ab84f5b9 88 _cleanup_strv_free_erase_ char **l = NULL;
e693a932 89 _cleanup_(erase_and_freep) char *p = NULL;
e287086b
LP
90 key_serial_t serial;
91 size_t n;
92 int r;
93
94 assert(keyname);
e287086b 95
9cb5bf91 96 if (!FLAGS_SET(flags, ASK_PASSWORD_PUSH_CACHE))
e287086b 97 return 0;
e013e10d
LP
98 if (strv_isempty(passwords))
99 return 0;
e287086b
LP
100
101 r = lookup_key(keyname, &serial);
102 if (r >= 0) {
103 r = retrieve_key(serial, &l);
104 if (r < 0)
105 return r;
106 } else if (r != -ENOKEY)
107 return r;
108
109 r = strv_extend_strv(&l, passwords, true);
110 if (r <= 0)
111 return r;
112
113 r = strv_make_nulstr(l, &p, &n);
114 if (r < 0)
115 return r;
116
76078ad8
LP
117 /* chop off the final NUL byte. We do this because we want to use the separator NUL bytes only if we
118 * have multiple passwords. */
119 n = LESS_BY(n, (size_t) 1);
120
b60df13b 121 serial = add_key("user", keyname, p, n, KEY_SPEC_USER_KEYRING);
e287086b
LP
122 if (serial == -1)
123 return -errno;
124
125 if (keyctl(KEYCTL_SET_TIMEOUT,
126 (unsigned long) serial,
127 (unsigned long) DIV_ROUND_UP(KEYRING_TIMEOUT_USEC, USEC_PER_SEC), 0, 0) < 0)
e3ac53a2 128 log_debug_errno(errno, "Failed to adjust kernel keyring key timeout: %m");
e287086b 129
c7b7d74e
XF
130 /* Tell everyone to check the keyring */
131 (void) touch("/run/systemd/ask-password");
132
e3ac53a2 133 log_debug("Added key to kernel keyring as %" PRIi32 ".", serial);
e287086b
LP
134
135 return 1;
136}
137
138static int add_to_keyring_and_log(const char *keyname, AskPasswordFlags flags, char **passwords) {
139 int r;
140
141 assert(keyname);
e287086b
LP
142
143 r = add_to_keyring(keyname, flags, passwords);
144 if (r < 0)
e3ac53a2 145 return log_debug_errno(r, "Failed to add password to kernel keyring: %m");
e287086b
LP
146
147 return 0;
148}
149
8a111277 150static int ask_password_keyring(const char *keyname, AskPasswordFlags flags, char ***ret) {
e287086b
LP
151
152 key_serial_t serial;
153 int r;
154
155 assert(keyname);
156 assert(ret);
157
9cb5bf91 158 if (!FLAGS_SET(flags, ASK_PASSWORD_ACCEPT_CACHED))
e287086b
LP
159 return -EUNATCH;
160
161 r = lookup_key(keyname, &serial);
bb44fd07
ZJS
162 if (ERRNO_IS_NEG_NOT_SUPPORTED(r) || r == -EPERM)
163 /* When retrieving, the distinction between "kernel or container manager don't support or
164 * allow this" and "no matching key known" doesn't matter. Note that we propagate EACCESS
165 * here (even if EPERM not) since that is used if the keyring is available, but we lack
166 * access to the key. */
167 return -ENOKEY;
168 if (r < 0)
e287086b
LP
169 return r;
170
171 return retrieve_key(serial, ret);
172}
173
8e9d1eec 174static int backspace_chars(int ttyfd, size_t p) {
58fc840b 175 if (ttyfd < 0)
8e9d1eec 176 return 0;
58fc840b 177
8e9d1eec
ZJS
178 _cleanup_free_ char *buf = malloc_multiply(3, p);
179 if (!buf)
180 return log_oom();
58fc840b 181
8e9d1eec
ZJS
182 for (size_t i = 0; i < p; i++)
183 memcpy(buf + 3 * i, "\b \b", 3);
58fc840b 184
e22c60a9 185 return loop_write(ttyfd, buf, 3 * p);
8e9d1eec 186}
fd6ac62c 187
8e9d1eec 188static int backspace_string(int ttyfd, const char *str) {
fd6ac62c
LP
189 assert(str);
190
f95dbcc2 191 /* Backspaces through enough characters to entirely undo printing of the specified string. */
fd6ac62c 192
8e9d1eec
ZJS
193 if (ttyfd < 0)
194 return 0;
195
196 size_t m = utf8_n_codepoints(str);
f5fbe71d 197 if (m == SIZE_MAX)
8e9d1eec 198 m = strlen(str); /* Not a valid UTF-8 string? If so, let's backspace the number of bytes
5bc9ea07 199 * output. Most likely this happened because we are not in a UTF-8 locale,
8e9d1eec
ZJS
200 * and in that case that is the correct thing to do. And even if it's not,
201 * terminals tend to stop backspacing at the leftmost column, hence
202 * backspacing too much should be mostly OK. */
fd6ac62c 203
8e9d1eec 204 return backspace_chars(ttyfd, m);
fd6ac62c
LP
205}
206
6b2faba7
FB
207int ask_password_plymouth(
208 const char *message,
209 usec_t until,
210 AskPasswordFlags flags,
211 const char *flag_file,
212 char ***ret) {
213
214 static const union sockaddr_union sa = PLYMOUTH_SOCKET;
254d1313 215 _cleanup_close_ int fd = -EBADF, notify = -EBADF;
6b2faba7
FB
216 _cleanup_free_ char *packet = NULL;
217 ssize_t k;
218 int r, n;
219 struct pollfd pollfd[2] = {};
220 char buffer[LINE_MAX];
221 size_t p = 0;
222 enum {
223 POLL_SOCKET,
224 POLL_INOTIFY
225 };
226
227 assert(ret);
228
66bff73b
LP
229 if (!message)
230 message = "Password:";
231
6b2faba7
FB
232 if (flag_file) {
233 notify = inotify_init1(IN_CLOEXEC|IN_NONBLOCK);
234 if (notify < 0)
235 return -errno;
236
108dfff2 237 if (inotify_add_watch(notify, flag_file, IN_ATTRIB) < 0) /* for the link count */
6b2faba7
FB
238 return -errno;
239 }
240
241 fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
242 if (fd < 0)
243 return -errno;
244
108dfff2 245 if (connect(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0)
6b2faba7
FB
246 return -errno;
247
9cb5bf91 248 if (FLAGS_SET(flags, ASK_PASSWORD_ACCEPT_CACHED)) {
6b2faba7
FB
249 packet = strdup("c");
250 n = 1;
251 } else if (asprintf(&packet, "*\002%c%s%n", (int) (strlen(message) + 1), message, &n) < 0)
252 packet = NULL;
253 if (!packet)
254 return -ENOMEM;
255
e22c60a9 256 r = loop_write_full(fd, packet, n + 1, USEC_INFINITY);
6b2faba7
FB
257 if (r < 0)
258 return r;
259
692597c8
LP
260 CLEANUP_ERASE(buffer);
261
6b2faba7
FB
262 pollfd[POLL_SOCKET].fd = fd;
263 pollfd[POLL_SOCKET].events = POLLIN;
264 pollfd[POLL_INOTIFY].fd = notify;
265 pollfd[POLL_INOTIFY].events = POLLIN;
266
267 for (;;) {
d9e2af0a 268 usec_t timeout;
6b2faba7 269
d9e2af0a
YW
270 if (until > 0)
271 timeout = usec_sub_unsigned(until, now(CLOCK_MONOTONIC));
272 else
273 timeout = USEC_INFINITY;
6b2faba7 274
692597c8
LP
275 if (flag_file && access(flag_file, F_OK) < 0)
276 return -errno;
6b2faba7 277
d9e2af0a
YW
278 r = ppoll_usec(pollfd, notify >= 0 ? 2 : 1, timeout);
279 if (r == -EINTR)
280 continue;
281 if (r < 0)
692597c8
LP
282 return r;
283 if (r == 0)
284 return -ETIME;
6b2faba7
FB
285
286 if (notify >= 0 && pollfd[POLL_INOTIFY].revents != 0)
287 (void) flush_fd(notify);
288
289 if (pollfd[POLL_SOCKET].revents == 0)
290 continue;
291
292 k = read(fd, buffer + p, sizeof(buffer) - p);
293 if (k < 0) {
8add30a0 294 if (ERRNO_IS_TRANSIENT(errno))
6b2faba7
FB
295 continue;
296
692597c8 297 return -errno;
6b2faba7 298 }
692597c8
LP
299 if (k == 0)
300 return -EIO;
6b2faba7
FB
301
302 p += k;
303
6b2faba7
FB
304 if (buffer[0] == 5) {
305
9cb5bf91 306 if (FLAGS_SET(flags, ASK_PASSWORD_ACCEPT_CACHED)) {
6b2faba7
FB
307 /* Hmm, first try with cached
308 * passwords failed, so let's retry
309 * with a normal password request */
310 packet = mfree(packet);
311
692597c8
LP
312 if (asprintf(&packet, "*\002%c%s%n", (int) (strlen(message) + 1), message, &n) < 0)
313 return -ENOMEM;
6b2faba7 314
e22c60a9 315 r = loop_write_full(fd, packet, n + 1, USEC_INFINITY);
6b2faba7 316 if (r < 0)
692597c8 317 return r;
6b2faba7
FB
318
319 flags &= ~ASK_PASSWORD_ACCEPT_CACHED;
320 p = 0;
321 continue;
322 }
323
324 /* No password, because UI not shown */
692597c8 325 return -ENOENT;
6b2faba7
FB
326
327 } else if (IN_SET(buffer[0], 2, 9)) {
328 uint32_t size;
329 char **l;
330
331 /* One or more answers */
332 if (p < 5)
333 continue;
334
335 memcpy(&size, buffer+1, sizeof(size));
336 size = le32toh(size);
692597c8
LP
337 if (size + 5 > sizeof(buffer))
338 return -EIO;
6b2faba7
FB
339
340 if (p-5 < size)
341 continue;
342
343 l = strv_parse_nulstr(buffer + 5, size);
692597c8
LP
344 if (!l)
345 return -ENOMEM;
6b2faba7
FB
346
347 *ret = l;
348 break;
349
692597c8 350 } else
6b2faba7 351 /* Unknown packet */
692597c8 352 return -EIO;
6b2faba7
FB
353 }
354
692597c8 355 return 0;
6b2faba7
FB
356}
357
8aaf18e0
ZJS
358#define NO_ECHO "(no echo) "
359#define PRESS_TAB "(press TAB for no echo) "
360#define SKIPPED "(skipped)"
361
7f4e0805 362int ask_password_tty(
daa55720 363 int ttyfd,
7f4e0805 364 const char *message,
e287086b 365 const char *keyname,
7f4e0805 366 usec_t until,
e287086b 367 AskPasswordFlags flags,
7f4e0805 368 const char *flag_file,
c7b7d74e 369 char ***ret) {
7f4e0805 370
088dcd8e
LP
371 enum {
372 POLL_TTY,
373 POLL_INOTIFY,
374 _POLL_MAX,
375 };
376
8aaf18e0 377 bool reset_tty = false, dirty = false, use_color = false, press_tab_visible = false;
254d1313 378 _cleanup_close_ int cttyfd = -EBADF, notify = -EBADF;
7f4e0805 379 struct termios old_termios, new_termios;
f3149d57 380 char passphrase[LINE_MAX + 1] = {}, *x;
c7b7d74e 381 _cleanup_strv_free_erase_ char **l = NULL;
088dcd8e 382 struct pollfd pollfd[_POLL_MAX];
f3149d57 383 size_t p = 0, codepoint = 0;
088dcd8e 384 int r;
7f4e0805 385
e287086b
LP
386 assert(ret);
387
9cb5bf91 388 if (FLAGS_SET(flags, ASK_PASSWORD_NO_TTY))
e287086b
LP
389 return -EUNATCH;
390
391 if (!message)
392 message = "Password:";
7f4e0805 393
e390c34d 394 if (!FLAGS_SET(flags, ASK_PASSWORD_HIDE_EMOJI) && emoji_enabled())
52d199e3
LP
395 message = strjoina(special_glyph(SPECIAL_GLYPH_LOCK_AND_KEY), " ", message);
396
9cb5bf91 397 if (flag_file || (FLAGS_SET(flags, ASK_PASSWORD_ACCEPT_CACHED) && keyname)) {
981e4cd3 398 notify = inotify_init1(IN_CLOEXEC|IN_NONBLOCK);
a497a296
LP
399 if (notify < 0)
400 return -errno;
c7b7d74e
XF
401 }
402 if (flag_file) {
a497a296
LP
403 if (inotify_add_watch(notify, flag_file, IN_ATTRIB /* for the link count */) < 0)
404 return -errno;
7f4e0805 405 }
9cb5bf91 406 if (FLAGS_SET(flags, ASK_PASSWORD_ACCEPT_CACHED) && keyname) {
c7b7d74e
XF
407 r = ask_password_keyring(keyname, flags, ret);
408 if (r >= 0)
409 return 0;
410 else if (r != -ENOKEY)
411 return r;
412
413 if (inotify_add_watch(notify, "/run/systemd/ask-password", IN_ATTRIB /* for mtime */) < 0)
414 return -errno;
415 }
7f4e0805 416
692597c8
LP
417 CLEANUP_ERASE(passphrase);
418
daa55720
LP
419 /* If the caller didn't specify a TTY, then use the controlling tty, if we can. */
420 if (ttyfd < 0)
421 ttyfd = cttyfd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC);
7f4e0805 422
daa55720 423 if (ttyfd >= 0) {
a497a296
LP
424 if (tcgetattr(ttyfd, &old_termios) < 0)
425 return -errno;
7f4e0805 426
9cb5bf91 427 if (FLAGS_SET(flags, ASK_PASSWORD_CONSOLE_COLOR))
c2b32159
LP
428 use_color = dev_console_colors_enabled();
429 else
430 use_color = colors_enabled();
431
432 if (use_color)
e22c60a9 433 (void) loop_write(ttyfd, ANSI_HIGHLIGHT, SIZE_MAX);
ac7a9674 434
e22c60a9
MY
435 (void) loop_write(ttyfd, message, SIZE_MAX);
436 (void) loop_write(ttyfd, " ", 1);
ac7a9674 437
9cb5bf91 438 if (!FLAGS_SET(flags, ASK_PASSWORD_SILENT) && !FLAGS_SET(flags, ASK_PASSWORD_ECHO)) {
8aaf18e0 439 if (use_color)
e22c60a9
MY
440 (void) loop_write(ttyfd, ansi_grey(), SIZE_MAX);
441
442 (void) loop_write(ttyfd, PRESS_TAB, SIZE_MAX);
8aaf18e0
ZJS
443 press_tab_visible = true;
444 }
445
c2b32159 446 if (use_color)
e22c60a9 447 (void) loop_write(ttyfd, ANSI_NORMAL, SIZE_MAX);
7f4e0805
LP
448
449 new_termios = old_termios;
450 new_termios.c_lflag &= ~(ICANON|ECHO);
451 new_termios.c_cc[VMIN] = 1;
452 new_termios.c_cc[VTIME] = 0;
453
108dfff2
LP
454 r = RET_NERRNO(tcsetattr(ttyfd, TCSADRAIN, &new_termios));
455 if (r < 0)
7f4e0805 456 goto finish;
7f4e0805
LP
457
458 reset_tty = true;
459 }
460
70dee475
LP
461 pollfd[POLL_TTY] = (struct pollfd) {
462 .fd = ttyfd >= 0 ? ttyfd : STDIN_FILENO,
463 .events = POLLIN,
464 };
465 pollfd[POLL_INOTIFY] = (struct pollfd) {
466 .fd = notify,
467 .events = POLLIN,
468 };
7f4e0805
LP
469
470 for (;;) {
e1ed99c8 471 _cleanup_(erase_char) char c;
d9e2af0a 472 usec_t timeout;
7f4e0805
LP
473 ssize_t n;
474
d9e2af0a
YW
475 if (until > 0)
476 timeout = usec_sub_unsigned(until, now(CLOCK_MONOTONIC));
477 else
478 timeout = USEC_INFINITY;
7f4e0805 479
108dfff2
LP
480 if (flag_file) {
481 r = RET_NERRNO(access(flag_file, F_OK));
482 if (r < 0)
7f4e0805 483 goto finish;
108dfff2 484 }
7f4e0805 485
d9e2af0a
YW
486 r = ppoll_usec(pollfd, notify >= 0 ? 2 : 1, timeout);
487 if (r == -EINTR)
488 continue;
489 if (r < 0)
7f4e0805 490 goto finish;
d9e2af0a 491 if (r == 0) {
ccc80078 492 r = -ETIME;
7f4e0805
LP
493 goto finish;
494 }
495
1f00998c 496 if (notify >= 0 && pollfd[POLL_INOTIFY].revents != 0 && keyname) {
665dfe93 497 (void) flush_fd(notify);
7f4e0805 498
c7b7d74e
XF
499 r = ask_password_keyring(keyname, flags, ret);
500 if (r >= 0) {
501 r = 0;
502 goto finish;
503 } else if (r != -ENOKEY)
504 goto finish;
505 }
506
7f4e0805
LP
507 if (pollfd[POLL_TTY].revents == 0)
508 continue;
509
981e4cd3
LP
510 n = read(ttyfd >= 0 ? ttyfd : STDIN_FILENO, &c, 1);
511 if (n < 0) {
8add30a0 512 if (ERRNO_IS_TRANSIENT(errno))
7f4e0805
LP
513 continue;
514
515 r = -errno;
516 goto finish;
517
fd6ac62c 518 }
7f4e0805 519
8aaf18e0
ZJS
520 if (press_tab_visible) {
521 assert(ttyfd >= 0);
522 backspace_chars(ttyfd, strlen(PRESS_TAB));
523 press_tab_visible = false;
524 }
525
fd6ac62c
LP
526 /* We treat EOF, newline and NUL byte all as valid end markers */
527 if (n == 0 || c == '\n' || c == 0)
7f4e0805 528 break;
fd6ac62c 529
d325f244
FB
530 if (c == 4) { /* C-d also known as EOT */
531 if (ttyfd >= 0)
e22c60a9 532 (void) loop_write(ttyfd, SKIPPED, SIZE_MAX);
d325f244
FB
533
534 goto skipped;
535 }
536
fd6ac62c 537 if (c == 21) { /* C-u */
7f4e0805 538
9cb5bf91 539 if (!FLAGS_SET(flags, ASK_PASSWORD_SILENT))
8e9d1eec 540 (void) backspace_string(ttyfd, passphrase);
fd6ac62c 541
87f54463 542 explicit_bzero_safe(passphrase, sizeof(passphrase));
fd6ac62c 543 p = codepoint = 0;
7f4e0805 544
4c701096 545 } else if (IN_SET(c, '\b', 127)) {
58fc840b
LP
546
547 if (p > 0) {
fd6ac62c 548 size_t q;
58fc840b 549
9cb5bf91 550 if (!FLAGS_SET(flags, ASK_PASSWORD_SILENT))
8e9d1eec 551 (void) backspace_chars(ttyfd, 1);
58fc840b 552
92e068b4
ZJS
553 /* Remove a full UTF-8 codepoint from the end. For that, figure out where the
554 * last one begins */
fd6ac62c
LP
555 q = 0;
556 for (;;) {
37ca78a3 557 int z;
fd6ac62c 558
f5fbe71d 559 z = utf8_encoded_valid_unichar(passphrase + q, SIZE_MAX);
37ca78a3 560 if (z <= 0) {
f5fbe71d 561 q = SIZE_MAX; /* Invalid UTF8! */
fd6ac62c
LP
562 break;
563 }
564
565 if (q + z >= p) /* This one brings us over the edge */
566 break;
567
568 q += z;
569 }
570
f5fbe71d 571 p = codepoint = q == SIZE_MAX ? p - 1 : q;
87f54463 572 explicit_bzero_safe(passphrase + p, sizeof(passphrase) - p);
fd6ac62c 573
9cb5bf91 574 } else if (!dirty && !FLAGS_SET(flags, ASK_PASSWORD_SILENT)) {
441dfe09 575
e287086b 576 flags |= ASK_PASSWORD_SILENT;
441dfe09 577
92e068b4
ZJS
578 /* There are two ways to enter silent mode. Either by pressing backspace as
579 * first key (and only as first key), or ... */
fd6ac62c 580
441dfe09 581 if (ttyfd >= 0)
e22c60a9 582 (void) loop_write(ttyfd, NO_ECHO, SIZE_MAX);
441dfe09 583
58fc840b 584 } else if (ttyfd >= 0)
e22c60a9 585 (void) loop_write(ttyfd, "\a", 1);
7f4e0805 586
9cb5bf91 587 } else if (c == '\t' && !FLAGS_SET(flags, ASK_PASSWORD_SILENT)) {
58fc840b 588
8e9d1eec 589 (void) backspace_string(ttyfd, passphrase);
e287086b 590 flags |= ASK_PASSWORD_SILENT;
58fc840b 591
441dfe09
LP
592 /* ... or by pressing TAB at any time. */
593
58fc840b 594 if (ttyfd >= 0)
e22c60a9 595 (void) loop_write(ttyfd, NO_ECHO, SIZE_MAX);
036eeac5 596
fd6ac62c
LP
597 } else if (p >= sizeof(passphrase)-1) {
598
599 /* Reached the size limit */
600 if (ttyfd >= 0)
e22c60a9 601 (void) loop_write(ttyfd, "\a", 1);
fd6ac62c
LP
602
603 } else {
7f4e0805
LP
604 passphrase[p++] = c;
605
9cb5bf91 606 if (!FLAGS_SET(flags, ASK_PASSWORD_SILENT) && ttyfd >= 0) {
fd6ac62c 607 /* Check if we got a complete UTF-8 character now. If so, let's output one '*'. */
f5fbe71d 608 n = utf8_encoded_valid_unichar(passphrase + codepoint, SIZE_MAX);
f3149d57 609 if (n >= 0) {
9cb5bf91 610 if (FLAGS_SET(flags, ASK_PASSWORD_ECHO))
e22c60a9 611 (void) loop_write(ttyfd, passphrase + codepoint, n);
d26eef92 612 else
e22c60a9
MY
613 (void) loop_write(ttyfd,
614 special_glyph(SPECIAL_GLYPH_BULLET),
615 SIZE_MAX);
f3149d57 616 codepoint = p;
f3149d57
ZJS
617 }
618 }
441dfe09
LP
619
620 dirty = true;
7f4e0805
LP
621 }
622 }
623
981e4cd3
LP
624 x = strndup(passphrase, p);
625 if (!x) {
7f4e0805
LP
626 r = -ENOMEM;
627 goto finish;
628 }
629
0e28c86f
LP
630 r = strv_consume(&l, x);
631 if (r < 0)
c7b7d74e 632 goto finish;
c7b7d74e 633
d325f244 634skipped:
72c08a47
ZJS
635 if (strv_isempty(l))
636 r = log_debug_errno(SYNTHETIC_ERRNO(ECANCELED), "Password query was cancelled.");
637 else {
638 if (keyname)
639 (void) add_to_keyring_and_log(keyname, flags, l);
640
641 *ret = TAKE_PTR(l);
642 r = 0;
643 }
7f4e0805
LP
644
645finish:
981e4cd3 646 if (ttyfd >= 0 && reset_tty) {
e22c60a9 647 (void) loop_write(ttyfd, "\n", 1);
ac7a9674 648 (void) tcsetattr(ttyfd, TCSADRAIN, &old_termios);
7f4e0805
LP
649 }
650
651 return r;
652}
653
15a3e96f
LP
654static int create_socket(char **ret) {
655 _cleanup_free_ char *path = NULL;
f36a9d59
ZJS
656 union sockaddr_union sa;
657 socklen_t sa_len;
254d1313 658 _cleanup_close_ int fd = -EBADF;
f36a9d59 659 int r;
7f4e0805 660
15a3e96f 661 assert(ret);
7f4e0805 662
e62d8c39 663 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
4a62c710 664 if (fd < 0)
00843602 665 return -errno;
7f4e0805 666
15a3e96f
LP
667 if (asprintf(&path, "/run/systemd/ask-password/sck.%" PRIx64, random_u64()) < 0)
668 return -ENOMEM;
669
f36a9d59
ZJS
670 r = sockaddr_un_set_path(&sa.un, path);
671 if (r < 0)
672 return r;
673 sa_len = r;
7f4e0805 674
2053593f 675 WITH_UMASK(0177)
f36a9d59 676 if (bind(fd, &sa.sa, sa_len) < 0)
00843602 677 return -errno;
1d6702e8 678
2ff48e98
LP
679 r = setsockopt_int(fd, SOL_SOCKET, SO_PASSCRED, true);
680 if (r < 0)
681 return r;
7f4e0805 682
15a3e96f
LP
683 *ret = TAKE_PTR(path);
684 return TAKE_FD(fd);
7f4e0805
LP
685}
686
7f4e0805
LP
687int ask_password_agent(
688 const char *message,
689 const char *icon,
9fa1de96 690 const char *id,
e287086b 691 const char *keyname,
7f4e0805 692 usec_t until,
e287086b
LP
693 AskPasswordFlags flags,
694 char ***ret) {
7f4e0805
LP
695
696 enum {
697 FD_SOCKET,
698 FD_SIGNAL,
c7b7d74e 699 FD_INOTIFY,
7f4e0805
LP
700 _FD_MAX
701 };
702
254d1313 703 _cleanup_close_ int socket_fd = -EBADF, signal_fd = -EBADF, notify = -EBADF, fd = -EBADF;
2b583ce6 704 char temp[] = "/run/systemd/ask-password/tmp.XXXXXX";
7f4e0805 705 char final[sizeof(temp)] = "";
981e4cd3 706 _cleanup_free_ char *socket_name = NULL;
c7b7d74e 707 _cleanup_strv_free_erase_ char **l = NULL;
e287086b 708 _cleanup_fclose_ FILE *f = NULL;
7f4e0805 709 struct pollfd pollfd[_FD_MAX];
e287086b 710 sigset_t mask, oldmask;
981e4cd3 711 int r;
7f4e0805 712
e287086b 713 assert(ret);
21bc923a 714
9cb5bf91 715 if (FLAGS_SET(flags, ASK_PASSWORD_NO_AGENT))
e287086b 716 return -EUNATCH;
00843602 717
72c0a2c2
LP
718 assert_se(sigemptyset(&mask) >= 0);
719 assert_se(sigset_add_many(&mask, SIGINT, SIGTERM, -1) >= 0);
720 assert_se(sigprocmask(SIG_BLOCK, &mask, &oldmask) >= 0);
f9b72cd8 721
00843602 722 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
7f4e0805 723
9cb5bf91 724 if (FLAGS_SET(flags, ASK_PASSWORD_ACCEPT_CACHED) && keyname) {
c7b7d74e
XF
725 r = ask_password_keyring(keyname, flags, ret);
726 if (r >= 0) {
727 r = 0;
728 goto finish;
729 } else if (r != -ENOKEY)
730 goto finish;
731
732 notify = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
733 if (notify < 0) {
734 r = -errno;
735 goto finish;
736 }
108dfff2
LP
737
738 r = RET_NERRNO(inotify_add_watch(notify, "/run/systemd/ask-password", IN_ATTRIB /* for mtime */));
739 if (r < 0)
c7b7d74e 740 goto finish;
c7b7d74e
XF
741 }
742
646853bd 743 fd = mkostemp_safe(temp);
1d6702e8 744 if (fd < 0) {
709f6e46 745 r = fd;
7f4e0805
LP
746 goto finish;
747 }
748
00843602 749 (void) fchmod(fd, 0644);
7f4e0805 750
4fa744a3 751 f = take_fdopen(&fd, "w");
981e4cd3 752 if (!f) {
00843602 753 r = -errno;
7f4e0805
LP
754 goto finish;
755 }
756
981e4cd3
LP
757 signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
758 if (signal_fd < 0) {
00843602 759 r = -errno;
7f4e0805
LP
760 goto finish;
761 }
762
981e4cd3
LP
763 socket_fd = create_socket(&socket_name);
764 if (socket_fd < 0) {
7f4e0805
LP
765 r = socket_fd;
766 goto finish;
767 }
768
769 fprintf(f,
770 "[Ask]\n"
de0671ee 771 "PID="PID_FMT"\n"
7f4e0805 772 "Socket=%s\n"
21bc923a 773 "AcceptCached=%i\n"
64845bdc 774 "Echo=%i\n"
1fa94a31
SB
775 "NotAfter="USEC_FMT"\n"
776 "Silent=%i\n",
df0ff127 777 getpid_cached(),
7f4e0805 778 socket_name,
9cb5bf91
CH
779 FLAGS_SET(flags, ASK_PASSWORD_ACCEPT_CACHED),
780 FLAGS_SET(flags, ASK_PASSWORD_ECHO),
1fa94a31 781 until,
9cb5bf91 782 FLAGS_SET(flags, ASK_PASSWORD_SILENT));
7f4e0805
LP
783
784 if (message)
785 fprintf(f, "Message=%s\n", message);
786
787 if (icon)
788 fprintf(f, "Icon=%s\n", icon);
789
9fa1de96
DH
790 if (id)
791 fprintf(f, "Id=%s\n", id);
792
dacd6cee 793 r = fflush_and_check(f);
00843602 794 if (r < 0)
7f4e0805 795 goto finish;
7f4e0805
LP
796
797 memcpy(final, temp, sizeof(temp));
798
799 final[sizeof(final)-11] = 'a';
800 final[sizeof(final)-10] = 's';
801 final[sizeof(final)-9] = 'k';
802
108dfff2
LP
803 r = RET_NERRNO(rename(temp, final));
804 if (r < 0)
7f4e0805 805 goto finish;
7f4e0805
LP
806
807 zero(pollfd);
808 pollfd[FD_SOCKET].fd = socket_fd;
809 pollfd[FD_SOCKET].events = POLLIN;
810 pollfd[FD_SIGNAL].fd = signal_fd;
811 pollfd[FD_SIGNAL].events = POLLIN;
c7b7d74e
XF
812 pollfd[FD_INOTIFY].fd = notify;
813 pollfd[FD_INOTIFY].events = POLLIN;
7f4e0805
LP
814
815 for (;;) {
fb29cdbe 816 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred))) control;
7f4e0805 817 char passphrase[LINE_MAX+1];
7f4e0805
LP
818 struct iovec iovec;
819 struct ucred *ucred;
d9e2af0a 820 usec_t timeout;
7f4e0805 821 ssize_t n;
7f4e0805 822
d9e2af0a
YW
823 if (until > 0)
824 timeout = usec_sub_unsigned(until, now(CLOCK_MONOTONIC));
825 else
826 timeout = USEC_INFINITY;
7f4e0805 827
d9e2af0a
YW
828 r = ppoll_usec(pollfd, notify >= 0 ? _FD_MAX : _FD_MAX - 1, timeout);
829 if (r == -EINTR)
830 continue;
831 if (r < 0)
7f4e0805 832 goto finish;
d9e2af0a 833 if (r == 0) {
7f4e0805
LP
834 r = -ETIME;
835 goto finish;
836 }
837
21bc923a
LP
838 if (pollfd[FD_SIGNAL].revents & POLLIN) {
839 r = -EINTR;
840 goto finish;
841 }
7f4e0805 842
c7b7d74e
XF
843 if (notify >= 0 && pollfd[FD_INOTIFY].revents != 0) {
844 (void) flush_fd(notify);
845
846 r = ask_password_keyring(keyname, flags, ret);
847 if (r >= 0) {
848 r = 0;
849 goto finish;
850 } else if (r != -ENOKEY)
851 goto finish;
852 }
853
854 if (pollfd[FD_SOCKET].revents == 0)
855 continue;
856
7f4e0805 857 if (pollfd[FD_SOCKET].revents != POLLIN) {
7f4e0805
LP
858 r = -EIO;
859 goto finish;
860 }
861
5cfa2c3d 862 iovec = IOVEC_MAKE(passphrase, sizeof(passphrase));
7f4e0805 863
41ab8c67
LP
864 struct msghdr msghdr = {
865 .msg_iov = &iovec,
866 .msg_iovlen = 1,
867 .msg_control = &control,
868 .msg_controllen = sizeof(control),
869 };
7f4e0805 870
3691bcf3 871 n = recvmsg_safe(socket_fd, &msghdr, 0);
bb44fd07
ZJS
872 if (ERRNO_IS_NEG_TRANSIENT(n))
873 continue;
874 else if (n == -EXFULL) {
875 log_debug("Got message with truncated control data, ignoring.");
876 continue;
877 } else if (n < 0) {
3691bcf3 878 r = (int) n;
7f4e0805
LP
879 goto finish;
880 }
881
692597c8
LP
882 CLEANUP_ERASE(passphrase);
883
1c8da044
LP
884 cmsg_close_all(&msghdr);
885
8add30a0 886 if (n == 0) {
00843602 887 log_debug("Message too short");
7f4e0805
LP
888 continue;
889 }
890
371d72e0
LP
891 ucred = CMSG_FIND_DATA(&msghdr, SOL_SOCKET, SCM_CREDENTIALS, struct ucred);
892 if (!ucred) {
00843602 893 log_debug("Received message without credentials. Ignoring.");
7f4e0805
LP
894 continue;
895 }
896
7f4e0805 897 if (ucred->uid != 0) {
00843602 898 log_debug("Got request from unprivileged user. Ignoring.");
7f4e0805
LP
899 continue;
900 }
901
902 if (passphrase[0] == '+') {
e287086b 903 /* An empty message refers to the empty password */
8254a475 904 if (n == 1)
bea1a013 905 l = strv_new("");
8254a475
LP
906 else
907 l = strv_parse_nulstr(passphrase+1, n-1);
8254a475 908 if (!l) {
7f4e0805
LP
909 r = -ENOMEM;
910 goto finish;
911 }
912
58629001 913 if (strv_isempty(l)) {
e287086b 914 l = strv_free(l);
00843602 915 log_debug("Invalid packet");
21bc923a
LP
916 continue;
917 }
918
e287086b
LP
919 break;
920 }
21bc923a 921
e287086b 922 if (passphrase[0] == '-') {
7f4e0805
LP
923 r = -ECANCELED;
924 goto finish;
7f4e0805
LP
925 }
926
e287086b 927 log_debug("Invalid packet");
7f4e0805
LP
928 }
929
e287086b
LP
930 if (keyname)
931 (void) add_to_keyring_and_log(keyname, flags, l);
932
ae2a15bc 933 *ret = TAKE_PTR(l);
7f4e0805
LP
934 r = 0;
935
936finish:
981e4cd3 937 if (socket_name)
00843602 938 (void) unlink(socket_name);
7f4e0805 939
00843602 940 (void) unlink(temp);
7f4e0805
LP
941
942 if (final[0])
00843602 943 (void) unlink(final);
7f4e0805 944
f9b72cd8 945 assert_se(sigprocmask(SIG_SETMASK, &oldmask, NULL) == 0);
7f4e0805
LP
946 return r;
947}
260ab287 948
8806bb4b
LP
949static int ask_password_credential(const char *credential_name, AskPasswordFlags flags, char ***ret) {
950 _cleanup_(erase_and_freep) char *buffer = NULL;
951 size_t size;
952 char **l;
953 int r;
954
955 assert(credential_name);
956 assert(ret);
957
958 r = read_credential(credential_name, (void**) &buffer, &size);
959 if (IN_SET(r, -ENXIO, -ENOENT)) /* No credentials passed or this credential not defined? */
960 return -ENOKEY;
961
962 l = strv_parse_nulstr(buffer, size);
963 if (!l)
964 return -ENOMEM;
965
966 *ret = l;
967 return 0;
968}
969
00843602
LP
970int ask_password_auto(
971 const char *message,
972 const char *icon,
8806bb4b
LP
973 const char *id, /* id in "ask-password" protocol */
974 const char *key_name, /* name in kernel keyring */
975 const char *credential_name, /* name in $CREDENTIALS_DIRECTORY directory */
00843602 976 usec_t until,
e287086b
LP
977 AskPasswordFlags flags,
978 char ***ret) {
00843602
LP
979
980 int r;
981
e287086b 982 assert(ret);
21bc923a 983
9cb5bf91 984 if (!FLAGS_SET(flags, ASK_PASSWORD_NO_CREDENTIAL) && credential_name) {
8806bb4b
LP
985 r = ask_password_credential(credential_name, flags, ret);
986 if (r != -ENOKEY)
987 return r;
988 }
989
9cb5bf91 990 if (FLAGS_SET(flags, ASK_PASSWORD_ACCEPT_CACHED) &&
8806bb4b 991 key_name &&
9cb5bf91
CH
992 (FLAGS_SET(flags, ASK_PASSWORD_NO_TTY) || !isatty(STDIN_FILENO)) &&
993 FLAGS_SET(flags, ASK_PASSWORD_NO_AGENT)) {
8806bb4b 994 r = ask_password_keyring(key_name, flags, ret);
e287086b
LP
995 if (r != -ENOKEY)
996 return r;
997 }
998
9cb5bf91 999 if (!FLAGS_SET(flags, ASK_PASSWORD_NO_TTY) && isatty(STDIN_FILENO))
8806bb4b 1000 return ask_password_tty(-1, message, key_name, until, flags, NULL, ret);
00843602 1001
9cb5bf91 1002 if (!FLAGS_SET(flags, ASK_PASSWORD_NO_AGENT))
8806bb4b 1003 return ask_password_agent(message, icon, id, key_name, until, flags, ret);
e287086b
LP
1004
1005 return -EUNATCH;
260ab287 1006}