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