]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/tty-ask-password-agent/tty-ask-password-agent.c
ask-password: rework how we pass request meta info when asking passwords
[thirdparty/systemd.git] / src / tty-ask-password-agent / tty-ask-password-agent.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 /***
3 Copyright © 2015 Werner Fink
4 ***/
5
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <getopt.h>
9 #include <stdbool.h>
10 #include <stddef.h>
11 #include <sys/prctl.h>
12 #include <sys/signalfd.h>
13 #include <sys/stat.h>
14 #include <sys/types.h>
15 #include <sys/un.h>
16 #include <sys/wait.h>
17 #include <unistd.h>
18
19 #include "alloc-util.h"
20 #include "ask-password-api.h"
21 #include "build.h"
22 #include "conf-parser.h"
23 #include "constants.h"
24 #include "dirent-util.h"
25 #include "exit-status.h"
26 #include "fd-util.h"
27 #include "fileio.h"
28 #include "hashmap.h"
29 #include "inotify-util.h"
30 #include "io-util.h"
31 #include "macro.h"
32 #include "main-func.h"
33 #include "memory-util.h"
34 #include "mkdir-label.h"
35 #include "path-util.h"
36 #include "pretty-print.h"
37 #include "process-util.h"
38 #include "set.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 "wall.h"
45
46 static enum {
47 ACTION_LIST,
48 ACTION_QUERY,
49 ACTION_WATCH,
50 ACTION_WALL,
51 } arg_action = ACTION_QUERY;
52
53 static bool arg_plymouth = false;
54 static bool arg_console = false;
55 static const char *arg_device = NULL;
56
57 static int send_passwords(const char *socket_name, char **passwords) {
58 _cleanup_(erase_and_freep) char *packet = NULL;
59 _cleanup_close_ int socket_fd = -EBADF;
60 union sockaddr_union sa;
61 socklen_t sa_len;
62 size_t packet_length = 1;
63 char *d;
64 ssize_t n;
65 int r;
66
67 assert(socket_name);
68
69 r = sockaddr_un_set_path(&sa.un, socket_name);
70 if (r < 0)
71 return r;
72 sa_len = r;
73
74 STRV_FOREACH(p, passwords)
75 packet_length += strlen(*p) + 1;
76
77 packet = new(char, packet_length);
78 if (!packet)
79 return -ENOMEM;
80
81 packet[0] = '+';
82
83 d = packet + 1;
84 STRV_FOREACH(p, passwords)
85 d = stpcpy(d, *p) + 1;
86
87 socket_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
88 if (socket_fd < 0)
89 return log_debug_errno(errno, "socket(): %m");
90
91 n = sendto(socket_fd, packet, packet_length, MSG_NOSIGNAL, &sa.sa, sa_len);
92 if (n < 0)
93 return log_debug_errno(errno, "sendto(): %m");
94
95 return (int) n;
96 }
97
98 static bool wall_tty_match(const char *path, bool is_local, void *userdata) {
99 _cleanup_free_ char *p = NULL;
100 _cleanup_close_ int fd = -EBADF;
101 struct stat st;
102
103 assert(path_is_absolute(path));
104
105 if (lstat(path, &st) < 0) {
106 log_debug_errno(errno, "Failed to stat %s: %m", path);
107 return true;
108 }
109
110 if (!S_ISCHR(st.st_mode)) {
111 log_debug("%s is not a character device.", path);
112 return true;
113 }
114
115 /* We use named pipes to ensure that wall messages suggesting
116 * password entry are not printed over password prompts
117 * already shown. We use the fact here that opening a pipe in
118 * non-blocking mode for write-only will succeed only if
119 * there's some writer behind it. Using pipes has the
120 * advantage that the block will automatically go away if the
121 * process dies. */
122
123 if (asprintf(&p, "/run/systemd/ask-password-block/%u:%u", major(st.st_rdev), minor(st.st_rdev)) < 0) {
124 log_oom();
125 return true;
126 }
127
128 fd = open(p, O_WRONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
129 if (fd < 0) {
130 log_debug_errno(errno, "Failed to open the wall pipe: %m");
131 return 1;
132 }
133
134 /* What, we managed to open the pipe? Then this tty is filtered. */
135 return 0;
136 }
137
138 static int agent_ask_password_tty(
139 const char *message,
140 usec_t until,
141 AskPasswordFlags flags,
142 const char *flag_file,
143 char ***ret) {
144
145 int tty_fd = -EBADF, r;
146 const char *con = arg_device ?: "/dev/console";
147
148 if (arg_console) {
149 tty_fd = acquire_terminal(con, ACQUIRE_TERMINAL_WAIT, USEC_INFINITY);
150 if (tty_fd < 0)
151 return log_error_errno(tty_fd, "Failed to acquire %s: %m", con);
152
153 r = reset_terminal_fd(tty_fd, true);
154 if (r < 0)
155 log_warning_errno(r, "Failed to reset terminal, ignoring: %m");
156
157 log_info("Starting password query on %s.", con);
158 }
159
160 AskPasswordRequest req = {
161 .message = message,
162 };
163
164 r = ask_password_tty(tty_fd, &req, until, flags, flag_file, ret);
165
166 if (arg_console) {
167 tty_fd = safe_close(tty_fd);
168 release_terminal();
169
170 if (r >= 0)
171 log_info("Password query on %s finished successfully.", con);
172 }
173
174 return r;
175 }
176
177 static int process_one_password_file(const char *filename) {
178 _cleanup_free_ char *socket_name = NULL, *message = NULL;
179 bool accept_cached = false, echo = false, silent = false;
180 uint64_t not_after = 0;
181 pid_t pid = 0;
182
183 const ConfigTableItem items[] = {
184 { "Ask", "Socket", config_parse_string, CONFIG_PARSE_STRING_SAFE, &socket_name },
185 { "Ask", "NotAfter", config_parse_uint64, 0, &not_after },
186 { "Ask", "Message", config_parse_string, 0, &message },
187 { "Ask", "PID", config_parse_pid, 0, &pid },
188 { "Ask", "AcceptCached", config_parse_bool, 0, &accept_cached },
189 { "Ask", "Echo", config_parse_bool, 0, &echo },
190 { "Ask", "Silent", config_parse_bool, 0, &silent },
191 {}
192 };
193
194 int r;
195
196 assert(filename);
197
198 r = config_parse(NULL, filename, NULL,
199 NULL,
200 config_item_table_lookup, items,
201 CONFIG_PARSE_RELAXED|CONFIG_PARSE_WARN,
202 NULL,
203 NULL);
204 if (r < 0)
205 return r;
206
207 if (!socket_name)
208 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG),
209 "Invalid password file %s", filename);
210
211 if (not_after > 0 && now(CLOCK_MONOTONIC) > not_after)
212 return 0;
213
214 if (pid > 0 && pid_is_alive(pid) <= 0)
215 return 0;
216
217 switch (arg_action) {
218 case ACTION_LIST:
219 printf("'%s' (PID " PID_FMT ")\n", strna(message), pid);
220 return 0;
221
222 case ACTION_WALL: {
223 _cleanup_free_ char *msg = NULL;
224
225 if (asprintf(&msg,
226 "Password entry required for \'%s\' (PID " PID_FMT ").\r\n"
227 "Please enter password with the systemd-tty-ask-password-agent tool.",
228 strna(message),
229 pid) < 0)
230 return log_oom();
231
232 (void) wall(msg, NULL, NULL, wall_tty_match, NULL);
233 return 0;
234 }
235 case ACTION_QUERY:
236 case ACTION_WATCH: {
237 _cleanup_strv_free_erase_ char **passwords = NULL;
238 AskPasswordFlags flags = 0;
239
240 if (access(socket_name, W_OK) < 0) {
241 if (arg_action == ACTION_QUERY)
242 log_info("Not querying '%s' (PID " PID_FMT "), lacking privileges.", strna(message), pid);
243
244 return 0;
245 }
246
247 SET_FLAG(flags, ASK_PASSWORD_ACCEPT_CACHED, accept_cached);
248 SET_FLAG(flags, ASK_PASSWORD_CONSOLE_COLOR, arg_console);
249 SET_FLAG(flags, ASK_PASSWORD_ECHO, echo);
250 SET_FLAG(flags, ASK_PASSWORD_SILENT, silent);
251
252 if (arg_plymouth) {
253 AskPasswordRequest req = {
254 .message = message,
255 };
256
257 r = ask_password_plymouth(&req, not_after, flags, filename, &passwords);
258 } else
259 r = agent_ask_password_tty(message, not_after, flags, filename, &passwords);
260 if (r < 0) {
261 /* If the query went away, that's OK */
262 if (IN_SET(r, -ETIME, -ENOENT))
263 return 0;
264
265 return log_error_errno(r, "Failed to query password: %m");
266 }
267
268 if (strv_isempty(passwords))
269 return -ECANCELED;
270
271 r = send_passwords(socket_name, passwords);
272 if (r < 0)
273 return log_error_errno(r, "Failed to send: %m");
274 break;
275 }}
276
277 return 0;
278 }
279
280 static int wall_tty_block(void) {
281 _cleanup_free_ char *p = NULL;
282 dev_t devnr;
283 int fd, r;
284
285 r = get_ctty_devnr(0, &devnr);
286 if (r == -ENXIO) /* We have no controlling tty */
287 return -ENOTTY;
288 if (r < 0)
289 return log_error_errno(r, "Failed to get controlling TTY: %m");
290
291 if (asprintf(&p, "/run/systemd/ask-password-block/%u:%u", major(devnr), minor(devnr)) < 0)
292 return log_oom();
293
294 (void) mkdir_parents_label(p, 0700);
295 (void) mkfifo(p, 0600);
296
297 fd = open(p, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
298 if (fd < 0)
299 return log_debug_errno(errno, "Failed to open %s: %m", p);
300
301 return fd;
302 }
303
304 static int process_password_files(void) {
305 _cleanup_closedir_ DIR *d = NULL;
306 int r = 0;
307
308 d = opendir("/run/systemd/ask-password");
309 if (!d) {
310 if (errno == ENOENT)
311 return 0;
312
313 return log_error_errno(errno, "Failed to open /run/systemd/ask-password: %m");
314 }
315
316 FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read directory: %m")) {
317 _cleanup_free_ char *p = NULL;
318 int q;
319
320 /* We only support /run on tmpfs, hence we can rely on
321 * d_type to be reliable */
322
323 if (de->d_type != DT_REG)
324 continue;
325
326 if (!startswith(de->d_name, "ask."))
327 continue;
328
329 p = path_join("/run/systemd/ask-password", de->d_name);
330 if (!p)
331 return log_oom();
332
333 q = process_one_password_file(p);
334 if (q < 0 && r == 0)
335 r = q;
336 }
337
338 return r;
339 }
340
341 static int process_and_watch_password_files(bool watch) {
342 enum {
343 FD_SIGNAL,
344 FD_INOTIFY,
345 _FD_MAX
346 };
347
348 _unused_ _cleanup_close_ int tty_block_fd = -EBADF;
349 _cleanup_close_ int notify = -EBADF, signal_fd = -EBADF;
350 struct pollfd pollfd[_FD_MAX];
351 sigset_t mask;
352 int r;
353
354 tty_block_fd = wall_tty_block();
355
356 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
357
358 assert_se(sigemptyset(&mask) >= 0);
359 assert_se(sigset_add_many(&mask, SIGTERM, -1) >= 0);
360 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) >= 0);
361
362 if (watch) {
363 signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
364 if (signal_fd < 0)
365 return log_error_errno(errno, "Failed to allocate signal file descriptor: %m");
366
367 pollfd[FD_SIGNAL] = (struct pollfd) { .fd = signal_fd, .events = POLLIN };
368
369 notify = inotify_init1(IN_CLOEXEC);
370 if (notify < 0)
371 return log_error_errno(errno, "Failed to allocate directory watch: %m");
372
373 r = inotify_add_watch_and_warn(notify, "/run/systemd/ask-password", IN_CLOSE_WRITE|IN_MOVED_TO);
374 if (r < 0)
375 return r;
376
377 pollfd[FD_INOTIFY] = (struct pollfd) { .fd = notify, .events = POLLIN };
378 }
379
380 for (;;) {
381 usec_t timeout = USEC_INFINITY;
382
383 r = process_password_files();
384 if (r < 0) {
385 if (r == -ECANCELED)
386 /* Disable poll() timeout since at least one password has
387 * been skipped and therefore one file remains and is
388 * unlikely to trigger any events. */
389 timeout = 0;
390 else
391 /* FIXME: we should do something here since otherwise the service
392 * requesting the password won't notice the error and will wait
393 * indefinitely. */
394 log_error_errno(r, "Failed to process password: %m");
395 }
396
397 if (!watch)
398 break;
399
400 r = ppoll_usec(pollfd, _FD_MAX, timeout);
401 if (r == -EINTR)
402 continue;
403 if (r < 0)
404 return r;
405
406 if (pollfd[FD_INOTIFY].revents != 0)
407 (void) flush_fd(notify);
408
409 if (pollfd[FD_SIGNAL].revents != 0)
410 break;
411 }
412
413 return 0;
414 }
415
416 static int help(void) {
417 _cleanup_free_ char *link = NULL;
418 int r;
419
420 r = terminal_urlify_man("systemd-tty-ask-password-agent", "1", &link);
421 if (r < 0)
422 return log_oom();
423
424 printf("%s [OPTIONS...]\n\n"
425 "%sProcess system password requests.%s\n\n"
426 " -h --help Show this help\n"
427 " --version Show package version\n"
428 " --list Show pending password requests\n"
429 " --query Process pending password requests\n"
430 " --watch Continuously process password requests\n"
431 " --wall Continuously forward password requests to wall\n"
432 " --plymouth Ask question with Plymouth instead of on TTY\n"
433 " --console[=DEVICE] Ask question on /dev/console (or DEVICE if specified)\n"
434 " instead of the current TTY\n"
435 "\nSee the %s for details.\n",
436 program_invocation_short_name,
437 ansi_highlight(),
438 ansi_normal(),
439 link);
440
441 return 0;
442 }
443
444 static int parse_argv(int argc, char *argv[]) {
445
446 enum {
447 ARG_LIST = 0x100,
448 ARG_QUERY,
449 ARG_WATCH,
450 ARG_WALL,
451 ARG_PLYMOUTH,
452 ARG_CONSOLE,
453 ARG_VERSION
454 };
455
456 static const struct option options[] = {
457 { "help", no_argument, NULL, 'h' },
458 { "version", no_argument, NULL, ARG_VERSION },
459 { "list", no_argument, NULL, ARG_LIST },
460 { "query", no_argument, NULL, ARG_QUERY },
461 { "watch", no_argument, NULL, ARG_WATCH },
462 { "wall", no_argument, NULL, ARG_WALL },
463 { "plymouth", no_argument, NULL, ARG_PLYMOUTH },
464 { "console", optional_argument, NULL, ARG_CONSOLE },
465 {}
466 };
467
468 int c;
469
470 assert(argc >= 0);
471 assert(argv);
472
473 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
474
475 switch (c) {
476
477 case 'h':
478 return help();
479
480 case ARG_VERSION:
481 return version();
482
483 case ARG_LIST:
484 arg_action = ACTION_LIST;
485 break;
486
487 case ARG_QUERY:
488 arg_action = ACTION_QUERY;
489 break;
490
491 case ARG_WATCH:
492 arg_action = ACTION_WATCH;
493 break;
494
495 case ARG_WALL:
496 arg_action = ACTION_WALL;
497 break;
498
499 case ARG_PLYMOUTH:
500 arg_plymouth = true;
501 break;
502
503 case ARG_CONSOLE:
504 arg_console = true;
505 if (optarg) {
506
507 if (isempty(optarg))
508 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
509 "Empty console device path is not allowed.");
510
511 arg_device = optarg;
512 }
513 break;
514
515 case '?':
516 return -EINVAL;
517
518 default:
519 assert_not_reached();
520 }
521
522 if (optind != argc)
523 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
524 "%s takes no arguments.", program_invocation_short_name);
525
526 if (arg_plymouth || arg_console) {
527
528 if (!IN_SET(arg_action, ACTION_QUERY, ACTION_WATCH))
529 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
530 "Options --query and --watch conflict.");
531
532 if (arg_plymouth && arg_console)
533 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
534 "Options --plymouth and --console conflict.");
535 }
536
537 return 1;
538 }
539
540 /*
541 * To be able to ask on all terminal devices of /dev/console the devices are collected. If more than one
542 * device is found, then on each of the terminals an inquiring task is forked. Every task has its own session
543 * and its own controlling terminal. If one of the tasks does handle a password, the remaining tasks will be
544 * terminated.
545 */
546 static int ask_on_this_console(const char *tty, pid_t *ret_pid, char **arguments) {
547 static const struct sigaction sigchld = {
548 .sa_handler = nop_signal_handler,
549 .sa_flags = SA_NOCLDSTOP | SA_RESTART,
550 };
551 static const struct sigaction sighup = {
552 .sa_handler = SIG_DFL,
553 .sa_flags = SA_RESTART,
554 };
555 int r;
556
557 assert_se(sigaction(SIGCHLD, &sigchld, NULL) >= 0);
558 assert_se(sigaction(SIGHUP, &sighup, NULL) >= 0);
559 assert_se(sigprocmask_many(SIG_UNBLOCK, NULL, SIGHUP, SIGCHLD, -1) >= 0);
560
561 r = safe_fork("(sd-passwd)", FORK_RESET_SIGNALS|FORK_LOG, ret_pid);
562 if (r < 0)
563 return r;
564 if (r == 0) {
565 assert_se(prctl(PR_SET_PDEATHSIG, SIGHUP) >= 0);
566
567 STRV_FOREACH(i, arguments) {
568 char *k;
569
570 if (!streq(*i, "--console"))
571 continue;
572
573 k = strjoin("--console=", tty);
574 if (!k) {
575 log_oom();
576 _exit(EXIT_FAILURE);
577 }
578
579 free_and_replace(*i, k);
580 }
581
582 execv(SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, arguments);
583 _exit(EXIT_FAILURE);
584 }
585
586 return 0;
587 }
588
589 static void terminate_agents(Set *pids) {
590 sigset_t set;
591 void *p;
592 int r, signum;
593
594 /*
595 * Request termination of the remaining processes as those
596 * are not required anymore.
597 */
598 SET_FOREACH(p, pids)
599 (void) kill(PTR_TO_PID(p), SIGTERM);
600
601 /*
602 * Collect the processes which have go away.
603 */
604 assert_se(sigemptyset(&set) >= 0);
605 assert_se(sigaddset(&set, SIGCHLD) >= 0);
606
607 while (!set_isempty(pids)) {
608 siginfo_t status = {};
609
610 r = waitid(P_ALL, 0, &status, WEXITED|WNOHANG);
611 if (r < 0 && errno == EINTR)
612 continue;
613
614 if (r == 0 && status.si_pid > 0) {
615 set_remove(pids, PID_TO_PTR(status.si_pid));
616 continue;
617 }
618
619 signum = sigtimedwait(&set, NULL, TIMESPEC_STORE(50 * USEC_PER_MSEC));
620 if (signum < 0) {
621 if (errno != EAGAIN)
622 log_error_errno(errno, "sigtimedwait() failed: %m");
623 break;
624 }
625 assert(signum == SIGCHLD);
626 }
627
628 /*
629 * Kill hanging processes.
630 */
631 SET_FOREACH(p, pids) {
632 log_warning("Failed to terminate child %d, killing it", PTR_TO_PID(p));
633 (void) kill(PTR_TO_PID(p), SIGKILL);
634 }
635 }
636
637 static int ask_on_consoles(char *argv[]) {
638 _cleanup_set_free_ Set *pids = NULL;
639 _cleanup_strv_free_ char **consoles = NULL, **arguments = NULL;
640 siginfo_t status = {};
641 pid_t pid;
642 int r;
643
644 r = get_kernel_consoles(&consoles);
645 if (r < 0)
646 return log_error_errno(r, "Failed to determine devices of /dev/console: %m");
647
648 pids = set_new(NULL);
649 if (!pids)
650 return log_oom();
651
652 arguments = strv_copy(argv);
653 if (!arguments)
654 return log_oom();
655
656 /* Start an agent on each console. */
657 STRV_FOREACH(tty, consoles) {
658 r = ask_on_this_console(*tty, &pid, arguments);
659 if (r < 0)
660 return r;
661
662 if (set_put(pids, PID_TO_PTR(pid)) < 0)
663 return log_oom();
664 }
665
666 /* Wait for an agent to exit. */
667 for (;;) {
668 zero(status);
669
670 if (waitid(P_ALL, 0, &status, WEXITED) < 0) {
671 if (errno == EINTR)
672 continue;
673
674 return log_error_errno(errno, "waitid() failed: %m");
675 }
676
677 set_remove(pids, PID_TO_PTR(status.si_pid));
678 break;
679 }
680
681 if (!is_clean_exit(status.si_code, status.si_status, EXIT_CLEAN_DAEMON, NULL))
682 log_error("Password agent failed with: %d", status.si_status);
683
684 terminate_agents(pids);
685 return 0;
686 }
687
688 static int run(int argc, char *argv[]) {
689 int r;
690
691 log_setup();
692
693 umask(0022);
694
695 r = parse_argv(argc, argv);
696 if (r <= 0)
697 return r;
698
699 if (arg_console && !arg_device)
700 /*
701 * Spawn a separate process for each console device.
702 */
703 return ask_on_consoles(argv);
704
705 if (arg_device) {
706 /*
707 * Later on, a controlling terminal will be acquired,
708 * therefore the current process has to become a session
709 * leader and should not have a controlling terminal already.
710 */
711 (void) setsid();
712 (void) release_terminal();
713 }
714
715 return process_and_watch_password_files(!IN_SET(arg_action, ACTION_QUERY, ACTION_LIST));
716 }
717
718 DEFINE_MAIN_FUNCTION(run);