1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright © 2015 Werner Fink
13 #include <sys/prctl.h>
14 #include <sys/signalfd.h>
16 #include <sys/types.h>
21 #include "alloc-util.h"
22 #include "ask-password-api.h"
23 #include "conf-parser.h"
25 #include "dirent-util.h"
26 #include "exit-status.h"
33 #include "main-func.h"
34 #include "memory-util.h"
36 #include "path-util.h"
37 #include "pretty-print.h"
38 #include "process-util.h"
40 #include "signal-util.h"
41 #include "socket-util.h"
42 #include "string-util.h"
44 #include "terminal-util.h"
45 #include "utmp-wtmp.h"
52 } arg_action
= ACTION_QUERY
;
54 static bool arg_plymouth
= false;
55 static bool arg_console
= false;
56 static const char *arg_device
= NULL
;
58 static int send_passwords(const char *socket_name
, char **passwords
) {
59 _cleanup_(erase_and_freep
) char *packet
= NULL
;
60 _cleanup_close_
int socket_fd
= -1;
61 union sockaddr_union sa
= {};
62 size_t packet_length
= 1;
69 salen
= 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
, salen
);
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
,
149 const char *con
= arg_device
?: "/dev/console";
151 tty_fd
= acquire_terminal(con
, ACQUIRE_TERMINAL_WAIT
, USEC_INFINITY
);
153 return log_error_errno(tty_fd
, "Failed to acquire %s: %m", con
);
155 r
= reset_terminal_fd(tty_fd
, true);
157 log_warning_errno(r
, "Failed to reset terminal, ignoring: %m");
161 r
= ask_password_tty(tty_fd
, message
, NULL
, until
, flags
, flag_file
, ret
);
164 tty_fd
= safe_close(tty_fd
);
171 static int process_one_password_file(const char *filename
) {
172 _cleanup_free_
char *socket_name
= NULL
, *message
= NULL
;
173 bool accept_cached
= false, echo
= false;
174 uint64_t not_after
= 0;
177 const ConfigTableItem items
[] = {
178 { "Ask", "Socket", config_parse_string
, 0, &socket_name
},
179 { "Ask", "NotAfter", config_parse_uint64
, 0, ¬_after
},
180 { "Ask", "Message", config_parse_string
, 0, &message
},
181 { "Ask", "PID", config_parse_unsigned
, 0, &pid
},
182 { "Ask", "AcceptCached", config_parse_bool
, 0, &accept_cached
},
183 { "Ask", "Echo", config_parse_bool
, 0, &echo
},
191 r
= config_parse(NULL
, filename
, NULL
,
193 config_item_table_lookup
, items
,
194 CONFIG_PARSE_RELAXED
|CONFIG_PARSE_WARN
, NULL
);
199 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
200 "Invalid password file %s", filename
);
202 if (not_after
> 0 && now(CLOCK_MONOTONIC
) > not_after
)
205 if (pid
> 0 && !pid_is_alive(pid
))
208 switch (arg_action
) {
210 printf("'%s' (PID %u)\n", message
, pid
);
214 _cleanup_free_
char *wall
= NULL
;
217 "Password entry required for \'%s\' (PID %u).\r\n"
218 "Please enter password with the systemd-tty-ask-password-agent tool.",
223 (void) utmp_wall(wall
, NULL
, NULL
, wall_tty_match
, NULL
);
228 _cleanup_strv_free_erase_
char **passwords
= NULL
;
229 AskPasswordFlags flags
= 0;
231 if (access(socket_name
, W_OK
) < 0) {
232 if (arg_action
== ACTION_QUERY
)
233 log_info("Not querying '%s' (PID %u), lacking privileges.", message
, pid
);
238 SET_FLAG(flags
, ASK_PASSWORD_ACCEPT_CACHED
, accept_cached
);
239 SET_FLAG(flags
, ASK_PASSWORD_CONSOLE_COLOR
, arg_console
);
240 SET_FLAG(flags
, ASK_PASSWORD_ECHO
, echo
);
243 r
= ask_password_plymouth(message
, not_after
, flags
, filename
, &passwords
);
245 r
= agent_ask_password_tty(message
, not_after
, flags
, filename
, &passwords
);
248 /* If the query went away, that's OK */
249 if (IN_SET(r
, -ETIME
, -ENOENT
))
252 return log_error_errno(r
, "Failed to query password: %m");
255 if (strv_isempty(passwords
))
258 r
= send_passwords(socket_name
, passwords
);
260 return log_error_errno(r
, "Failed to send: %m");
268 static int wall_tty_block(void) {
269 _cleanup_free_
char *p
= NULL
;
273 r
= get_ctty_devnr(0, &devnr
);
274 if (r
== -ENXIO
) /* We have no controlling tty */
277 return log_error_errno(r
, "Failed to get controlling TTY: %m");
279 if (asprintf(&p
, "/run/systemd/ask-password-block/%u:%u", major(devnr
), minor(devnr
)) < 0)
282 (void) mkdir_parents_label(p
, 0700);
283 (void) mkfifo(p
, 0600);
285 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
287 return log_debug_errno(errno
, "Failed to open %s: %m", p
);
292 static int process_password_files(void) {
293 _cleanup_closedir_
DIR *d
;
297 d
= opendir("/run/systemd/ask-password");
302 return log_error_errno(errno
, "Failed to open /run/systemd/ask-password: %m");
305 FOREACH_DIRENT(de
, d
, return log_error_errno(errno
, "Failed to read directory: %m")) {
306 _cleanup_free_
char *p
= NULL
;
309 /* We only support /run on tmpfs, hence we can rely on
310 * d_type to be reliable */
312 if (de
->d_type
!= DT_REG
)
315 if (!startswith(de
->d_name
, "ask."))
318 p
= path_join("/run/systemd/ask-password", de
->d_name
);
322 q
= process_one_password_file(p
);
330 static int process_and_watch_password_files(bool watch
) {
337 _cleanup_close_
int notify
= -1, signal_fd
= -1, tty_block_fd
= -1;
338 struct pollfd pollfd
[_FD_MAX
];
342 tty_block_fd
= wall_tty_block();
344 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
346 assert_se(sigemptyset(&mask
) >= 0);
347 assert_se(sigset_add_many(&mask
, SIGTERM
, -1) >= 0);
348 assert_se(sigprocmask(SIG_SETMASK
, &mask
, NULL
) >= 0);
351 signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
353 return log_error_errno(errno
, "Failed to allocate signal file descriptor: %m");
355 pollfd
[FD_SIGNAL
] = (struct pollfd
) { .fd
= signal_fd
, .events
= POLLIN
};
357 notify
= inotify_init1(IN_CLOEXEC
);
359 return log_error_errno(errno
, "Failed to allocate directory watch: %m");
361 r
= inotify_add_watch_and_warn(notify
, "/run/systemd/ask-password", IN_CLOSE_WRITE
|IN_MOVED_TO
);
365 pollfd
[FD_INOTIFY
] = (struct pollfd
) { .fd
= notify
, .events
= POLLIN
};
371 r
= process_password_files();
374 /* Disable poll() timeout since at least one password has
375 * been skipped and therefore one file remains and is
376 * unlikely to trigger any events. */
379 /* FIXME: we should do something here since otherwise the service
380 * requesting the password won't notice the error and will wait
382 log_error_errno(r
, "Failed to process password: %m");
388 if (poll(pollfd
, _FD_MAX
, timeout
) < 0) {
395 if (pollfd
[FD_INOTIFY
].revents
!= 0)
396 (void) flush_fd(notify
);
398 if (pollfd
[FD_SIGNAL
].revents
!= 0)
405 static int help(void) {
406 _cleanup_free_
char *link
= NULL
;
409 r
= terminal_urlify_man("systemd-tty-ask-password-agent", "1", &link
);
413 printf("%s [OPTIONS...]\n\n"
414 "Process system password requests.\n\n"
415 " -h --help Show this help\n"
416 " --version Show package version\n"
417 " --list Show pending password requests\n"
418 " --query Process pending password requests\n"
419 " --watch Continuously process password requests\n"
420 " --wall Continuously forward password requests to wall\n"
421 " --plymouth Ask question with Plymouth instead of on TTY\n"
422 " --console Ask question on /dev/console instead of current TTY\n"
423 "\nSee the %s for details.\n"
424 , program_invocation_short_name
431 static int parse_argv(int argc
, char *argv
[]) {
443 static const struct option options
[] = {
444 { "help", no_argument
, NULL
, 'h' },
445 { "version", no_argument
, NULL
, ARG_VERSION
},
446 { "list", no_argument
, NULL
, ARG_LIST
},
447 { "query", no_argument
, NULL
, ARG_QUERY
},
448 { "watch", no_argument
, NULL
, ARG_WATCH
},
449 { "wall", no_argument
, NULL
, ARG_WALL
},
450 { "plymouth", no_argument
, NULL
, ARG_PLYMOUTH
},
451 { "console", optional_argument
, NULL
, ARG_CONSOLE
},
460 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
471 arg_action
= ACTION_LIST
;
475 arg_action
= ACTION_QUERY
;
479 arg_action
= ACTION_WATCH
;
483 arg_action
= ACTION_WALL
;
495 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
496 "Empty console device path is not allowed.");
506 assert_not_reached("Unhandled option");
510 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
511 "%s takes no arguments.", program_invocation_short_name
);
513 if (arg_plymouth
|| arg_console
) {
515 if (!IN_SET(arg_action
, ACTION_QUERY
, ACTION_WATCH
))
516 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
517 "Options --query and --watch conflict.");
519 if (arg_plymouth
&& arg_console
)
520 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
521 "Options --plymouth and --console conflict.");
528 * To be able to ask on all terminal devices of /dev/console the devices are collected. If more than one
529 * device is found, then on each of the terminals a inquiring task is forked. Every task has its own session
530 * and its own controlling terminal. If one of the tasks does handle a password, the remaining tasks will be
533 static int ask_on_this_console(const char *tty
, pid_t
*ret_pid
, char **arguments
) {
534 static const struct sigaction sigchld
= {
535 .sa_handler
= nop_signal_handler
,
536 .sa_flags
= SA_NOCLDSTOP
| SA_RESTART
,
538 static const struct sigaction sighup
= {
539 .sa_handler
= SIG_DFL
,
540 .sa_flags
= SA_RESTART
,
544 assert_se(sigaction(SIGCHLD
, &sigchld
, NULL
) >= 0);
545 assert_se(sigaction(SIGHUP
, &sighup
, NULL
) >= 0);
546 assert_se(sigprocmask_many(SIG_UNBLOCK
, NULL
, SIGHUP
, SIGCHLD
, -1) >= 0);
548 r
= safe_fork("(sd-passwd)", FORK_RESET_SIGNALS
|FORK_LOG
, ret_pid
);
554 assert_se(prctl(PR_SET_PDEATHSIG
, SIGHUP
) >= 0);
556 STRV_FOREACH(i
, arguments
) {
559 if (!streq(*i
, "--console"))
562 k
= strjoin("--console=", tty
);
568 free_and_replace(*i
, k
);
571 execv(SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH
, arguments
);
578 static void terminate_agents(Set
*pids
) {
580 siginfo_t status
= {};
587 * Request termination of the remaining processes as those
588 * are not required anymore.
590 SET_FOREACH(p
, pids
, i
)
591 (void) kill(PTR_TO_PID(p
), SIGTERM
);
594 * Collect the processes which have go away.
596 assert_se(sigemptyset(&set
) >= 0);
597 assert_se(sigaddset(&set
, SIGCHLD
) >= 0);
598 timespec_store(&ts
, 50 * USEC_PER_MSEC
);
600 while (!set_isempty(pids
)) {
603 r
= waitid(P_ALL
, 0, &status
, WEXITED
|WNOHANG
);
604 if (r
< 0 && errno
== EINTR
)
607 if (r
== 0 && status
.si_pid
> 0) {
608 set_remove(pids
, PID_TO_PTR(status
.si_pid
));
612 signum
= sigtimedwait(&set
, NULL
, &ts
);
615 log_error_errno(errno
, "sigtimedwait() failed: %m");
618 assert(signum
== SIGCHLD
);
622 * Kill hanging processes.
624 SET_FOREACH(p
, pids
, i
) {
625 log_warning("Failed to terminate child %d, killing it", PTR_TO_PID(p
));
626 (void) kill(PTR_TO_PID(p
), SIGKILL
);
630 static int ask_on_consoles(char *argv
[]) {
631 _cleanup_set_free_ Set
*pids
= NULL
;
632 _cleanup_strv_free_
char **consoles
= NULL
, **arguments
= NULL
;
633 siginfo_t status
= {};
638 r
= get_kernel_consoles(&consoles
);
640 return log_error_errno(r
, "Failed to determine devices of /dev/console: %m");
642 pids
= set_new(NULL
);
646 arguments
= strv_copy(argv
);
650 /* Start an agent on each console. */
651 STRV_FOREACH(tty
, consoles
) {
652 r
= ask_on_this_console(*tty
, &pid
, arguments
);
656 if (set_put(pids
, PID_TO_PTR(pid
)) < 0)
660 /* Wait for an agent to exit. */
664 if (waitid(P_ALL
, 0, &status
, WEXITED
) < 0) {
668 return log_error_errno(errno
, "waitid() failed: %m");
671 set_remove(pids
, PID_TO_PTR(status
.si_pid
));
675 if (!is_clean_exit(status
.si_code
, status
.si_status
, EXIT_CLEAN_DAEMON
, NULL
))
676 log_error("Password agent failed with: %d", status
.si_status
);
678 terminate_agents(pids
);
682 static int run(int argc
, char *argv
[]) {
689 r
= parse_argv(argc
, argv
);
693 if (arg_console
&& !arg_device
)
695 * Spawn a separate process for each console device.
697 return ask_on_consoles(argv
);
701 * Later on, a controlling terminal will be acquired,
702 * therefore the current process has to become a session
703 * leader and should not have a controlling terminal already.
706 (void) release_terminal();
709 return process_and_watch_password_files(arg_action
!= ACTION_QUERY
);
712 DEFINE_MAIN_FUNCTION(run
);