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"
21 #include "conf-parser.h"
23 #include "dirent-util.h"
24 #include "exit-status.h"
31 #include "main-func.h"
32 #include "memory-util.h"
34 #include "path-util.h"
35 #include "pretty-print.h"
36 #include "process-util.h"
38 #include "signal-util.h"
39 #include "socket-util.h"
40 #include "string-util.h"
42 #include "terminal-util.h"
43 #include "utmp-wtmp.h"
50 } arg_action
= ACTION_QUERY
;
52 static bool arg_plymouth
= false;
53 static bool arg_console
= false;
54 static const char *arg_device
= NULL
;
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
;
61 size_t packet_length
= 1;
68 r
= sockaddr_un_set_path(&sa
.un
, socket_name
);
73 STRV_FOREACH(p
, passwords
)
74 packet_length
+= strlen(*p
) + 1;
76 packet
= new(char, packet_length
);
83 STRV_FOREACH(p
, passwords
)
84 d
= stpcpy(d
, *p
) + 1;
86 socket_fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0);
88 return log_debug_errno(errno
, "socket(): %m");
90 n
= sendto(socket_fd
, packet
, packet_length
, MSG_NOSIGNAL
, &sa
.sa
, sa_len
);
92 return log_debug_errno(errno
, "sendto(): %m");
97 static bool wall_tty_match(const char *path
, void *userdata
) {
98 _cleanup_free_
char *p
= NULL
;
99 _cleanup_close_
int fd
= -1;
102 if (!path_is_absolute(path
))
103 path
= strjoina("/dev/", 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
,
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 r
= ask_password_tty(tty_fd
, message
, NULL
, until
, flags
, flag_file
, ret
);
163 tty_fd
= safe_close(tty_fd
);
167 log_info("Password query on %s finished successfully.", con
);
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;
179 const ConfigTableItem items
[] = {
180 { "Ask", "Socket", config_parse_string
, 0, &socket_name
},
181 { "Ask", "NotAfter", config_parse_uint64
, 0, ¬_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
},
194 r
= config_parse(NULL
, filename
, NULL
,
196 config_item_table_lookup
, items
,
197 CONFIG_PARSE_RELAXED
|CONFIG_PARSE_WARN
,
204 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
205 "Invalid password file %s", filename
);
207 if (not_after
> 0 && now(CLOCK_MONOTONIC
) > not_after
)
210 if (pid
> 0 && !pid_is_alive(pid
))
213 switch (arg_action
) {
215 printf("'%s' (PID %u)\n", strna(message
), pid
);
219 _cleanup_free_
char *wall
= NULL
;
222 "Password entry required for \'%s\' (PID %u).\r\n"
223 "Please enter password with the systemd-tty-ask-password-agent tool.",
228 (void) utmp_wall(wall
, NULL
, NULL
, wall_tty_match
, NULL
);
233 _cleanup_strv_free_erase_
char **passwords
= NULL
;
234 AskPasswordFlags flags
= 0;
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
);
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
);
249 r
= ask_password_plymouth(message
, not_after
, flags
, filename
, &passwords
);
251 r
= agent_ask_password_tty(message
, not_after
, flags
, filename
, &passwords
);
253 /* If the query went away, that's OK */
254 if (IN_SET(r
, -ETIME
, -ENOENT
))
257 return log_error_errno(r
, "Failed to query password: %m");
260 if (strv_isempty(passwords
))
263 r
= send_passwords(socket_name
, passwords
);
265 return log_error_errno(r
, "Failed to send: %m");
272 static int wall_tty_block(void) {
273 _cleanup_free_
char *p
= NULL
;
277 r
= get_ctty_devnr(0, &devnr
);
278 if (r
== -ENXIO
) /* We have no controlling tty */
281 return log_error_errno(r
, "Failed to get controlling TTY: %m");
283 if (asprintf(&p
, "/run/systemd/ask-password-block/%u:%u", major(devnr
), minor(devnr
)) < 0)
286 (void) mkdir_parents_label(p
, 0700);
287 (void) mkfifo(p
, 0600);
289 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
291 return log_debug_errno(errno
, "Failed to open %s: %m", p
);
296 static int process_password_files(void) {
297 _cleanup_closedir_
DIR *d
= NULL
;
301 d
= opendir("/run/systemd/ask-password");
306 return log_error_errno(errno
, "Failed to open /run/systemd/ask-password: %m");
309 FOREACH_DIRENT(de
, d
, return log_error_errno(errno
, "Failed to read directory: %m")) {
310 _cleanup_free_
char *p
= NULL
;
313 /* We only support /run on tmpfs, hence we can rely on
314 * d_type to be reliable */
316 if (de
->d_type
!= DT_REG
)
319 if (!startswith(de
->d_name
, "ask."))
322 p
= path_join("/run/systemd/ask-password", de
->d_name
);
326 q
= process_one_password_file(p
);
334 static int process_and_watch_password_files(bool watch
) {
341 _unused_ _cleanup_close_
int tty_block_fd
= -1;
342 _cleanup_close_
int notify
= -1, signal_fd
= -1;
343 struct pollfd pollfd
[_FD_MAX
];
347 tty_block_fd
= wall_tty_block();
349 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
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);
356 signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
358 return log_error_errno(errno
, "Failed to allocate signal file descriptor: %m");
360 pollfd
[FD_SIGNAL
] = (struct pollfd
) { .fd
= signal_fd
, .events
= POLLIN
};
362 notify
= inotify_init1(IN_CLOEXEC
);
364 return log_error_errno(errno
, "Failed to allocate directory watch: %m");
366 r
= inotify_add_watch_and_warn(notify
, "/run/systemd/ask-password", IN_CLOSE_WRITE
|IN_MOVED_TO
);
370 pollfd
[FD_INOTIFY
] = (struct pollfd
) { .fd
= notify
, .events
= POLLIN
};
374 usec_t timeout
= USEC_INFINITY
;
376 r
= process_password_files();
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. */
384 /* FIXME: we should do something here since otherwise the service
385 * requesting the password won't notice the error and will wait
387 log_error_errno(r
, "Failed to process password: %m");
393 r
= ppoll_usec(pollfd
, _FD_MAX
, timeout
);
399 if (pollfd
[FD_INOTIFY
].revents
!= 0)
400 (void) flush_fd(notify
);
402 if (pollfd
[FD_SIGNAL
].revents
!= 0)
409 static int help(void) {
410 _cleanup_free_
char *link
= NULL
;
413 r
= terminal_urlify_man("systemd-tty-ask-password-agent", "1", &link
);
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
,
437 static int parse_argv(int argc
, char *argv
[]) {
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
},
466 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
477 arg_action
= ACTION_LIST
;
481 arg_action
= ACTION_QUERY
;
485 arg_action
= ACTION_WATCH
;
489 arg_action
= ACTION_WALL
;
501 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
502 "Empty console device path is not allowed.");
512 assert_not_reached();
516 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
517 "%s takes no arguments.", program_invocation_short_name
);
519 if (arg_plymouth
|| arg_console
) {
521 if (!IN_SET(arg_action
, ACTION_QUERY
, ACTION_WATCH
))
522 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
523 "Options --query and --watch conflict.");
525 if (arg_plymouth
&& arg_console
)
526 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
527 "Options --plymouth and --console conflict.");
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
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
,
544 static const struct sigaction sighup
= {
545 .sa_handler
= SIG_DFL
,
546 .sa_flags
= SA_RESTART
,
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);
554 r
= safe_fork("(sd-passwd)", FORK_RESET_SIGNALS
|FORK_LOG
, ret_pid
);
560 assert_se(prctl(PR_SET_PDEATHSIG
, SIGHUP
) >= 0);
562 STRV_FOREACH(i
, arguments
) {
565 if (!streq(*i
, "--console"))
568 k
= strjoin("--console=", tty
);
574 free_and_replace(*i
, k
);
577 execv(SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH
, arguments
);
584 static void terminate_agents(Set
*pids
) {
586 siginfo_t status
= {};
592 * Request termination of the remaining processes as those
593 * are not required anymore.
596 (void) kill(PTR_TO_PID(p
), SIGTERM
);
599 * Collect the processes which have go away.
601 assert_se(sigemptyset(&set
) >= 0);
602 assert_se(sigaddset(&set
, SIGCHLD
) >= 0);
603 timespec_store(&ts
, 50 * USEC_PER_MSEC
);
605 while (!set_isempty(pids
)) {
608 r
= waitid(P_ALL
, 0, &status
, WEXITED
|WNOHANG
);
609 if (r
< 0 && errno
== EINTR
)
612 if (r
== 0 && status
.si_pid
> 0) {
613 set_remove(pids
, PID_TO_PTR(status
.si_pid
));
617 signum
= sigtimedwait(&set
, NULL
, &ts
);
620 log_error_errno(errno
, "sigtimedwait() failed: %m");
623 assert(signum
== SIGCHLD
);
627 * Kill hanging processes.
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
);
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
= {};
643 r
= get_kernel_consoles(&consoles
);
645 return log_error_errno(r
, "Failed to determine devices of /dev/console: %m");
647 pids
= set_new(NULL
);
651 arguments
= strv_copy(argv
);
655 /* Start an agent on each console. */
656 STRV_FOREACH(tty
, consoles
) {
657 r
= ask_on_this_console(*tty
, &pid
, arguments
);
661 if (set_put(pids
, PID_TO_PTR(pid
)) < 0)
665 /* Wait for an agent to exit. */
669 if (waitid(P_ALL
, 0, &status
, WEXITED
) < 0) {
673 return log_error_errno(errno
, "waitid() failed: %m");
676 set_remove(pids
, PID_TO_PTR(status
.si_pid
));
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
);
683 terminate_agents(pids
);
687 static int run(int argc
, char *argv
[]) {
694 r
= parse_argv(argc
, argv
);
698 if (arg_console
&& !arg_device
)
700 * Spawn a separate process for each console device.
702 return ask_on_consoles(argv
);
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.
711 (void) release_terminal();
714 return process_and_watch_password_files(!IN_SET(arg_action
, ACTION_QUERY
, ACTION_LIST
));
717 DEFINE_MAIN_FUNCTION(run
);