1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 Copyright © 2015 Werner Fink
11 #include <sys/prctl.h>
12 #include <sys/signalfd.h>
14 #include <sys/types.h>
19 #include "alloc-util.h"
20 #include "ask-password-api.h"
22 #include "conf-parser.h"
23 #include "constants.h"
24 #include "dirent-util.h"
25 #include "exit-status.h"
29 #include "inotify-util.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"
39 #include "signal-util.h"
40 #include "socket-util.h"
41 #include "string-util.h"
43 #include "terminal-util.h"
51 } arg_action
= ACTION_QUERY
;
53 static bool arg_plymouth
= false;
54 static bool arg_console
= false;
55 static const char *arg_device
= NULL
;
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
;
62 size_t packet_length
= 1;
69 r
= sockaddr_un_set_path(&sa
.un
, socket_name
);
74 STRV_FOREACH(p
, passwords
)
75 packet_length
+= strlen(*p
) + 1;
77 packet
= new(char, packet_length
);
84 STRV_FOREACH(p
, passwords
)
85 d
= stpcpy(d
, *p
) + 1;
87 socket_fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0);
89 return log_debug_errno(errno
, "socket(): %m");
91 n
= sendto(socket_fd
, packet
, packet_length
, MSG_NOSIGNAL
, &sa
.sa
, sa_len
);
93 return log_debug_errno(errno
, "sendto(): %m");
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
;
103 assert(path_is_absolute(path
));
105 if (lstat(path
, &st
) < 0) {
106 log_debug_errno(errno
, "Failed to stat %s: %m", path
);
110 if (!S_ISCHR(st
.st_mode
)) {
111 log_debug("%s is not a character device.", path
);
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
123 if (asprintf(&p
, "/run/systemd/ask-password-block/%u:%u", major(st
.st_rdev
), minor(st
.st_rdev
)) < 0) {
128 fd
= open(p
, O_WRONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
130 log_debug_errno(errno
, "Failed to open the wall pipe: %m");
134 /* What, we managed to open the pipe? Then this tty is filtered. */
138 static int agent_ask_password_tty(
141 AskPasswordFlags flags
,
142 const char *flag_file
,
145 int tty_fd
= -EBADF
, r
;
146 const char *con
= arg_device
?: "/dev/console";
149 tty_fd
= acquire_terminal(con
, ACQUIRE_TERMINAL_WAIT
, USEC_INFINITY
);
151 return log_error_errno(tty_fd
, "Failed to acquire %s: %m", con
);
153 r
= reset_terminal_fd(tty_fd
, true);
155 log_warning_errno(r
, "Failed to reset terminal, ignoring: %m");
157 log_info("Starting password query on %s.", con
);
160 AskPasswordRequest req
= {
164 r
= ask_password_tty(tty_fd
, &req
, until
, flags
, flag_file
, ret
);
167 tty_fd
= safe_close(tty_fd
);
171 log_info("Password query on %s finished successfully.", con
);
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;
183 const ConfigTableItem items
[] = {
184 { "Ask", "Socket", config_parse_string
, CONFIG_PARSE_STRING_SAFE
, &socket_name
},
185 { "Ask", "NotAfter", config_parse_uint64
, 0, ¬_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
},
198 r
= config_parse(NULL
, filename
, NULL
,
200 config_item_table_lookup
, items
,
201 CONFIG_PARSE_RELAXED
|CONFIG_PARSE_WARN
,
208 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
209 "Invalid password file %s", filename
);
211 if (not_after
> 0 && now(CLOCK_MONOTONIC
) > not_after
)
214 if (pid
> 0 && pid_is_alive(pid
) <= 0)
217 switch (arg_action
) {
219 printf("'%s' (PID " PID_FMT
")\n", strna(message
), pid
);
223 _cleanup_free_
char *msg
= NULL
;
226 "Password entry required for \'%s\' (PID " PID_FMT
").\r\n"
227 "Please enter password with the systemd-tty-ask-password-agent tool.",
232 (void) wall(msg
, NULL
, NULL
, wall_tty_match
, NULL
);
237 _cleanup_strv_free_erase_
char **passwords
= NULL
;
238 AskPasswordFlags flags
= 0;
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
);
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
);
253 AskPasswordRequest req
= {
257 r
= ask_password_plymouth(&req
, not_after
, flags
, filename
, &passwords
);
259 r
= agent_ask_password_tty(message
, not_after
, flags
, filename
, &passwords
);
261 /* If the query went away, that's OK */
262 if (IN_SET(r
, -ETIME
, -ENOENT
))
265 return log_error_errno(r
, "Failed to query password: %m");
268 if (strv_isempty(passwords
))
271 r
= send_passwords(socket_name
, passwords
);
273 return log_error_errno(r
, "Failed to send: %m");
280 static int wall_tty_block(void) {
281 _cleanup_free_
char *p
= NULL
;
285 r
= get_ctty_devnr(0, &devnr
);
286 if (r
== -ENXIO
) /* We have no controlling tty */
289 return log_error_errno(r
, "Failed to get controlling TTY: %m");
291 if (asprintf(&p
, "/run/systemd/ask-password-block/%u:%u", major(devnr
), minor(devnr
)) < 0)
294 (void) mkdir_parents_label(p
, 0700);
295 (void) mkfifo(p
, 0600);
297 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
299 return log_debug_errno(errno
, "Failed to open %s: %m", p
);
304 static int process_password_files(void) {
305 _cleanup_closedir_
DIR *d
= NULL
;
308 d
= opendir("/run/systemd/ask-password");
313 return log_error_errno(errno
, "Failed to open /run/systemd/ask-password: %m");
316 FOREACH_DIRENT(de
, d
, return log_error_errno(errno
, "Failed to read directory: %m")) {
317 _cleanup_free_
char *p
= NULL
;
320 /* We only support /run on tmpfs, hence we can rely on
321 * d_type to be reliable */
323 if (de
->d_type
!= DT_REG
)
326 if (!startswith(de
->d_name
, "ask."))
329 p
= path_join("/run/systemd/ask-password", de
->d_name
);
333 q
= process_one_password_file(p
);
341 static int process_and_watch_password_files(bool watch
) {
348 _unused_ _cleanup_close_
int tty_block_fd
= -EBADF
;
349 _cleanup_close_
int notify
= -EBADF
, signal_fd
= -EBADF
;
350 struct pollfd pollfd
[_FD_MAX
];
354 tty_block_fd
= wall_tty_block();
356 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
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);
363 signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
365 return log_error_errno(errno
, "Failed to allocate signal file descriptor: %m");
367 pollfd
[FD_SIGNAL
] = (struct pollfd
) { .fd
= signal_fd
, .events
= POLLIN
};
369 notify
= inotify_init1(IN_CLOEXEC
);
371 return log_error_errno(errno
, "Failed to allocate directory watch: %m");
373 r
= inotify_add_watch_and_warn(notify
, "/run/systemd/ask-password", IN_CLOSE_WRITE
|IN_MOVED_TO
);
377 pollfd
[FD_INOTIFY
] = (struct pollfd
) { .fd
= notify
, .events
= POLLIN
};
381 usec_t timeout
= USEC_INFINITY
;
383 r
= process_password_files();
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. */
391 /* FIXME: we should do something here since otherwise the service
392 * requesting the password won't notice the error and will wait
394 log_error_errno(r
, "Failed to process password: %m");
400 r
= ppoll_usec(pollfd
, _FD_MAX
, timeout
);
406 if (pollfd
[FD_INOTIFY
].revents
!= 0)
407 (void) flush_fd(notify
);
409 if (pollfd
[FD_SIGNAL
].revents
!= 0)
416 static int help(void) {
417 _cleanup_free_
char *link
= NULL
;
420 r
= terminal_urlify_man("systemd-tty-ask-password-agent", "1", &link
);
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
,
444 static int parse_argv(int argc
, char *argv
[]) {
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
},
473 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
484 arg_action
= ACTION_LIST
;
488 arg_action
= ACTION_QUERY
;
492 arg_action
= ACTION_WATCH
;
496 arg_action
= ACTION_WALL
;
508 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
509 "Empty console device path is not allowed.");
519 assert_not_reached();
523 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
524 "%s takes no arguments.", program_invocation_short_name
);
526 if (arg_plymouth
|| arg_console
) {
528 if (!IN_SET(arg_action
, ACTION_QUERY
, ACTION_WATCH
))
529 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
530 "Options --query and --watch conflict.");
532 if (arg_plymouth
&& arg_console
)
533 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
534 "Options --plymouth and --console conflict.");
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
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
,
551 static const struct sigaction sighup
= {
552 .sa_handler
= SIG_DFL
,
553 .sa_flags
= SA_RESTART
,
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);
561 r
= safe_fork("(sd-passwd)", FORK_RESET_SIGNALS
|FORK_LOG
, ret_pid
);
565 assert_se(prctl(PR_SET_PDEATHSIG
, SIGHUP
) >= 0);
567 STRV_FOREACH(i
, arguments
) {
570 if (!streq(*i
, "--console"))
573 k
= strjoin("--console=", tty
);
579 free_and_replace(*i
, k
);
582 execv(SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH
, arguments
);
589 static void terminate_agents(Set
*pids
) {
595 * Request termination of the remaining processes as those
596 * are not required anymore.
599 (void) kill(PTR_TO_PID(p
), SIGTERM
);
602 * Collect the processes which have go away.
604 assert_se(sigemptyset(&set
) >= 0);
605 assert_se(sigaddset(&set
, SIGCHLD
) >= 0);
607 while (!set_isempty(pids
)) {
608 siginfo_t status
= {};
610 r
= waitid(P_ALL
, 0, &status
, WEXITED
|WNOHANG
);
611 if (r
< 0 && errno
== EINTR
)
614 if (r
== 0 && status
.si_pid
> 0) {
615 set_remove(pids
, PID_TO_PTR(status
.si_pid
));
619 signum
= sigtimedwait(&set
, NULL
, TIMESPEC_STORE(50 * USEC_PER_MSEC
));
622 log_error_errno(errno
, "sigtimedwait() failed: %m");
625 assert(signum
== SIGCHLD
);
629 * Kill hanging processes.
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
);
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
= {};
644 r
= get_kernel_consoles(&consoles
);
646 return log_error_errno(r
, "Failed to determine devices of /dev/console: %m");
648 pids
= set_new(NULL
);
652 arguments
= strv_copy(argv
);
656 /* Start an agent on each console. */
657 STRV_FOREACH(tty
, consoles
) {
658 r
= ask_on_this_console(*tty
, &pid
, arguments
);
662 if (set_put(pids
, PID_TO_PTR(pid
)) < 0)
666 /* Wait for an agent to exit. */
670 if (waitid(P_ALL
, 0, &status
, WEXITED
) < 0) {
674 return log_error_errno(errno
, "waitid() failed: %m");
677 set_remove(pids
, PID_TO_PTR(status
.si_pid
));
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
);
684 terminate_agents(pids
);
688 static int run(int argc
, char *argv
[]) {
695 r
= parse_argv(argc
, argv
);
699 if (arg_console
&& !arg_device
)
701 * Spawn a separate process for each console device.
703 return ask_on_consoles(argv
);
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.
712 (void) release_terminal();
715 return process_and_watch_password_files(!IN_SET(arg_action
, ACTION_QUERY
, ACTION_LIST
));
718 DEFINE_MAIN_FUNCTION(run
);