]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/ask-password-api.c
ask-password: prevent buffer overrow when reading from keyring
[thirdparty/systemd.git] / src / shared / ask-password-api.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
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 <poll.h>
a8fbdf54 8#include <signal.h>
00843602 9#include <stdbool.h>
7f4e0805 10#include <stddef.h>
a8fbdf54
TA
11#include <stdint.h>
12#include <stdio.h>
13#include <stdlib.h>
00843602
LP
14#include <string.h>
15#include <sys/inotify.h>
7f4e0805 16#include <sys/signalfd.h>
00843602 17#include <sys/socket.h>
a8fbdf54
TA
18#include <sys/stat.h>
19#include <sys/time.h>
20#include <sys/uio.h>
00843602
LP
21#include <sys/un.h>
22#include <termios.h>
23#include <unistd.h>
7f4e0805 24
b5efdb8a 25#include "alloc-util.h"
3ffd4af2
LP
26#include "ask-password-api.h"
27#include "fd-util.h"
0d39fa9c 28#include "fileio.h"
f97b34a6 29#include "format-util.h"
c7b7d74e 30#include "fs-util.h"
c004493c 31#include "io-util.h"
a8fbdf54
TA
32#include "log.h"
33#include "macro.h"
0a970718 34#include "memory-util.h"
e287086b 35#include "missing.h"
49e942b2 36#include "mkdir.h"
df0ff127 37#include "process-util.h"
3df3e884 38#include "random-util.h"
24882e06 39#include "signal-util.h"
00843602 40#include "socket-util.h"
07630cea 41#include "string-util.h"
00843602
LP
42#include "strv.h"
43#include "terminal-util.h"
a8fbdf54 44#include "time-util.h"
e4de7287 45#include "tmpfile-util.h"
affb60b1 46#include "umask-util.h"
f3149d57 47#include "utf8.h"
7f4e0805 48
e287086b
LP
49#define KEYRING_TIMEOUT_USEC ((5 * USEC_PER_MINUTE) / 2)
50
51static int lookup_key(const char *keyname, key_serial_t *ret) {
52 key_serial_t serial;
53
54 assert(keyname);
55 assert(ret);
56
57 serial = request_key("user", keyname, NULL, 0);
58 if (serial == -1)
9c4615fb 59 return negative_errno();
e287086b
LP
60
61 *ret = serial;
62 return 0;
63}
64
65static int retrieve_key(key_serial_t serial, char ***ret) {
66 _cleanup_free_ char *p = NULL;
67 long m = 100, n;
68 char **l;
69
70 assert(ret);
71
72 for (;;) {
73 p = new(char, m);
74 if (!p)
75 return -ENOMEM;
76
77 n = keyctl(KEYCTL_READ, (unsigned long) serial, (unsigned long) p, (unsigned long) m, 0);
78 if (n < 0)
79 return -errno;
e287086b
LP
80 if (n < m)
81 break;
82
59c55e73 83 explicit_bzero_safe(p, m);
054b6be0
LP
84
85 if (m > LONG_MAX / 2) /* overflow check */
86 return -ENOMEM;
e287086b 87 m *= 2;
054b6be0
LP
88 if ((long) (size_t) m != m) /* make sure that this still fits if converted to size_t */
89 return -ENOMEM;
90
91 free(p);
e287086b
LP
92 }
93
94 l = strv_parse_nulstr(p, n);
95 if (!l)
96 return -ENOMEM;
97
87f54463 98 explicit_bzero_safe(p, n);
1602b008 99
e287086b
LP
100 *ret = l;
101 return 0;
102}
103
104static int add_to_keyring(const char *keyname, AskPasswordFlags flags, char **passwords) {
ab84f5b9 105 _cleanup_strv_free_erase_ char **l = NULL;
e287086b
LP
106 _cleanup_free_ char *p = NULL;
107 key_serial_t serial;
108 size_t n;
109 int r;
110
111 assert(keyname);
112 assert(passwords);
113
114 if (!(flags & ASK_PASSWORD_PUSH_CACHE))
115 return 0;
116
117 r = lookup_key(keyname, &serial);
118 if (r >= 0) {
119 r = retrieve_key(serial, &l);
120 if (r < 0)
121 return r;
122 } else if (r != -ENOKEY)
123 return r;
124
125 r = strv_extend_strv(&l, passwords, true);
126 if (r <= 0)
127 return r;
128
129 r = strv_make_nulstr(l, &p, &n);
130 if (r < 0)
131 return r;
132
b60df13b 133 serial = add_key("user", keyname, p, n, KEY_SPEC_USER_KEYRING);
87f54463 134 explicit_bzero_safe(p, n);
e287086b
LP
135 if (serial == -1)
136 return -errno;
137
138 if (keyctl(KEYCTL_SET_TIMEOUT,
139 (unsigned long) serial,
140 (unsigned long) DIV_ROUND_UP(KEYRING_TIMEOUT_USEC, USEC_PER_SEC), 0, 0) < 0)
141 log_debug_errno(errno, "Failed to adjust timeout: %m");
142
c7b7d74e
XF
143 /* Tell everyone to check the keyring */
144 (void) touch("/run/systemd/ask-password");
145
e287086b
LP
146 log_debug("Added key to keyring as %" PRIi32 ".", serial);
147
148 return 1;
149}
150
151static int add_to_keyring_and_log(const char *keyname, AskPasswordFlags flags, char **passwords) {
152 int r;
153
154 assert(keyname);
155 assert(passwords);
156
157 r = add_to_keyring(keyname, flags, passwords);
158 if (r < 0)
159 return log_debug_errno(r, "Failed to add password to keyring: %m");
160
161 return 0;
162}
163
8a111277 164static int ask_password_keyring(const char *keyname, AskPasswordFlags flags, char ***ret) {
e287086b
LP
165
166 key_serial_t serial;
167 int r;
168
169 assert(keyname);
170 assert(ret);
171
172 if (!(flags & ASK_PASSWORD_ACCEPT_CACHED))
173 return -EUNATCH;
174
175 r = lookup_key(keyname, &serial);
176 if (r == -ENOSYS) /* when retrieving the distinction doesn't matter */
177 return -ENOKEY;
178 if (r < 0)
179 return r;
180
181 return retrieve_key(serial, ret);
182}
183
58fc840b
LP
184static void backspace_chars(int ttyfd, size_t p) {
185
186 if (ttyfd < 0)
187 return;
188
189 while (p > 0) {
190 p--;
191
192 loop_write(ttyfd, "\b \b", 3, false);
193 }
194}
195
fd6ac62c
LP
196static void backspace_string(int ttyfd, const char *str) {
197 size_t m;
198
199 assert(str);
200
201 if (ttyfd < 0)
202 return;
203
f95dbcc2 204 /* Backspaces through enough characters to entirely undo printing of the specified string. */
fd6ac62c
LP
205
206 m = utf8_n_codepoints(str);
207 if (m == (size_t) -1)
208 m = strlen(str); /* Not a valid UTF-8 string? If so, let's backspace the number of bytes output. Most
209 * likely this happened because we are not in an UTF-8 locale, and in that case that
210 * is the correct thing to do. And even if it's not, terminals tend to stop
211 * backspacing at the leftmost column, hence backspacing too much should be mostly
212 * OK. */
213
214 backspace_chars(ttyfd, m);
215}
216
7f4e0805 217int ask_password_tty(
daa55720 218 int ttyfd,
7f4e0805 219 const char *message,
e287086b 220 const char *keyname,
7f4e0805 221 usec_t until,
e287086b 222 AskPasswordFlags flags,
7f4e0805 223 const char *flag_file,
c7b7d74e 224 char ***ret) {
7f4e0805 225
088dcd8e
LP
226 enum {
227 POLL_TTY,
228 POLL_INOTIFY,
229 _POLL_MAX,
230 };
231
c2b32159 232 bool reset_tty = false, dirty = false, use_color = false;
daa55720 233 _cleanup_close_ int cttyfd = -1, notify = -1;
7f4e0805 234 struct termios old_termios, new_termios;
f3149d57 235 char passphrase[LINE_MAX + 1] = {}, *x;
c7b7d74e 236 _cleanup_strv_free_erase_ char **l = NULL;
088dcd8e 237 struct pollfd pollfd[_POLL_MAX];
f3149d57 238 size_t p = 0, codepoint = 0;
088dcd8e 239 int r;
7f4e0805 240
e287086b
LP
241 assert(ret);
242
243 if (flags & ASK_PASSWORD_NO_TTY)
244 return -EUNATCH;
245
246 if (!message)
247 message = "Password:";
7f4e0805 248
c7b7d74e 249 if (flag_file || ((flags & ASK_PASSWORD_ACCEPT_CACHED) && keyname)) {
981e4cd3 250 notify = inotify_init1(IN_CLOEXEC|IN_NONBLOCK);
a497a296
LP
251 if (notify < 0)
252 return -errno;
c7b7d74e
XF
253 }
254 if (flag_file) {
a497a296
LP
255 if (inotify_add_watch(notify, flag_file, IN_ATTRIB /* for the link count */) < 0)
256 return -errno;
7f4e0805 257 }
c7b7d74e
XF
258 if ((flags & ASK_PASSWORD_ACCEPT_CACHED) && keyname) {
259 r = ask_password_keyring(keyname, flags, ret);
260 if (r >= 0)
261 return 0;
262 else if (r != -ENOKEY)
263 return r;
264
265 if (inotify_add_watch(notify, "/run/systemd/ask-password", IN_ATTRIB /* for mtime */) < 0)
266 return -errno;
267 }
7f4e0805 268
daa55720
LP
269 /* If the caller didn't specify a TTY, then use the controlling tty, if we can. */
270 if (ttyfd < 0)
271 ttyfd = cttyfd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC);
7f4e0805 272
daa55720 273 if (ttyfd >= 0) {
a497a296
LP
274 if (tcgetattr(ttyfd, &old_termios) < 0)
275 return -errno;
7f4e0805 276
c2b32159
LP
277 if (flags & ASK_PASSWORD_CONSOLE_COLOR)
278 use_color = dev_console_colors_enabled();
279 else
280 use_color = colors_enabled();
281
282 if (use_color)
ac7a9674
LP
283 (void) loop_write(ttyfd, ANSI_HIGHLIGHT, STRLEN(ANSI_HIGHLIGHT), false);
284
285 (void) loop_write(ttyfd, message, strlen(message), false);
286 (void) loop_write(ttyfd, " ", 1, false);
287
c2b32159 288 if (use_color)
ac7a9674 289 (void) loop_write(ttyfd, ANSI_NORMAL, STRLEN(ANSI_NORMAL), false);
7f4e0805
LP
290
291 new_termios = old_termios;
292 new_termios.c_lflag &= ~(ICANON|ECHO);
293 new_termios.c_cc[VMIN] = 1;
294 new_termios.c_cc[VTIME] = 0;
295
296 if (tcsetattr(ttyfd, TCSADRAIN, &new_termios) < 0) {
297 r = -errno;
298 goto finish;
299 }
300
301 reset_tty = true;
302 }
303
70dee475
LP
304 pollfd[POLL_TTY] = (struct pollfd) {
305 .fd = ttyfd >= 0 ? ttyfd : STDIN_FILENO,
306 .events = POLLIN,
307 };
308 pollfd[POLL_INOTIFY] = (struct pollfd) {
309 .fd = notify,
310 .events = POLLIN,
311 };
7f4e0805
LP
312
313 for (;;) {
e1ed99c8 314 _cleanup_(erase_char) char c;
7f4e0805
LP
315 int sleep_for = -1, k;
316 ssize_t n;
317
318 if (until > 0) {
319 usec_t y;
320
321 y = now(CLOCK_MONOTONIC);
322
323 if (y > until) {
7ded2e28 324 r = -ETIME;
7f4e0805
LP
325 goto finish;
326 }
327
c9eb4a00 328 sleep_for = (int) DIV_ROUND_UP(until - y, USEC_PER_MSEC);
7f4e0805
LP
329 }
330
331 if (flag_file)
332 if (access(flag_file, F_OK) < 0) {
333 r = -errno;
334 goto finish;
335 }
336
e287086b 337 k = poll(pollfd, notify >= 0 ? 2 : 1, sleep_for);
981e4cd3 338 if (k < 0) {
7f4e0805
LP
339 if (errno == EINTR)
340 continue;
341
342 r = -errno;
343 goto finish;
344 } else if (k == 0) {
ccc80078 345 r = -ETIME;
7f4e0805
LP
346 goto finish;
347 }
348
1f00998c 349 if (notify >= 0 && pollfd[POLL_INOTIFY].revents != 0 && keyname) {
665dfe93 350 (void) flush_fd(notify);
7f4e0805 351
c7b7d74e
XF
352 r = ask_password_keyring(keyname, flags, ret);
353 if (r >= 0) {
354 r = 0;
355 goto finish;
356 } else if (r != -ENOKEY)
357 goto finish;
358 }
359
7f4e0805
LP
360 if (pollfd[POLL_TTY].revents == 0)
361 continue;
362
981e4cd3
LP
363 n = read(ttyfd >= 0 ? ttyfd : STDIN_FILENO, &c, 1);
364 if (n < 0) {
3742095b 365 if (IN_SET(errno, EINTR, EAGAIN))
7f4e0805
LP
366 continue;
367
368 r = -errno;
369 goto finish;
370
fd6ac62c 371 }
7f4e0805 372
fd6ac62c
LP
373 /* We treat EOF, newline and NUL byte all as valid end markers */
374 if (n == 0 || c == '\n' || c == 0)
7f4e0805 375 break;
fd6ac62c
LP
376
377 if (c == 21) { /* C-u */
7f4e0805 378
e287086b 379 if (!(flags & ASK_PASSWORD_SILENT))
fd6ac62c
LP
380 backspace_string(ttyfd, passphrase);
381
87f54463 382 explicit_bzero_safe(passphrase, sizeof(passphrase));
fd6ac62c 383 p = codepoint = 0;
7f4e0805 384
4c701096 385 } else if (IN_SET(c, '\b', 127)) {
58fc840b
LP
386
387 if (p > 0) {
fd6ac62c 388 size_t q;
58fc840b 389
e287086b 390 if (!(flags & ASK_PASSWORD_SILENT))
58fc840b
LP
391 backspace_chars(ttyfd, 1);
392
92e068b4
ZJS
393 /* Remove a full UTF-8 codepoint from the end. For that, figure out where the
394 * last one begins */
fd6ac62c
LP
395 q = 0;
396 for (;;) {
397 size_t z;
398
92e068b4 399 z = utf8_encoded_valid_unichar(passphrase + q, (size_t) -1);
fd6ac62c
LP
400 if (z == 0) {
401 q = (size_t) -1; /* Invalid UTF8! */
402 break;
403 }
404
405 if (q + z >= p) /* This one brings us over the edge */
406 break;
407
408 q += z;
409 }
410
411 p = codepoint = q == (size_t) -1 ? p - 1 : q;
87f54463 412 explicit_bzero_safe(passphrase + p, sizeof(passphrase) - p);
fd6ac62c 413
e287086b 414 } else if (!dirty && !(flags & ASK_PASSWORD_SILENT)) {
441dfe09 415
e287086b 416 flags |= ASK_PASSWORD_SILENT;
441dfe09 417
92e068b4
ZJS
418 /* There are two ways to enter silent mode. Either by pressing backspace as
419 * first key (and only as first key), or ... */
fd6ac62c 420
441dfe09 421 if (ttyfd >= 0)
ac7a9674 422 (void) loop_write(ttyfd, "(no echo) ", 10, false);
441dfe09 423
58fc840b 424 } else if (ttyfd >= 0)
ac7a9674 425 (void) loop_write(ttyfd, "\a", 1, false);
7f4e0805 426
e287086b 427 } else if (c == '\t' && !(flags & ASK_PASSWORD_SILENT)) {
58fc840b 428
fd6ac62c 429 backspace_string(ttyfd, passphrase);
e287086b 430 flags |= ASK_PASSWORD_SILENT;
58fc840b 431
441dfe09
LP
432 /* ... or by pressing TAB at any time. */
433
58fc840b 434 if (ttyfd >= 0)
ac7a9674 435 (void) loop_write(ttyfd, "(no echo) ", 10, false);
036eeac5 436
fd6ac62c
LP
437 } else if (p >= sizeof(passphrase)-1) {
438
439 /* Reached the size limit */
440 if (ttyfd >= 0)
441 (void) loop_write(ttyfd, "\a", 1, false);
442
443 } else {
7f4e0805
LP
444 passphrase[p++] = c;
445
f3149d57 446 if (!(flags & ASK_PASSWORD_SILENT) && ttyfd >= 0) {
fd6ac62c 447 /* Check if we got a complete UTF-8 character now. If so, let's output one '*'. */
92e068b4 448 n = utf8_encoded_valid_unichar(passphrase + codepoint, (size_t) -1);
f3149d57 449 if (n >= 0) {
d26eef92
ZJS
450 if (flags & ASK_PASSWORD_ECHO)
451 (void) loop_write(ttyfd, passphrase + codepoint, n, false);
452 else
453 (void) loop_write(ttyfd, "*", 1, false);
f3149d57 454 codepoint = p;
f3149d57
ZJS
455 }
456 }
441dfe09
LP
457
458 dirty = true;
7f4e0805
LP
459 }
460 }
461
981e4cd3 462 x = strndup(passphrase, p);
87f54463 463 explicit_bzero_safe(passphrase, sizeof(passphrase));
981e4cd3 464 if (!x) {
7f4e0805
LP
465 r = -ENOMEM;
466 goto finish;
467 }
468
0e28c86f
LP
469 r = strv_consume(&l, x);
470 if (r < 0)
c7b7d74e 471 goto finish;
c7b7d74e 472
e287086b 473 if (keyname)
c7b7d74e 474 (void) add_to_keyring_and_log(keyname, flags, l);
e287086b 475
c7b7d74e 476 *ret = TAKE_PTR(l);
7f4e0805
LP
477 r = 0;
478
479finish:
981e4cd3 480 if (ttyfd >= 0 && reset_tty) {
ac7a9674
LP
481 (void) loop_write(ttyfd, "\n", 1, false);
482 (void) tcsetattr(ttyfd, TCSADRAIN, &old_termios);
7f4e0805
LP
483 }
484
485 return r;
486}
487
15a3e96f
LP
488static int create_socket(char **ret) {
489 _cleanup_free_ char *path = NULL;
490 union sockaddr_union sa = {};
00843602 491 _cleanup_close_ int fd = -1;
2ff48e98 492 int salen, r;
7f4e0805 493
15a3e96f 494 assert(ret);
7f4e0805 495
e62d8c39 496 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
4a62c710 497 if (fd < 0)
00843602 498 return -errno;
7f4e0805 499
15a3e96f
LP
500 if (asprintf(&path, "/run/systemd/ask-password/sck.%" PRIx64, random_u64()) < 0)
501 return -ENOMEM;
502
503 salen = sockaddr_un_set_path(&sa.un, path);
504 if (salen < 0)
505 return salen;
7f4e0805 506
5c0d398d 507 RUN_WITH_UMASK(0177) {
15a3e96f 508 if (bind(fd, &sa.sa, salen) < 0)
00843602 509 return -errno;
5c0d398d 510 }
1d6702e8 511
2ff48e98
LP
512 r = setsockopt_int(fd, SOL_SOCKET, SO_PASSCRED, true);
513 if (r < 0)
514 return r;
7f4e0805 515
15a3e96f
LP
516 *ret = TAKE_PTR(path);
517 return TAKE_FD(fd);
7f4e0805
LP
518}
519
7f4e0805
LP
520int ask_password_agent(
521 const char *message,
522 const char *icon,
9fa1de96 523 const char *id,
e287086b 524 const char *keyname,
7f4e0805 525 usec_t until,
e287086b
LP
526 AskPasswordFlags flags,
527 char ***ret) {
7f4e0805
LP
528
529 enum {
530 FD_SOCKET,
531 FD_SIGNAL,
c7b7d74e 532 FD_INOTIFY,
7f4e0805
LP
533 _FD_MAX
534 };
535
c7b7d74e 536 _cleanup_close_ int socket_fd = -1, signal_fd = -1, notify = -1, fd = -1;
2b583ce6 537 char temp[] = "/run/systemd/ask-password/tmp.XXXXXX";
7f4e0805 538 char final[sizeof(temp)] = "";
981e4cd3 539 _cleanup_free_ char *socket_name = NULL;
c7b7d74e 540 _cleanup_strv_free_erase_ char **l = NULL;
e287086b 541 _cleanup_fclose_ FILE *f = NULL;
7f4e0805 542 struct pollfd pollfd[_FD_MAX];
e287086b 543 sigset_t mask, oldmask;
981e4cd3 544 int r;
7f4e0805 545
e287086b 546 assert(ret);
21bc923a 547
e287086b
LP
548 if (flags & ASK_PASSWORD_NO_AGENT)
549 return -EUNATCH;
00843602 550
72c0a2c2
LP
551 assert_se(sigemptyset(&mask) >= 0);
552 assert_se(sigset_add_many(&mask, SIGINT, SIGTERM, -1) >= 0);
553 assert_se(sigprocmask(SIG_BLOCK, &mask, &oldmask) >= 0);
f9b72cd8 554
00843602 555 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
7f4e0805 556
c7b7d74e
XF
557 if ((flags & ASK_PASSWORD_ACCEPT_CACHED) && keyname) {
558 r = ask_password_keyring(keyname, flags, ret);
559 if (r >= 0) {
560 r = 0;
561 goto finish;
562 } else if (r != -ENOKEY)
563 goto finish;
564
565 notify = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
566 if (notify < 0) {
567 r = -errno;
568 goto finish;
569 }
570 if (inotify_add_watch(notify, "/run/systemd/ask-password", IN_ATTRIB /* for mtime */) < 0) {
571 r = -errno;
572 goto finish;
573 }
574 }
575
646853bd 576 fd = mkostemp_safe(temp);
1d6702e8 577 if (fd < 0) {
709f6e46 578 r = fd;
7f4e0805
LP
579 goto finish;
580 }
581
00843602 582 (void) fchmod(fd, 0644);
7f4e0805 583
981e4cd3
LP
584 f = fdopen(fd, "w");
585 if (!f) {
00843602 586 r = -errno;
7f4e0805
LP
587 goto finish;
588 }
589
590 fd = -1;
591
981e4cd3
LP
592 signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
593 if (signal_fd < 0) {
00843602 594 r = -errno;
7f4e0805
LP
595 goto finish;
596 }
597
981e4cd3
LP
598 socket_fd = create_socket(&socket_name);
599 if (socket_fd < 0) {
7f4e0805
LP
600 r = socket_fd;
601 goto finish;
602 }
603
604 fprintf(f,
605 "[Ask]\n"
de0671ee 606 "PID="PID_FMT"\n"
7f4e0805 607 "Socket=%s\n"
21bc923a 608 "AcceptCached=%i\n"
64845bdc 609 "Echo=%i\n"
de0671ee 610 "NotAfter="USEC_FMT"\n",
df0ff127 611 getpid_cached(),
7f4e0805 612 socket_name,
e287086b
LP
613 (flags & ASK_PASSWORD_ACCEPT_CACHED) ? 1 : 0,
614 (flags & ASK_PASSWORD_ECHO) ? 1 : 0,
de0671ee 615 until);
7f4e0805
LP
616
617 if (message)
618 fprintf(f, "Message=%s\n", message);
619
620 if (icon)
621 fprintf(f, "Icon=%s\n", icon);
622
9fa1de96
DH
623 if (id)
624 fprintf(f, "Id=%s\n", id);
625
dacd6cee 626 r = fflush_and_check(f);
00843602 627 if (r < 0)
7f4e0805 628 goto finish;
7f4e0805
LP
629
630 memcpy(final, temp, sizeof(temp));
631
632 final[sizeof(final)-11] = 'a';
633 final[sizeof(final)-10] = 's';
634 final[sizeof(final)-9] = 'k';
635
636 if (rename(temp, final) < 0) {
00843602 637 r = -errno;
7f4e0805
LP
638 goto finish;
639 }
640
641 zero(pollfd);
642 pollfd[FD_SOCKET].fd = socket_fd;
643 pollfd[FD_SOCKET].events = POLLIN;
644 pollfd[FD_SIGNAL].fd = signal_fd;
645 pollfd[FD_SIGNAL].events = POLLIN;
c7b7d74e
XF
646 pollfd[FD_INOTIFY].fd = notify;
647 pollfd[FD_INOTIFY].events = POLLIN;
7f4e0805
LP
648
649 for (;;) {
650 char passphrase[LINE_MAX+1];
651 struct msghdr msghdr;
652 struct iovec iovec;
653 struct ucred *ucred;
654 union {
655 struct cmsghdr cmsghdr;
656 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
657 } control;
658 ssize_t n;
659 int k;
660 usec_t t;
661
662 t = now(CLOCK_MONOTONIC);
663
7dcda352 664 if (until > 0 && until <= t) {
7f4e0805
LP
665 r = -ETIME;
666 goto finish;
667 }
668
c7b7d74e 669 k = poll(pollfd, notify >= 0 ? _FD_MAX : _FD_MAX - 1, until > 0 ? (int) ((until-t)/USEC_PER_MSEC) : -1);
981e4cd3 670 if (k < 0) {
7f4e0805
LP
671 if (errno == EINTR)
672 continue;
673
00843602 674 r = -errno;
7f4e0805
LP
675 goto finish;
676 }
677
678 if (k <= 0) {
7f4e0805
LP
679 r = -ETIME;
680 goto finish;
681 }
682
21bc923a
LP
683 if (pollfd[FD_SIGNAL].revents & POLLIN) {
684 r = -EINTR;
685 goto finish;
686 }
7f4e0805 687
c7b7d74e
XF
688 if (notify >= 0 && pollfd[FD_INOTIFY].revents != 0) {
689 (void) flush_fd(notify);
690
691 r = ask_password_keyring(keyname, flags, ret);
692 if (r >= 0) {
693 r = 0;
694 goto finish;
695 } else if (r != -ENOKEY)
696 goto finish;
697 }
698
699 if (pollfd[FD_SOCKET].revents == 0)
700 continue;
701
7f4e0805 702 if (pollfd[FD_SOCKET].revents != POLLIN) {
7f4e0805
LP
703 r = -EIO;
704 goto finish;
705 }
706
5cfa2c3d 707 iovec = IOVEC_MAKE(passphrase, sizeof(passphrase));
7f4e0805
LP
708
709 zero(control);
710 zero(msghdr);
711 msghdr.msg_iov = &iovec;
712 msghdr.msg_iovlen = 1;
713 msghdr.msg_control = &control;
714 msghdr.msg_controllen = sizeof(control);
715
981e4cd3
LP
716 n = recvmsg(socket_fd, &msghdr, 0);
717 if (n < 0) {
3742095b 718 if (IN_SET(errno, EAGAIN, EINTR))
7f4e0805
LP
719 continue;
720
00843602 721 r = -errno;
7f4e0805
LP
722 goto finish;
723 }
724
1c8da044
LP
725 cmsg_close_all(&msghdr);
726
7f4e0805 727 if (n <= 0) {
00843602 728 log_debug("Message too short");
7f4e0805
LP
729 continue;
730 }
731
732 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
733 control.cmsghdr.cmsg_level != SOL_SOCKET ||
734 control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
735 control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
00843602 736 log_debug("Received message without credentials. Ignoring.");
7f4e0805
LP
737 continue;
738 }
739
740 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
741 if (ucred->uid != 0) {
00843602 742 log_debug("Got request from unprivileged user. Ignoring.");
7f4e0805
LP
743 continue;
744 }
745
746 if (passphrase[0] == '+') {
e287086b 747 /* An empty message refers to the empty password */
8254a475 748 if (n == 1)
bea1a013 749 l = strv_new("");
8254a475
LP
750 else
751 l = strv_parse_nulstr(passphrase+1, n-1);
87f54463 752 explicit_bzero_safe(passphrase, n);
8254a475 753 if (!l) {
7f4e0805
LP
754 r = -ENOMEM;
755 goto finish;
756 }
757
58629001 758 if (strv_isempty(l)) {
e287086b 759 l = strv_free(l);
00843602 760 log_debug("Invalid packet");
21bc923a
LP
761 continue;
762 }
763
e287086b
LP
764 break;
765 }
21bc923a 766
e287086b 767 if (passphrase[0] == '-') {
7f4e0805
LP
768 r = -ECANCELED;
769 goto finish;
7f4e0805
LP
770 }
771
e287086b 772 log_debug("Invalid packet");
7f4e0805
LP
773 }
774
e287086b
LP
775 if (keyname)
776 (void) add_to_keyring_and_log(keyname, flags, l);
777
ae2a15bc 778 *ret = TAKE_PTR(l);
7f4e0805
LP
779 r = 0;
780
781finish:
981e4cd3 782 if (socket_name)
00843602 783 (void) unlink(socket_name);
7f4e0805 784
00843602 785 (void) unlink(temp);
7f4e0805
LP
786
787 if (final[0])
00843602 788 (void) unlink(final);
7f4e0805 789
f9b72cd8 790 assert_se(sigprocmask(SIG_SETMASK, &oldmask, NULL) == 0);
7f4e0805
LP
791 return r;
792}
260ab287 793
00843602
LP
794int ask_password_auto(
795 const char *message,
796 const char *icon,
797 const char *id,
e287086b 798 const char *keyname,
00843602 799 usec_t until,
e287086b
LP
800 AskPasswordFlags flags,
801 char ***ret) {
00843602
LP
802
803 int r;
804
e287086b 805 assert(ret);
21bc923a 806
c7b7d74e
XF
807 if ((flags & ASK_PASSWORD_ACCEPT_CACHED) &&
808 keyname &&
809 ((flags & ASK_PASSWORD_NO_TTY) || !isatty(STDIN_FILENO)) &&
810 (flags & ASK_PASSWORD_NO_AGENT)) {
e287086b
LP
811 r = ask_password_keyring(keyname, flags, ret);
812 if (r != -ENOKEY)
813 return r;
814 }
815
c7b7d74e
XF
816 if (!(flags & ASK_PASSWORD_NO_TTY) && isatty(STDIN_FILENO))
817 return ask_password_tty(-1, message, keyname, until, flags, NULL, ret);
00843602 818
e287086b
LP
819 if (!(flags & ASK_PASSWORD_NO_AGENT))
820 return ask_password_agent(message, icon, id, keyname, until, flags, ret);
821
822 return -EUNATCH;
260ab287 823}