1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright © 2015 Werner Fink
14 #include <sys/inotify.h>
15 #include <sys/prctl.h>
16 #include <sys/signalfd.h>
17 #include <sys/socket.h>
22 #include "alloc-util.h"
23 #include "ask-password-api.h"
24 #include "conf-parser.h"
26 #include "dirent-util.h"
27 #include "exit-status.h"
34 #include "path-util.h"
35 #include "process-util.h"
36 #include "signal-util.h"
37 #include "socket-util.h"
38 #include "string-util.h"
40 #include "terminal-util.h"
42 #include "utmp-wtmp.h"
49 } arg_action
= ACTION_QUERY
;
51 static bool arg_plymouth
= false;
52 static bool arg_console
= false;
53 static const char *arg_device
= NULL
;
55 static int ask_password_plymouth(
58 AskPasswordFlags flags
,
59 const char *flag_file
,
62 static const union sockaddr_union sa
= PLYMOUTH_SOCKET
;
63 _cleanup_close_
int fd
= -1, notify
= -1;
64 _cleanup_free_
char *packet
= NULL
;
67 struct pollfd pollfd
[2] = {};
68 char buffer
[LINE_MAX
];
78 notify
= inotify_init1(IN_CLOEXEC
|IN_NONBLOCK
);
82 r
= inotify_add_watch(notify
, flag_file
, IN_ATTRIB
); /* for the link count */
87 fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
91 r
= connect(fd
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
));
95 if (flags
& ASK_PASSWORD_ACCEPT_CACHED
) {
98 } else if (asprintf(&packet
, "*\002%c%s%n", (int) (strlen(message
) + 1), message
, &n
) < 0)
103 r
= loop_write(fd
, packet
, n
+ 1, true);
107 pollfd
[POLL_SOCKET
].fd
= fd
;
108 pollfd
[POLL_SOCKET
].events
= POLLIN
;
109 pollfd
[POLL_INOTIFY
].fd
= notify
;
110 pollfd
[POLL_INOTIFY
].events
= POLLIN
;
113 int sleep_for
= -1, j
;
118 y
= now(CLOCK_MONOTONIC
);
125 sleep_for
= (int) ((until
- y
) / USEC_PER_MSEC
);
128 if (flag_file
&& access(flag_file
, F_OK
) < 0) {
133 j
= poll(pollfd
, notify
>= 0 ? 2 : 1, sleep_for
);
145 if (notify
>= 0 && pollfd
[POLL_INOTIFY
].revents
!= 0)
146 (void) flush_fd(notify
);
148 if (pollfd
[POLL_SOCKET
].revents
== 0)
151 k
= read(fd
, buffer
+ p
, sizeof(buffer
) - p
);
153 if (IN_SET(errno
, EINTR
, EAGAIN
))
168 if (buffer
[0] == 5) {
170 if (flags
& ASK_PASSWORD_ACCEPT_CACHED
) {
171 /* Hmm, first try with cached
172 * passwords failed, so let's retry
173 * with a normal password request */
174 packet
= mfree(packet
);
176 if (asprintf(&packet
, "*\002%c%s%n", (int) (strlen(message
) + 1), message
, &n
) < 0) {
181 r
= loop_write(fd
, packet
, n
+1, true);
185 flags
&= ~ASK_PASSWORD_ACCEPT_CACHED
;
190 /* No password, because UI not shown */
194 } else if (IN_SET(buffer
[0], 2, 9)) {
198 /* One or more answers */
202 memcpy(&size
, buffer
+1, sizeof(size
));
203 size
= le32toh(size
);
204 if (size
+ 5 > sizeof(buffer
)) {
212 l
= strv_parse_nulstr(buffer
+ 5, size
);
231 explicit_bzero(buffer
, sizeof(buffer
));
235 static int send_passwords(const char *socket_name
, char **passwords
) {
236 _cleanup_free_
char *packet
= NULL
;
237 _cleanup_close_
int socket_fd
= -1;
238 union sockaddr_union sa
= {};
239 size_t packet_length
= 1;
246 salen
= sockaddr_un_set_path(&sa
.un
, socket_name
);
250 STRV_FOREACH(p
, passwords
)
251 packet_length
+= strlen(*p
) + 1;
253 packet
= new(char, packet_length
);
260 STRV_FOREACH(p
, passwords
)
261 d
= stpcpy(d
, *p
) + 1;
263 socket_fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0);
265 r
= log_debug_errno(errno
, "socket(): %m");
269 n
= sendto(socket_fd
, packet
, packet_length
, MSG_NOSIGNAL
, &sa
.sa
, salen
);
271 r
= log_debug_errno(errno
, "sendto(): %m");
278 explicit_bzero(packet
, packet_length
);
282 static int parse_password(const char *filename
, char **wall
) {
283 _cleanup_free_
char *socket_name
= NULL
, *message
= NULL
;
284 bool accept_cached
= false, echo
= false;
285 uint64_t not_after
= 0;
288 const ConfigTableItem items
[] = {
289 { "Ask", "Socket", config_parse_string
, 0, &socket_name
},
290 { "Ask", "NotAfter", config_parse_uint64
, 0, ¬_after
},
291 { "Ask", "Message", config_parse_string
, 0, &message
},
292 { "Ask", "PID", config_parse_unsigned
, 0, &pid
},
293 { "Ask", "AcceptCached", config_parse_bool
, 0, &accept_cached
},
294 { "Ask", "Echo", config_parse_bool
, 0, &echo
},
302 r
= config_parse(NULL
, filename
, NULL
,
304 config_item_table_lookup
, items
,
305 CONFIG_PARSE_RELAXED
|CONFIG_PARSE_WARN
, NULL
);
310 log_error("Invalid password file %s", filename
);
314 if (not_after
> 0 && now(CLOCK_MONOTONIC
) > not_after
)
317 if (pid
> 0 && !pid_is_alive(pid
))
320 if (arg_action
== ACTION_LIST
)
321 printf("'%s' (PID %u)\n", message
, pid
);
323 else if (arg_action
== ACTION_WALL
) {
327 "%s%sPassword entry required for \'%s\' (PID %u).\r\n"
328 "Please enter password with the systemd-tty-ask-password-agent tool:",
330 *wall
? "\r\n\r\n" : "",
339 _cleanup_strv_free_erase_
char **passwords
= NULL
;
341 assert(IN_SET(arg_action
, ACTION_QUERY
, ACTION_WATCH
));
343 if (access(socket_name
, W_OK
) < 0) {
344 if (arg_action
== ACTION_QUERY
)
345 log_info("Not querying '%s' (PID %u), lacking privileges.", message
, pid
);
351 r
= ask_password_plymouth(message
, not_after
, accept_cached
? ASK_PASSWORD_ACCEPT_CACHED
: 0, filename
, &passwords
);
353 char *password
= NULL
;
357 const char *con
= arg_device
?: "/dev/console";
359 tty_fd
= acquire_terminal(con
, ACQUIRE_TERMINAL_WAIT
, USEC_INFINITY
);
361 return log_error_errno(tty_fd
, "Failed to acquire %s: %m", con
);
363 r
= reset_terminal_fd(tty_fd
, true);
365 log_warning_errno(r
, "Failed to reset terminal, ignoring: %m");
368 r
= ask_password_tty(tty_fd
, message
, NULL
, not_after
,
369 (echo
? ASK_PASSWORD_ECHO
: 0) |
370 (arg_console
? ASK_PASSWORD_CONSOLE_COLOR
: 0),
371 filename
, &password
);
374 tty_fd
= safe_close(tty_fd
);
379 r
= strv_push(&passwords
, password
);
382 string_free_erase(password
);
385 /* If the query went away, that's OK */
386 if (IN_SET(r
, -ETIME
, -ENOENT
))
390 return log_error_errno(r
, "Failed to query password: %m");
392 r
= send_passwords(socket_name
, passwords
);
394 return log_error_errno(r
, "Failed to send: %m");
400 static int wall_tty_block(void) {
401 _cleanup_free_
char *p
= NULL
;
405 r
= get_ctty_devnr(0, &devnr
);
406 if (r
== -ENXIO
) /* We have no controlling tty */
409 return log_error_errno(r
, "Failed to get controlling TTY: %m");
411 if (asprintf(&p
, "/run/systemd/ask-password-block/%u:%u", major(devnr
), minor(devnr
)) < 0)
414 (void) mkdir_parents_label(p
, 0700);
415 (void) mkfifo(p
, 0600);
417 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
419 return log_debug_errno(errno
, "Failed to open %s: %m", p
);
424 static bool wall_tty_match(const char *path
, void *userdata
) {
425 _cleanup_free_
char *p
= NULL
;
426 _cleanup_close_
int fd
= -1;
429 if (!path_is_absolute(path
))
430 path
= strjoina("/dev/", path
);
432 if (lstat(path
, &st
) < 0) {
433 log_debug_errno(errno
, "Failed to stat %s: %m", path
);
437 if (!S_ISCHR(st
.st_mode
)) {
438 log_debug("%s is not a character device.", path
);
442 /* We use named pipes to ensure that wall messages suggesting
443 * password entry are not printed over password prompts
444 * already shown. We use the fact here that opening a pipe in
445 * non-blocking mode for write-only will succeed only if
446 * there's some writer behind it. Using pipes has the
447 * advantage that the block will automatically go away if the
450 if (asprintf(&p
, "/run/systemd/ask-password-block/%u:%u", major(st
.st_rdev
), minor(st
.st_rdev
)) < 0) {
455 fd
= open(p
, O_WRONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
457 log_debug_errno(errno
, "Failed to open the wall pipe: %m");
461 /* What, we managed to open the pipe? Then this tty is filtered. */
465 static int show_passwords(void) {
466 _cleanup_closedir_
DIR *d
;
470 d
= opendir("/run/systemd/ask-password");
475 return log_error_errno(errno
, "Failed to open /run/systemd/ask-password: %m");
478 FOREACH_DIRENT_ALL(de
, d
, return log_error_errno(errno
, "Failed to read directory: %m")) {
479 _cleanup_free_
char *p
= NULL
, *wall
= NULL
;
482 /* We only support /dev on tmpfs, hence we can rely on
483 * d_type to be reliable */
485 if (de
->d_type
!= DT_REG
)
488 if (hidden_or_backup_file(de
->d_name
))
491 if (!startswith(de
->d_name
, "ask."))
494 p
= strappend("/run/systemd/ask-password/", de
->d_name
);
498 q
= parse_password(p
, &wall
);
503 (void) utmp_wall(wall
, NULL
, NULL
, wall_tty_match
, NULL
);
509 static int watch_passwords(void) {
516 _cleanup_close_
int notify
= -1, signal_fd
= -1, tty_block_fd
= -1;
517 struct pollfd pollfd
[_FD_MAX
] = {};
521 tty_block_fd
= wall_tty_block();
523 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
525 notify
= inotify_init1(IN_CLOEXEC
);
527 return log_error_errno(errno
, "Failed to allocate directory watch: %m");
529 if (inotify_add_watch(notify
, "/run/systemd/ask-password", IN_CLOSE_WRITE
|IN_MOVED_TO
) < 0)
530 return log_error_errno(errno
, "Failed to add /run/systemd/ask-password to directory watch: %m");
532 assert_se(sigemptyset(&mask
) >= 0);
533 assert_se(sigset_add_many(&mask
, SIGINT
, SIGTERM
, -1) >= 0);
534 assert_se(sigprocmask(SIG_SETMASK
, &mask
, NULL
) >= 0);
536 signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
538 return log_error_errno(errno
, "Failed to allocate signal file descriptor: %m");
540 pollfd
[FD_INOTIFY
].fd
= notify
;
541 pollfd
[FD_INOTIFY
].events
= POLLIN
;
542 pollfd
[FD_SIGNAL
].fd
= signal_fd
;
543 pollfd
[FD_SIGNAL
].events
= POLLIN
;
546 r
= show_passwords();
548 log_error_errno(r
, "Failed to show password: %m");
550 if (poll(pollfd
, _FD_MAX
, -1) < 0) {
557 if (pollfd
[FD_INOTIFY
].revents
!= 0)
558 (void) flush_fd(notify
);
560 if (pollfd
[FD_SIGNAL
].revents
!= 0)
567 static int help(void) {
568 _cleanup_free_
char *link
= NULL
;
571 r
= terminal_urlify_man("systemd-tty-ask-password-agent", "1", &link
);
575 printf("%s [OPTIONS...]\n\n"
576 "Process system password requests.\n\n"
577 " -h --help Show this help\n"
578 " --version Show package version\n"
579 " --list Show pending password requests\n"
580 " --query Process pending password requests\n"
581 " --watch Continuously process password requests\n"
582 " --wall Continuously forward password requests to wall\n"
583 " --plymouth Ask question with Plymouth instead of on TTY\n"
584 " --console Ask question on /dev/console instead of current TTY\n"
585 "\nSee the %s for details.\n"
586 , program_invocation_short_name
593 static int parse_argv(int argc
, char *argv
[]) {
605 static const struct option options
[] = {
606 { "help", no_argument
, NULL
, 'h' },
607 { "version", no_argument
, NULL
, ARG_VERSION
},
608 { "list", no_argument
, NULL
, ARG_LIST
},
609 { "query", no_argument
, NULL
, ARG_QUERY
},
610 { "watch", no_argument
, NULL
, ARG_WATCH
},
611 { "wall", no_argument
, NULL
, ARG_WALL
},
612 { "plymouth", no_argument
, NULL
, ARG_PLYMOUTH
},
613 { "console", optional_argument
, NULL
, ARG_CONSOLE
},
622 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
633 arg_action
= ACTION_LIST
;
637 arg_action
= ACTION_QUERY
;
641 arg_action
= ACTION_WATCH
;
645 arg_action
= ACTION_WALL
;
656 if (isempty(optarg
)) {
657 log_error("Empty console device path is not allowed.");
669 assert_not_reached("Unhandled option");
672 if (optind
!= argc
) {
673 log_error("%s takes no arguments.", program_invocation_short_name
);
677 if (arg_plymouth
|| arg_console
) {
679 if (!IN_SET(arg_action
, ACTION_QUERY
, ACTION_WATCH
)) {
680 log_error("Options --query and --watch conflict.");
684 if (arg_plymouth
&& arg_console
) {
685 log_error("Options --plymouth and --console conflict.");
694 * To be able to ask on all terminal devices of /dev/console
695 * the devices are collected. If more than one device is found,
696 * then on each of the terminals a inquiring task is forked.
697 * Every task has its own session and its own controlling terminal.
698 * If one of the tasks does handle a password, the remaining tasks
699 * will be terminated.
701 static int ask_on_this_console(const char *tty
, pid_t
*ret_pid
, int argc
, char *argv
[]) {
702 struct sigaction sig
= {
703 .sa_handler
= nop_signal_handler
,
704 .sa_flags
= SA_NOCLDSTOP
| SA_RESTART
,
709 assert_se(sigprocmask_many(SIG_UNBLOCK
, NULL
, SIGHUP
, SIGCHLD
, -1) >= 0);
711 assert_se(sigemptyset(&sig
.sa_mask
) >= 0);
712 assert_se(sigaction(SIGCHLD
, &sig
, NULL
) >= 0);
714 sig
.sa_handler
= SIG_DFL
;
715 assert_se(sigaction(SIGHUP
, &sig
, NULL
) >= 0);
717 r
= safe_fork("(sd-passwd)", FORK_RESET_SIGNALS
|FORK_LOG
, &pid
);
723 assert_se(prctl(PR_SET_PDEATHSIG
, SIGHUP
) >= 0);
725 for (ac
= 0; ac
< argc
; ac
++) {
726 if (streq(argv
[ac
], "--console")) {
727 argv
[ac
] = strjoina("--console=", tty
);
734 execv(SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH
, argv
);
742 static void terminate_agents(Set
*pids
) {
744 siginfo_t status
= {};
751 * Request termination of the remaining processes as those
752 * are not required anymore.
754 SET_FOREACH(p
, pids
, i
)
755 (void) kill(PTR_TO_PID(p
), SIGTERM
);
758 * Collect the processes which have go away.
760 assert_se(sigemptyset(&set
) >= 0);
761 assert_se(sigaddset(&set
, SIGCHLD
) >= 0);
762 timespec_store(&ts
, 50 * USEC_PER_MSEC
);
764 while (!set_isempty(pids
)) {
767 r
= waitid(P_ALL
, 0, &status
, WEXITED
|WNOHANG
);
768 if (r
< 0 && errno
== EINTR
)
771 if (r
== 0 && status
.si_pid
> 0) {
772 set_remove(pids
, PID_TO_PTR(status
.si_pid
));
776 signum
= sigtimedwait(&set
, NULL
, &ts
);
779 log_error_errno(errno
, "sigtimedwait() failed: %m");
782 assert(signum
== SIGCHLD
);
786 * Kill hanging processes.
788 SET_FOREACH(p
, pids
, i
) {
789 log_warning("Failed to terminate child %d, killing it", PTR_TO_PID(p
));
790 (void) kill(PTR_TO_PID(p
), SIGKILL
);
794 static int ask_on_consoles(int argc
, char *argv
[]) {
795 _cleanup_set_free_ Set
*pids
= NULL
;
796 _cleanup_strv_free_
char **consoles
= NULL
;
797 siginfo_t status
= {};
802 r
= get_kernel_consoles(&consoles
);
804 return log_error_errno(r
, "Failed to determine devices of /dev/console: %m");
806 pids
= set_new(NULL
);
810 /* Start an agent on each console. */
811 STRV_FOREACH(tty
, consoles
) {
812 r
= ask_on_this_console(*tty
, &pid
, argc
, argv
);
816 if (set_put(pids
, PID_TO_PTR(pid
)) < 0)
820 /* Wait for an agent to exit. */
824 if (waitid(P_ALL
, 0, &status
, WEXITED
) < 0) {
828 return log_error_errno(errno
, "waitid() failed: %m");
831 set_remove(pids
, PID_TO_PTR(status
.si_pid
));
835 if (!is_clean_exit(status
.si_code
, status
.si_status
, EXIT_CLEAN_DAEMON
, NULL
))
836 log_error("Password agent failed with: %d", status
.si_status
);
838 terminate_agents(pids
);
842 int main(int argc
, char *argv
[]) {
845 log_set_target(LOG_TARGET_AUTO
);
846 log_parse_environment();
851 r
= parse_argv(argc
, argv
);
855 if (arg_console
&& !arg_device
)
857 * Spawn for each console device a separate process.
859 r
= ask_on_consoles(argc
, argv
);
864 * Later on, a controlling terminal will be acquired,
865 * therefore the current process has to become a session
866 * leader and should not have a controlling terminal already.
869 (void) release_terminal();
872 if (IN_SET(arg_action
, ACTION_WATCH
, ACTION_WALL
))
873 r
= watch_passwords();
875 r
= show_passwords();
879 return r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;