1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 Copyright © 2015 Werner Fink
10 #include <sys/prctl.h>
11 #include <sys/signalfd.h>
16 #include "alloc-util.h"
17 #include "ask-password-api.h"
19 #include "conf-parser.h"
20 #include "daemon-util.h"
21 #include "devnum-util.h"
22 #include "dirent-util.h"
23 #include "errno-util.h"
24 #include "exit-status.h"
26 #include "format-util.h"
28 #include "inotify-util.h"
30 #include "main-func.h"
31 #include "mkdir-label.h"
32 #include "path-util.h"
33 #include "pretty-print.h"
34 #include "process-util.h"
36 #include "signal-util.h"
37 #include "socket-util.h"
38 #include "static-destruct.h"
39 #include "string-util.h"
41 #include "terminal-util.h"
42 #include "time-util.h"
50 } arg_action
= ACTION_QUERY
;
52 static bool arg_plymouth
= false;
53 static bool arg_console
= false;
54 static char *arg_device
= NULL
;
56 STATIC_DESTRUCTOR_REGISTER(arg_device
, freep
);
58 static int send_passwords(const char *socket_name
, char **passwords
) {
63 union sockaddr_union sa
;
64 r
= sockaddr_un_set_path(&sa
.un
, socket_name
);
69 size_t packet_length
= 1;
70 STRV_FOREACH(p
, passwords
)
71 packet_length
+= strlen(*p
) + 1;
73 _cleanup_(erase_and_freep
) char *packet
= new(char, packet_length
);
80 STRV_FOREACH(p
, passwords
)
81 d
= stpcpy(d
, *p
) + 1;
83 _cleanup_close_
int socket_fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0);
85 return log_debug_errno(errno
, "socket(): %m");
87 ssize_t n
= sendto(socket_fd
, packet
, packet_length
, MSG_NOSIGNAL
, &sa
.sa
, sa_len
);
89 return log_debug_errno(errno
, "sendto(): %m");
94 static bool wall_tty_match(const char *path
, bool is_local
, void *userdata
) {
95 assert(path_is_absolute(path
));
98 if (lstat(path
, &st
) < 0) {
99 log_debug_errno(errno
, "Failed to stat TTY '%s', not restricting wall: %m", path
);
103 if (!S_ISCHR(st
.st_mode
)) {
104 log_debug("TTY '%s' is not a character device, not restricting wall.", path
);
108 /* We use named pipes to ensure that wall messages suggesting password entry are not printed over
109 * password prompts already shown. We use the fact here that opening a pipe in non-blocking mode for
110 * write-only will succeed only if there's some writer behind it. Using pipes has the advantage that
111 * the block will automatically go away if the process dies. */
113 _cleanup_free_
char *p
= NULL
;
114 if (asprintf(&p
, "/run/systemd/ask-password-block/" DEVNUM_FORMAT_STR
, DEVNUM_FORMAT_VAL(st
.st_rdev
)) < 0) {
119 _cleanup_close_
int fd
= open(p
, O_WRONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
121 log_debug_errno(errno
, "Failed to open the wall pipe for TTY '%s', not restricting wall: %m", path
);
125 /* What, we managed to open the pipe? Then this tty is filtered. */
129 static int agent_ask_password_tty(
132 AskPasswordFlags flags
,
133 const char *flag_file
,
136 int tty_fd
= -EBADF
, r
;
137 const char *con
= arg_device
?: "/dev/console";
140 tty_fd
= acquire_terminal(con
, ACQUIRE_TERMINAL_WAIT
|ACQUIRE_TERMINAL_WATCH_SIGTERM
, USEC_INFINITY
);
142 return log_error_errno(tty_fd
, "Failed to acquire %s: %m", con
);
144 (void) terminal_reset_defensive_locked(tty_fd
, TERMINAL_RESET_SWITCH_TO_TEXT
);
146 log_info("Starting password query on %s.", con
);
149 AskPasswordRequest req
= {
152 .flag_file
= flag_file
,
157 r
= ask_password_tty(&req
, flags
, ret
);
161 tty_fd
= safe_close(tty_fd
);
165 log_info("Password query on %s finished successfully.", con
);
171 static int process_one_password_file(const char *filename
, FILE *f
) {
172 _cleanup_free_
char *socket_name
= NULL
, *message
= NULL
;
173 bool accept_cached
= false, echo
= false, silent
= false;
174 uint64_t not_after
= 0;
177 const ConfigTableItem items
[] = {
178 { "Ask", "Socket", config_parse_string
, CONFIG_PARSE_STRING_SAFE
, &socket_name
},
179 { "Ask", "NotAfter", config_parse_uint64
, 0, ¬_after
},
180 { "Ask", "Message", config_parse_string
, 0, &message
},
181 { "Ask", "PID", config_parse_pid
, 0, &pid
},
182 { "Ask", "AcceptCached", config_parse_bool
, 0, &accept_cached
},
183 { "Ask", "Echo", config_parse_bool
, 0, &echo
},
184 { "Ask", "Silent", config_parse_bool
, 0, &silent
},
193 r
= config_parse(/* unit= */ NULL
,
196 /* sections= */ "Ask\0",
197 config_item_table_lookup
,
199 CONFIG_PARSE_RELAXED
|CONFIG_PARSE_WARN
,
200 /* userdata= */ NULL
,
201 /* ret_stat= */ NULL
);
206 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
207 "Invalid password file %s", filename
);
209 if (not_after
> 0 && now(CLOCK_MONOTONIC
) > not_after
)
212 if (pid
> 0 && pid_is_alive(pid
) <= 0)
215 switch (arg_action
) {
217 printf("'%s' (PID " PID_FMT
")\n", strna(message
), pid
);
221 _cleanup_free_
char *msg
= NULL
;
224 "Password entry required for \'%s\' (PID " PID_FMT
").\r\n"
225 "Please enter password with the systemd-tty-ask-password-agent tool.",
230 (void) wall(msg
, NULL
, NULL
, wall_tty_match
, NULL
);
235 _cleanup_strv_free_erase_
char **passwords
= NULL
;
236 AskPasswordFlags flags
= 0;
238 if (access(socket_name
, W_OK
) < 0) {
239 if (arg_action
== ACTION_QUERY
)
240 log_info("Not querying '%s' (PID " PID_FMT
"), lacking privileges.", strna(message
), pid
);
245 SET_FLAG(flags
, ASK_PASSWORD_ACCEPT_CACHED
, accept_cached
);
246 SET_FLAG(flags
, ASK_PASSWORD_CONSOLE_COLOR
, arg_console
);
247 SET_FLAG(flags
, ASK_PASSWORD_ECHO
, echo
);
248 SET_FLAG(flags
, ASK_PASSWORD_SILENT
, silent
);
250 /* Allow providing a password via env var, for debugging purposes */
251 const char *e
= secure_getenv("SYSTEMD_ASK_PASSWORD_AGENT_PASSWORD");
253 passwords
= strv_new(e
);
258 AskPasswordRequest req
= {
261 .flag_file
= filename
,
266 r
= ask_password_plymouth(&req
, flags
, &passwords
);
268 r
= agent_ask_password_tty(message
, not_after
, flags
, filename
, &passwords
);
270 /* If the query went away, that's OK */
271 if (IN_SET(r
, -ETIME
, -ENOENT
))
274 return log_error_errno(r
, "Failed to query password: %m");
278 assert(!strv_isempty(passwords
));
279 r
= send_passwords(socket_name
, passwords
);
281 return log_error_errno(r
, "Failed to send: %m");
288 static int wall_tty_block(void) {
289 _cleanup_free_
char *p
= NULL
;
293 r
= get_ctty_devnr(0, &devnr
);
294 if (r
== -ENXIO
) /* We have no controlling tty */
297 return log_error_errno(r
, "Failed to get controlling TTY: %m");
299 if (asprintf(&p
, "/run/systemd/ask-password-block/%u:%u", major(devnr
), minor(devnr
)) < 0)
302 (void) mkdir_parents_label(p
, 0700);
303 (void) mkfifo(p
, 0600);
305 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
307 return log_debug_errno(errno
, "Failed to open %s: %m", p
);
312 static int process_password_files(const char *path
) {
313 _cleanup_closedir_
DIR *d
= NULL
;
323 return log_error_errno(errno
, "Failed to open '%s': %m", path
);
326 FOREACH_DIRENT(de
, d
, return log_error_errno(errno
, "Failed to read directory '%s': %m", path
)) {
327 _cleanup_free_
char *p
= NULL
;
329 if (!IN_SET(de
->d_type
, DT_REG
, DT_UNKNOWN
))
332 if (!startswith(de
->d_name
, "ask."))
335 p
= path_join(path
, de
->d_name
);
339 _cleanup_fclose_
FILE *f
= NULL
;
340 r
= xfopenat(dirfd(d
), de
->d_name
, "re", O_NOFOLLOW
, &f
);
342 log_warning_errno(r
, "Failed to open '%s', ignoring: %m", p
);
346 RET_GATHER(ret
, process_one_password_file(p
, f
));
352 static int process_and_watch_password_files(bool watch
) {
359 _cleanup_free_
char *user_ask_password_directory
= NULL
;
360 _unused_ _cleanup_close_
int tty_block_fd
= -EBADF
;
361 _cleanup_close_
int notify
= -EBADF
, signal_fd
= -EBADF
;
362 struct pollfd pollfd
[_FD_MAX
];
366 tty_block_fd
= wall_tty_block();
368 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
370 r
= acquire_user_ask_password_directory(&user_ask_password_directory
);
372 return log_error_errno(r
, "Failed to determine per-user password directory: %m");
374 (void) mkdir_p_label(user_ask_password_directory
, 0755);
376 assert_se(sigemptyset(&mask
) >= 0);
377 assert_se(sigset_add_many(&mask
, SIGTERM
) >= 0);
378 assert_se(sigprocmask(SIG_SETMASK
, &mask
, NULL
) >= 0);
381 signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
383 return log_error_errno(errno
, "Failed to allocate signal file descriptor: %m");
385 pollfd
[FD_SIGNAL
] = (struct pollfd
) { .fd
= signal_fd
, .events
= POLLIN
};
387 notify
= inotify_init1(IN_CLOEXEC
);
389 return log_error_errno(errno
, "Failed to allocate directory watch: %m");
391 r
= inotify_add_watch_and_warn(notify
, "/run/systemd/ask-password", IN_CLOSE_WRITE
|IN_MOVED_TO
|IN_ONLYDIR
);
395 if (user_ask_password_directory
) {
396 r
= inotify_add_watch_and_warn(notify
, user_ask_password_directory
, IN_CLOSE_WRITE
|IN_MOVED_TO
|IN_ONLYDIR
);
401 pollfd
[FD_INOTIFY
] = (struct pollfd
) { .fd
= notify
, .events
= POLLIN
};
404 _unused_
_cleanup_(notify_on_cleanup
) const char *notify_stop
=
405 notify_start(NOTIFY_READY_MESSAGE
, NOTIFY_STOPPING_MESSAGE
);
408 usec_t timeout
= USEC_INFINITY
;
410 r
= process_password_files("/run/systemd/ask-password");
411 if (user_ask_password_directory
)
412 RET_GATHER(r
, process_password_files(user_ask_password_directory
));
414 /* Disable poll() timeout since at least one password has been skipped and therefore
415 * one file remains and is unlikely to trigger any events. */
418 /* FIXME: we should do something here since otherwise the service
419 * requesting the password won't notice the error and will wait
421 log_warning_errno(r
, "Failed to process password, ignoring: %m");
426 r
= ppoll_usec(pollfd
, _FD_MAX
, timeout
);
432 if (pollfd
[FD_INOTIFY
].revents
!= 0)
433 (void) flush_fd(notify
);
435 if (pollfd
[FD_SIGNAL
].revents
!= 0)
442 static int help(void) {
443 _cleanup_free_
char *link
= NULL
;
446 r
= terminal_urlify_man("systemd-tty-ask-password-agent", "1", &link
);
450 printf("%s [OPTIONS...]\n\n"
451 "%sProcess system password requests.%s\n\n"
452 " -h --help Show this help\n"
453 " --version Show package version\n"
454 " --list Show pending password requests\n"
455 " --query Process pending password requests\n"
456 " --watch Continuously process password requests\n"
457 " --wall Continuously forward password requests to wall\n"
458 " --plymouth Ask question with Plymouth instead of on TTY\n"
459 " --console[=DEVICE] Ask question on /dev/console (or DEVICE if specified)\n"
460 " instead of the current TTY\n"
461 "\nSee the %s for details.\n",
462 program_invocation_short_name
,
470 static int parse_argv(int argc
, char *argv
[]) {
482 static const struct option options
[] = {
483 { "help", no_argument
, NULL
, 'h' },
484 { "version", no_argument
, NULL
, ARG_VERSION
},
485 { "list", no_argument
, NULL
, ARG_LIST
},
486 { "query", no_argument
, NULL
, ARG_QUERY
},
487 { "watch", no_argument
, NULL
, ARG_WATCH
},
488 { "wall", no_argument
, NULL
, ARG_WALL
},
489 { "plymouth", no_argument
, NULL
, ARG_PLYMOUTH
},
490 { "console", optional_argument
, NULL
, ARG_CONSOLE
},
499 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
510 arg_action
= ACTION_LIST
;
514 arg_action
= ACTION_QUERY
;
518 arg_action
= ACTION_WATCH
;
522 arg_action
= ACTION_WALL
;
533 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
534 "Empty console device path is not allowed.");
536 r
= free_and_strdup_warn(&arg_device
, optarg
);
546 assert_not_reached();
550 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
551 "%s takes no arguments.", program_invocation_short_name
);
553 if (arg_plymouth
|| arg_console
) {
555 if (!IN_SET(arg_action
, ACTION_QUERY
, ACTION_WATCH
))
556 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
557 "Options --query and --watch conflict.");
559 if (arg_plymouth
&& arg_console
)
560 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
561 "Options --plymouth and --console conflict.");
568 * To be able to ask on all terminal devices of /dev/console the devices are collected. If more than one
569 * device is found, then on each of the terminals an inquiring task is forked. Every task has its own session
570 * and its own controlling terminal. If one of the tasks does handle a password, the remaining tasks will be
573 static int ask_on_this_console(const char *tty
, char **arguments
, pid_t
*ret_pid
) {
580 assert_se(sigaction(SIGCHLD
, &sigaction_nop_nocldstop
, NULL
) >= 0);
581 assert_se(sigaction(SIGHUP
, &sigaction_default
, NULL
) >= 0);
582 assert_se(sigprocmask_many(SIG_UNBLOCK
, NULL
, SIGHUP
, SIGCHLD
) >= 0);
584 r
= safe_fork("(sd-passwd)", FORK_RESET_SIGNALS
|FORK_KEEP_NOTIFY_SOCKET
|FORK_LOG
, ret_pid
);
588 assert_se(prctl(PR_SET_PDEATHSIG
, SIGHUP
) >= 0);
590 STRV_FOREACH(i
, arguments
) {
593 if (!streq(*i
, "--console"))
596 k
= strjoin("--console=", tty
);
602 free_and_replace(*i
, k
);
605 execv(SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH
, arguments
);
612 static void terminate_agents(Set
*pids
) {
618 * Request termination of the remaining processes as those
619 * are not required anymore.
622 (void) kill(PTR_TO_PID(p
), SIGTERM
);
625 * Collect the processes which have go away.
627 assert_se(sigemptyset(&set
) >= 0);
628 assert_se(sigaddset(&set
, SIGCHLD
) >= 0);
630 while (!set_isempty(pids
)) {
631 siginfo_t status
= {};
633 r
= waitid(P_ALL
, 0, &status
, WEXITED
|WNOHANG
);
634 if (r
< 0 && errno
== EINTR
)
637 if (r
== 0 && status
.si_pid
> 0) {
638 set_remove(pids
, PID_TO_PTR(status
.si_pid
));
642 signum
= sigtimedwait(&set
, NULL
, TIMESPEC_STORE(50 * USEC_PER_MSEC
));
645 log_error_errno(errno
, "sigtimedwait() failed: %m");
648 assert(signum
== SIGCHLD
);
652 * Kill hanging processes.
654 SET_FOREACH(p
, pids
) {
655 log_warning("Failed to terminate child %d, killing it", PTR_TO_PID(p
));
656 (void) kill(PTR_TO_PID(p
), SIGKILL
);
660 static int ask_on_consoles(char *argv
[]) {
661 _cleanup_strv_free_
char **consoles
= NULL
, **arguments
= NULL
;
662 _cleanup_set_free_ Set
*pids
= NULL
;
668 r
= get_kernel_consoles(&consoles
);
670 return log_error_errno(r
, "Failed to determine devices of /dev/console: %m");
672 /* No need to spawn subprocesses, there's only one console or using /dev/console as fallback */
673 arg_device
= TAKE_PTR(consoles
[0]);
677 pids
= set_new(NULL
);
681 arguments
= strv_copy(argv
);
685 /* Grant agents we spawn notify access too, so that once an agent establishes inotify watch
686 * READY=1 from them is accepted by service manager (see process_and_watch_password_files()).
688 * Note that when any agent exits STOPPING=1 would also be sent, but that's utterly what we want,
689 * i.e. the password is answered on one console and other agents get killed below. */
690 (void) sd_notify(/* unset_environment = */ false, "NOTIFYACCESS=all");
692 /* Start an agent on each console. */
693 STRV_FOREACH(tty
, consoles
) {
696 r
= ask_on_this_console(*tty
, arguments
, &pid
);
700 if (set_put(pids
, PID_TO_PTR(pid
)) < 0)
704 /* Wait for an agent to exit. */
706 siginfo_t status
= {};
708 if (waitid(P_ALL
, 0, &status
, WEXITED
) < 0) {
712 return log_error_errno(errno
, "Failed to wait for console ask-password agent: %m");
715 if (!is_clean_exit(status
.si_code
, status
.si_status
, EXIT_CLEAN_DAEMON
, NULL
))
716 log_error("Password agent failed with: %d", status
.si_status
);
718 set_remove(pids
, PID_TO_PTR(status
.si_pid
));
722 terminate_agents(pids
);
726 static int run(int argc
, char *argv
[]) {
733 r
= parse_argv(argc
, argv
);
737 /* Spawn a separate process for each console device if there're multiple. */
738 if (arg_console
&& !arg_device
) {
739 r
= ask_on_consoles(argv
);
747 /* Later on, a controlling terminal will be acquired, therefore the current process has to
748 * become a session leader and should not have a controlling terminal already. */
749 terminal_detach_session();
751 return process_and_watch_password_files(!IN_SET(arg_action
, ACTION_QUERY
, ACTION_LIST
));
754 DEFINE_MAIN_FUNCTION(run
);