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