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