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>
19 #include <sys/types.h>
24 #include "alloc-util.h"
25 #include "ask-password-api.h"
26 #include "conf-parser.h"
28 #include "dirent-util.h"
29 #include "exit-status.h"
35 #include "main-func.h"
36 #include "memory-util.h"
38 #include "path-util.h"
39 #include "plymouth-util.h"
40 #include "pretty-print.h"
41 #include "process-util.h"
43 #include "signal-util.h"
44 #include "socket-util.h"
45 #include "string-util.h"
47 #include "terminal-util.h"
48 #include "utmp-wtmp.h"
55 } arg_action
= ACTION_QUERY
;
57 static bool arg_plymouth
= false;
58 static bool arg_console
= false;
59 static const char *arg_device
= NULL
;
61 static int ask_password_plymouth(
64 AskPasswordFlags flags
,
65 const char *flag_file
,
68 static const union sockaddr_union sa
= PLYMOUTH_SOCKET
;
69 _cleanup_close_
int fd
= -1, notify
= -1;
70 _cleanup_free_
char *packet
= NULL
;
73 struct pollfd pollfd
[2] = {};
74 char buffer
[LINE_MAX
];
84 notify
= inotify_init1(IN_CLOEXEC
|IN_NONBLOCK
);
88 r
= inotify_add_watch(notify
, flag_file
, IN_ATTRIB
); /* for the link count */
93 fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
97 r
= connect(fd
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
));
101 if (flags
& ASK_PASSWORD_ACCEPT_CACHED
) {
102 packet
= strdup("c");
104 } else if (asprintf(&packet
, "*\002%c%s%n", (int) (strlen(message
) + 1), message
, &n
) < 0)
109 r
= loop_write(fd
, packet
, n
+ 1, true);
113 pollfd
[POLL_SOCKET
].fd
= fd
;
114 pollfd
[POLL_SOCKET
].events
= POLLIN
;
115 pollfd
[POLL_INOTIFY
].fd
= notify
;
116 pollfd
[POLL_INOTIFY
].events
= POLLIN
;
119 int sleep_for
= -1, j
;
124 y
= now(CLOCK_MONOTONIC
);
131 sleep_for
= (int) ((until
- y
) / USEC_PER_MSEC
);
134 if (flag_file
&& access(flag_file
, F_OK
) < 0) {
139 j
= poll(pollfd
, notify
>= 0 ? 2 : 1, sleep_for
);
151 if (notify
>= 0 && pollfd
[POLL_INOTIFY
].revents
!= 0)
152 (void) flush_fd(notify
);
154 if (pollfd
[POLL_SOCKET
].revents
== 0)
157 k
= read(fd
, buffer
+ p
, sizeof(buffer
) - p
);
159 if (IN_SET(errno
, EINTR
, EAGAIN
))
174 if (buffer
[0] == 5) {
176 if (flags
& ASK_PASSWORD_ACCEPT_CACHED
) {
177 /* Hmm, first try with cached
178 * passwords failed, so let's retry
179 * with a normal password request */
180 packet
= mfree(packet
);
182 if (asprintf(&packet
, "*\002%c%s%n", (int) (strlen(message
) + 1), message
, &n
) < 0) {
187 r
= loop_write(fd
, packet
, n
+1, true);
191 flags
&= ~ASK_PASSWORD_ACCEPT_CACHED
;
196 /* No password, because UI not shown */
200 } else if (IN_SET(buffer
[0], 2, 9)) {
204 /* One or more answers */
208 memcpy(&size
, buffer
+1, sizeof(size
));
209 size
= le32toh(size
);
210 if (size
+ 5 > sizeof(buffer
)) {
218 l
= strv_parse_nulstr(buffer
+ 5, size
);
237 explicit_bzero_safe(buffer
, sizeof(buffer
));
241 static int send_passwords(const char *socket_name
, char **passwords
) {
242 _cleanup_(erase_and_freep
) char *packet
= NULL
;
243 _cleanup_close_
int socket_fd
= -1;
244 union sockaddr_union sa
= {};
245 size_t packet_length
= 1;
252 salen
= sockaddr_un_set_path(&sa
.un
, socket_name
);
256 STRV_FOREACH(p
, passwords
)
257 packet_length
+= strlen(*p
) + 1;
259 packet
= new(char, packet_length
);
266 STRV_FOREACH(p
, passwords
)
267 d
= stpcpy(d
, *p
) + 1;
269 socket_fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0);
271 return log_debug_errno(errno
, "socket(): %m");
273 n
= sendto(socket_fd
, packet
, packet_length
, MSG_NOSIGNAL
, &sa
.sa
, salen
);
275 return log_debug_errno(errno
, "sendto(): %m");
280 static int parse_password(const char *filename
, char **wall
) {
281 _cleanup_free_
char *socket_name
= NULL
, *message
= NULL
;
282 bool accept_cached
= false, echo
= false;
283 uint64_t not_after
= 0;
286 const ConfigTableItem items
[] = {
287 { "Ask", "Socket", config_parse_string
, 0, &socket_name
},
288 { "Ask", "NotAfter", config_parse_uint64
, 0, ¬_after
},
289 { "Ask", "Message", config_parse_string
, 0, &message
},
290 { "Ask", "PID", config_parse_unsigned
, 0, &pid
},
291 { "Ask", "AcceptCached", config_parse_bool
, 0, &accept_cached
},
292 { "Ask", "Echo", config_parse_bool
, 0, &echo
},
300 r
= config_parse(NULL
, filename
, NULL
,
302 config_item_table_lookup
, items
,
303 CONFIG_PARSE_RELAXED
|CONFIG_PARSE_WARN
, NULL
);
308 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
309 "Invalid password file %s", filename
);
311 if (not_after
> 0 && now(CLOCK_MONOTONIC
) > not_after
)
314 if (pid
> 0 && !pid_is_alive(pid
))
317 if (arg_action
== ACTION_LIST
)
318 printf("'%s' (PID %u)\n", message
, pid
);
320 else if (arg_action
== ACTION_WALL
) {
324 "%s%sPassword entry required for \'%s\' (PID %u).\r\n"
325 "Please enter password with the systemd-tty-ask-password-agent tool:",
327 *wall
? "\r\n\r\n" : "",
336 _cleanup_strv_free_erase_
char **passwords
= NULL
;
338 assert(IN_SET(arg_action
, ACTION_QUERY
, ACTION_WATCH
));
340 if (access(socket_name
, W_OK
) < 0) {
341 if (arg_action
== ACTION_QUERY
)
342 log_info("Not querying '%s' (PID %u), lacking privileges.", message
, pid
);
348 r
= ask_password_plymouth(message
, not_after
, accept_cached
? ASK_PASSWORD_ACCEPT_CACHED
: 0, filename
, &passwords
);
353 const char *con
= arg_device
?: "/dev/console";
355 tty_fd
= acquire_terminal(con
, ACQUIRE_TERMINAL_WAIT
, USEC_INFINITY
);
357 return log_error_errno(tty_fd
, "Failed to acquire %s: %m", con
);
359 r
= reset_terminal_fd(tty_fd
, true);
361 log_warning_errno(r
, "Failed to reset terminal, ignoring: %m");
364 r
= ask_password_tty(tty_fd
, message
, NULL
, not_after
,
365 (echo
? ASK_PASSWORD_ECHO
: 0) |
366 (arg_console
? ASK_PASSWORD_CONSOLE_COLOR
: 0),
367 filename
, &passwords
);
370 tty_fd
= safe_close(tty_fd
);
375 /* If the query went away, that's OK */
376 if (IN_SET(r
, -ETIME
, -ENOENT
))
380 return log_error_errno(r
, "Failed to query password: %m");
382 r
= send_passwords(socket_name
, passwords
);
384 return log_error_errno(r
, "Failed to send: %m");
390 static int wall_tty_block(void) {
391 _cleanup_free_
char *p
= NULL
;
395 r
= get_ctty_devnr(0, &devnr
);
396 if (r
== -ENXIO
) /* We have no controlling tty */
399 return log_error_errno(r
, "Failed to get controlling TTY: %m");
401 if (asprintf(&p
, "/run/systemd/ask-password-block/%u:%u", major(devnr
), minor(devnr
)) < 0)
404 (void) mkdir_parents_label(p
, 0700);
405 (void) mkfifo(p
, 0600);
407 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
409 return log_debug_errno(errno
, "Failed to open %s: %m", p
);
414 static bool wall_tty_match(const char *path
, void *userdata
) {
415 _cleanup_free_
char *p
= NULL
;
416 _cleanup_close_
int fd
= -1;
419 if (!path_is_absolute(path
))
420 path
= strjoina("/dev/", path
);
422 if (lstat(path
, &st
) < 0) {
423 log_debug_errno(errno
, "Failed to stat %s: %m", path
);
427 if (!S_ISCHR(st
.st_mode
)) {
428 log_debug("%s is not a character device.", path
);
432 /* We use named pipes to ensure that wall messages suggesting
433 * password entry are not printed over password prompts
434 * already shown. We use the fact here that opening a pipe in
435 * non-blocking mode for write-only will succeed only if
436 * there's some writer behind it. Using pipes has the
437 * advantage that the block will automatically go away if the
440 if (asprintf(&p
, "/run/systemd/ask-password-block/%u:%u", major(st
.st_rdev
), minor(st
.st_rdev
)) < 0) {
445 fd
= open(p
, O_WRONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
447 log_debug_errno(errno
, "Failed to open the wall pipe: %m");
451 /* What, we managed to open the pipe? Then this tty is filtered. */
455 static int show_passwords(void) {
456 _cleanup_closedir_
DIR *d
;
460 d
= opendir("/run/systemd/ask-password");
465 return log_error_errno(errno
, "Failed to open /run/systemd/ask-password: %m");
468 FOREACH_DIRENT_ALL(de
, d
, return log_error_errno(errno
, "Failed to read directory: %m")) {
469 _cleanup_free_
char *p
= NULL
, *wall
= NULL
;
472 /* We only support /dev on tmpfs, hence we can rely on
473 * d_type to be reliable */
475 if (de
->d_type
!= DT_REG
)
478 if (hidden_or_backup_file(de
->d_name
))
481 if (!startswith(de
->d_name
, "ask."))
484 p
= path_join("/run/systemd/ask-password", de
->d_name
);
488 q
= parse_password(p
, &wall
);
493 (void) utmp_wall(wall
, NULL
, NULL
, wall_tty_match
, NULL
);
499 static int watch_passwords(void) {
506 _cleanup_close_
int notify
= -1, signal_fd
= -1, tty_block_fd
= -1;
507 struct pollfd pollfd
[_FD_MAX
] = {};
511 tty_block_fd
= wall_tty_block();
513 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
515 notify
= inotify_init1(IN_CLOEXEC
);
517 return log_error_errno(errno
, "Failed to allocate directory watch: %m");
519 if (inotify_add_watch(notify
, "/run/systemd/ask-password", IN_CLOSE_WRITE
|IN_MOVED_TO
) < 0) {
521 return log_error_errno(errno
, "Failed to add /run/systemd/ask-password to directory watch: inotify watch limit reached");
523 return log_error_errno(errno
, "Failed to add /run/systemd/ask-password to directory watch: %m");
526 assert_se(sigemptyset(&mask
) >= 0);
527 assert_se(sigset_add_many(&mask
, SIGINT
, SIGTERM
, -1) >= 0);
528 assert_se(sigprocmask(SIG_SETMASK
, &mask
, NULL
) >= 0);
530 signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
532 return log_error_errno(errno
, "Failed to allocate signal file descriptor: %m");
534 pollfd
[FD_INOTIFY
].fd
= notify
;
535 pollfd
[FD_INOTIFY
].events
= POLLIN
;
536 pollfd
[FD_SIGNAL
].fd
= signal_fd
;
537 pollfd
[FD_SIGNAL
].events
= POLLIN
;
540 r
= show_passwords();
542 log_error_errno(r
, "Failed to show password: %m");
544 if (poll(pollfd
, _FD_MAX
, -1) < 0) {
551 if (pollfd
[FD_INOTIFY
].revents
!= 0)
552 (void) flush_fd(notify
);
554 if (pollfd
[FD_SIGNAL
].revents
!= 0)
561 static int help(void) {
562 _cleanup_free_
char *link
= NULL
;
565 r
= terminal_urlify_man("systemd-tty-ask-password-agent", "1", &link
);
569 printf("%s [OPTIONS...]\n\n"
570 "Process system password requests.\n\n"
571 " -h --help Show this help\n"
572 " --version Show package version\n"
573 " --list Show pending password requests\n"
574 " --query Process pending password requests\n"
575 " --watch Continuously process password requests\n"
576 " --wall Continuously forward password requests to wall\n"
577 " --plymouth Ask question with Plymouth instead of on TTY\n"
578 " --console Ask question on /dev/console instead of current TTY\n"
579 "\nSee the %s for details.\n"
580 , program_invocation_short_name
587 static int parse_argv(int argc
, char *argv
[]) {
599 static const struct option options
[] = {
600 { "help", no_argument
, NULL
, 'h' },
601 { "version", no_argument
, NULL
, ARG_VERSION
},
602 { "list", no_argument
, NULL
, ARG_LIST
},
603 { "query", no_argument
, NULL
, ARG_QUERY
},
604 { "watch", no_argument
, NULL
, ARG_WATCH
},
605 { "wall", no_argument
, NULL
, ARG_WALL
},
606 { "plymouth", no_argument
, NULL
, ARG_PLYMOUTH
},
607 { "console", optional_argument
, NULL
, ARG_CONSOLE
},
616 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
627 arg_action
= ACTION_LIST
;
631 arg_action
= ACTION_QUERY
;
635 arg_action
= ACTION_WATCH
;
639 arg_action
= ACTION_WALL
;
651 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
652 "Empty console device path is not allowed.");
662 assert_not_reached("Unhandled option");
666 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
667 "%s takes no arguments.", program_invocation_short_name
);
669 if (arg_plymouth
|| arg_console
) {
671 if (!IN_SET(arg_action
, ACTION_QUERY
, ACTION_WATCH
))
672 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
673 "Options --query and --watch conflict.");
675 if (arg_plymouth
&& arg_console
)
676 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
677 "Options --plymouth and --console conflict.");
684 * To be able to ask on all terminal devices of /dev/console the devices are collected. If more than one
685 * device is found, then on each of the terminals a inquiring task is forked. Every task has its own session
686 * and its own controlling terminal. If one of the tasks does handle a password, the remaining tasks will be
689 static int ask_on_this_console(const char *tty
, pid_t
*ret_pid
, char **arguments
) {
690 static const struct sigaction sigchld
= {
691 .sa_handler
= nop_signal_handler
,
692 .sa_flags
= SA_NOCLDSTOP
| SA_RESTART
,
694 static const struct sigaction sighup
= {
695 .sa_handler
= SIG_DFL
,
696 .sa_flags
= SA_RESTART
,
700 assert_se(sigaction(SIGCHLD
, &sigchld
, NULL
) >= 0);
701 assert_se(sigaction(SIGHUP
, &sighup
, NULL
) >= 0);
702 assert_se(sigprocmask_many(SIG_UNBLOCK
, NULL
, SIGHUP
, SIGCHLD
, -1) >= 0);
704 r
= safe_fork("(sd-passwd)", FORK_RESET_SIGNALS
|FORK_LOG
, ret_pid
);
710 assert_se(prctl(PR_SET_PDEATHSIG
, SIGHUP
) >= 0);
712 STRV_FOREACH(i
, arguments
) {
715 if (!streq(*i
, "--console"))
718 k
= strjoin("--console=", tty
);
724 free_and_replace(*i
, k
);
727 execv(SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH
, arguments
);
734 static void terminate_agents(Set
*pids
) {
736 siginfo_t status
= {};
743 * Request termination of the remaining processes as those
744 * are not required anymore.
746 SET_FOREACH(p
, pids
, i
)
747 (void) kill(PTR_TO_PID(p
), SIGTERM
);
750 * Collect the processes which have go away.
752 assert_se(sigemptyset(&set
) >= 0);
753 assert_se(sigaddset(&set
, SIGCHLD
) >= 0);
754 timespec_store(&ts
, 50 * USEC_PER_MSEC
);
756 while (!set_isempty(pids
)) {
759 r
= waitid(P_ALL
, 0, &status
, WEXITED
|WNOHANG
);
760 if (r
< 0 && errno
== EINTR
)
763 if (r
== 0 && status
.si_pid
> 0) {
764 set_remove(pids
, PID_TO_PTR(status
.si_pid
));
768 signum
= sigtimedwait(&set
, NULL
, &ts
);
771 log_error_errno(errno
, "sigtimedwait() failed: %m");
774 assert(signum
== SIGCHLD
);
778 * Kill hanging processes.
780 SET_FOREACH(p
, pids
, i
) {
781 log_warning("Failed to terminate child %d, killing it", PTR_TO_PID(p
));
782 (void) kill(PTR_TO_PID(p
), SIGKILL
);
786 static int ask_on_consoles(char *argv
[]) {
787 _cleanup_set_free_ Set
*pids
= NULL
;
788 _cleanup_strv_free_
char **consoles
= NULL
, **arguments
= NULL
;
789 siginfo_t status
= {};
794 r
= get_kernel_consoles(&consoles
);
796 return log_error_errno(r
, "Failed to determine devices of /dev/console: %m");
798 pids
= set_new(NULL
);
802 arguments
= strv_copy(argv
);
806 /* Start an agent on each console. */
807 STRV_FOREACH(tty
, consoles
) {
808 r
= ask_on_this_console(*tty
, &pid
, arguments
);
812 if (set_put(pids
, PID_TO_PTR(pid
)) < 0)
816 /* Wait for an agent to exit. */
820 if (waitid(P_ALL
, 0, &status
, WEXITED
) < 0) {
824 return log_error_errno(errno
, "waitid() failed: %m");
827 set_remove(pids
, PID_TO_PTR(status
.si_pid
));
831 if (!is_clean_exit(status
.si_code
, status
.si_status
, EXIT_CLEAN_DAEMON
, NULL
))
832 log_error("Password agent failed with: %d", status
.si_status
);
834 terminate_agents(pids
);
838 static int run(int argc
, char *argv
[]) {
845 r
= parse_argv(argc
, argv
);
849 if (arg_console
&& !arg_device
)
851 * Spawn a separate process for each console device.
853 return ask_on_consoles(argv
);
857 * Later on, a controlling terminal will be acquired,
858 * therefore the current process has to become a session
859 * leader and should not have a controlling terminal already.
862 (void) release_terminal();
865 if (IN_SET(arg_action
, ACTION_WATCH
, ACTION_WALL
))
866 return watch_passwords();
868 return show_passwords();
871 DEFINE_MAIN_FUNCTION(run
);