1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright © 2015 Werner Fink
14 #include <sys/prctl.h>
15 #include <sys/signalfd.h>
16 #include <sys/socket.h>
18 #include <sys/types.h>
23 #include "alloc-util.h"
24 #include "ask-password-api.h"
25 #include "conf-parser.h"
27 #include "dirent-util.h"
28 #include "exit-status.h"
35 #include "main-func.h"
36 #include "memory-util.h"
38 #include "path-util.h"
39 #include "pretty-print.h"
40 #include "process-util.h"
42 #include "signal-util.h"
43 #include "socket-util.h"
44 #include "string-util.h"
46 #include "terminal-util.h"
47 #include "utmp-wtmp.h"
54 } arg_action
= ACTION_QUERY
;
56 static bool arg_plymouth
= false;
57 static bool arg_console
= false;
58 static const char *arg_device
= NULL
;
60 static int send_passwords(const char *socket_name
, char **passwords
) {
61 _cleanup_(erase_and_freep
) char *packet
= NULL
;
62 _cleanup_close_
int socket_fd
= -1;
63 union sockaddr_union sa
= {};
64 size_t packet_length
= 1;
71 salen
= sockaddr_un_set_path(&sa
.un
, socket_name
);
75 STRV_FOREACH(p
, passwords
)
76 packet_length
+= strlen(*p
) + 1;
78 packet
= new(char, packet_length
);
85 STRV_FOREACH(p
, passwords
)
86 d
= stpcpy(d
, *p
) + 1;
88 socket_fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0);
90 return log_debug_errno(errno
, "socket(): %m");
92 n
= sendto(socket_fd
, packet
, packet_length
, MSG_NOSIGNAL
, &sa
.sa
, salen
);
94 return log_debug_errno(errno
, "sendto(): %m");
99 static bool wall_tty_match(const char *path
, void *userdata
) {
100 _cleanup_free_
char *p
= NULL
;
101 _cleanup_close_
int fd
= -1;
104 if (!path_is_absolute(path
))
105 path
= strjoina("/dev/", path
);
107 if (lstat(path
, &st
) < 0) {
108 log_debug_errno(errno
, "Failed to stat %s: %m", path
);
112 if (!S_ISCHR(st
.st_mode
)) {
113 log_debug("%s is not a character device.", path
);
117 /* We use named pipes to ensure that wall messages suggesting
118 * password entry are not printed over password prompts
119 * already shown. We use the fact here that opening a pipe in
120 * non-blocking mode for write-only will succeed only if
121 * there's some writer behind it. Using pipes has the
122 * advantage that the block will automatically go away if the
125 if (asprintf(&p
, "/run/systemd/ask-password-block/%u:%u", major(st
.st_rdev
), minor(st
.st_rdev
)) < 0) {
130 fd
= open(p
, O_WRONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
132 log_debug_errno(errno
, "Failed to open the wall pipe: %m");
136 /* What, we managed to open the pipe? Then this tty is filtered. */
140 static int agent_ask_password_tty(
143 AskPasswordFlags flags
,
144 const char *flag_file
,
151 const char *con
= arg_device
?: "/dev/console";
153 tty_fd
= acquire_terminal(con
, ACQUIRE_TERMINAL_WAIT
, USEC_INFINITY
);
155 return log_error_errno(tty_fd
, "Failed to acquire %s: %m", con
);
157 r
= reset_terminal_fd(tty_fd
, true);
159 log_warning_errno(r
, "Failed to reset terminal, ignoring: %m");
163 r
= ask_password_tty(tty_fd
, message
, NULL
, until
, flags
, flag_file
, ret
);
166 tty_fd
= safe_close(tty_fd
);
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;
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
},
193 r
= config_parse(NULL
, filename
, NULL
,
195 config_item_table_lookup
, items
,
196 CONFIG_PARSE_RELAXED
|CONFIG_PARSE_WARN
, NULL
);
201 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
202 "Invalid password file %s", filename
);
204 if (not_after
> 0 && now(CLOCK_MONOTONIC
) > not_after
)
207 if (pid
> 0 && !pid_is_alive(pid
))
210 switch (arg_action
) {
212 printf("'%s' (PID %u)\n", message
, pid
);
216 _cleanup_free_
char *wall
= NULL
;
219 "Password entry required for \'%s\' (PID %u).\r\n"
220 "Please enter password with the systemd-tty-ask-password-agent tool.",
225 (void) utmp_wall(wall
, NULL
, NULL
, wall_tty_match
, NULL
);
230 _cleanup_strv_free_erase_
char **passwords
= NULL
;
231 AskPasswordFlags flags
= 0;
233 if (access(socket_name
, W_OK
) < 0) {
234 if (arg_action
== ACTION_QUERY
)
235 log_info("Not querying '%s' (PID %u), lacking privileges.", message
, pid
);
240 SET_FLAG(flags
, ASK_PASSWORD_ACCEPT_CACHED
, accept_cached
);
241 SET_FLAG(flags
, ASK_PASSWORD_CONSOLE_COLOR
, arg_console
);
242 SET_FLAG(flags
, ASK_PASSWORD_ECHO
, echo
);
245 r
= ask_password_plymouth(message
, not_after
, flags
, filename
, &passwords
);
247 r
= agent_ask_password_tty(message
, not_after
, flags
, filename
, &passwords
);
250 /* If the query went away, that's OK */
251 if (IN_SET(r
, -ETIME
, -ENOENT
))
254 return log_error_errno(r
, "Failed to query password: %m");
257 if (strv_isempty(passwords
))
260 r
= send_passwords(socket_name
, passwords
);
262 return log_error_errno(r
, "Failed to send: %m");
270 static int wall_tty_block(void) {
271 _cleanup_free_
char *p
= NULL
;
275 r
= get_ctty_devnr(0, &devnr
);
276 if (r
== -ENXIO
) /* We have no controlling tty */
279 return log_error_errno(r
, "Failed to get controlling TTY: %m");
281 if (asprintf(&p
, "/run/systemd/ask-password-block/%u:%u", major(devnr
), minor(devnr
)) < 0)
284 (void) mkdir_parents_label(p
, 0700);
285 (void) mkfifo(p
, 0600);
287 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
289 return log_debug_errno(errno
, "Failed to open %s: %m", p
);
294 static int process_password_files(void) {
295 _cleanup_closedir_
DIR *d
;
299 d
= opendir("/run/systemd/ask-password");
304 return log_error_errno(errno
, "Failed to open /run/systemd/ask-password: %m");
307 FOREACH_DIRENT(de
, d
, return log_error_errno(errno
, "Failed to read directory: %m")) {
308 _cleanup_free_
char *p
= NULL
;
311 /* We only support /run on tmpfs, hence we can rely on
312 * d_type to be reliable */
314 if (de
->d_type
!= DT_REG
)
317 if (!startswith(de
->d_name
, "ask."))
320 p
= path_join("/run/systemd/ask-password", de
->d_name
);
324 q
= process_one_password_file(p
);
332 static int process_and_watch_password_files(bool watch
) {
339 _cleanup_close_
int notify
= -1, signal_fd
= -1, tty_block_fd
= -1;
340 struct pollfd pollfd
[_FD_MAX
];
344 tty_block_fd
= wall_tty_block();
346 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
348 assert_se(sigemptyset(&mask
) >= 0);
349 assert_se(sigset_add_many(&mask
, SIGTERM
, -1) >= 0);
350 assert_se(sigprocmask(SIG_SETMASK
, &mask
, NULL
) >= 0);
353 signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
355 return log_error_errno(errno
, "Failed to allocate signal file descriptor: %m");
357 pollfd
[FD_SIGNAL
] = (struct pollfd
) { .fd
= signal_fd
, .events
= POLLIN
};
359 notify
= inotify_init1(IN_CLOEXEC
);
361 return log_error_errno(errno
, "Failed to allocate directory watch: %m");
363 r
= inotify_add_watch_and_warn(notify
, "/run/systemd/ask-password", IN_CLOSE_WRITE
|IN_MOVED_TO
);
367 pollfd
[FD_INOTIFY
] = (struct pollfd
) { .fd
= notify
, .events
= POLLIN
};
373 r
= process_password_files();
376 /* Disable poll() timeout since at least one password has
377 * been skipped and therefore one file remains and is
378 * unlikely to trigger any events. */
381 /* FIXME: we should do something here since otherwise the service
382 * requesting the password won't notice the error and will wait
384 log_error_errno(r
, "Failed to process password: %m");
390 if (poll(pollfd
, _FD_MAX
, timeout
) < 0) {
397 if (pollfd
[FD_INOTIFY
].revents
!= 0)
398 (void) flush_fd(notify
);
400 if (pollfd
[FD_SIGNAL
].revents
!= 0)
407 static int help(void) {
408 _cleanup_free_
char *link
= NULL
;
411 r
= terminal_urlify_man("systemd-tty-ask-password-agent", "1", &link
);
415 printf("%s [OPTIONS...]\n\n"
416 "Process system password requests.\n\n"
417 " -h --help Show this help\n"
418 " --version Show package version\n"
419 " --list Show pending password requests\n"
420 " --query Process pending password requests\n"
421 " --watch Continuously process password requests\n"
422 " --wall Continuously forward password requests to wall\n"
423 " --plymouth Ask question with Plymouth instead of on TTY\n"
424 " --console Ask question on /dev/console instead of current TTY\n"
425 "\nSee the %s for details.\n"
426 , program_invocation_short_name
433 static int parse_argv(int argc
, char *argv
[]) {
445 static const struct option options
[] = {
446 { "help", no_argument
, NULL
, 'h' },
447 { "version", no_argument
, NULL
, ARG_VERSION
},
448 { "list", no_argument
, NULL
, ARG_LIST
},
449 { "query", no_argument
, NULL
, ARG_QUERY
},
450 { "watch", no_argument
, NULL
, ARG_WATCH
},
451 { "wall", no_argument
, NULL
, ARG_WALL
},
452 { "plymouth", no_argument
, NULL
, ARG_PLYMOUTH
},
453 { "console", optional_argument
, NULL
, ARG_CONSOLE
},
462 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
473 arg_action
= ACTION_LIST
;
477 arg_action
= ACTION_QUERY
;
481 arg_action
= ACTION_WATCH
;
485 arg_action
= ACTION_WALL
;
497 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
498 "Empty console device path is not allowed.");
508 assert_not_reached("Unhandled option");
512 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
513 "%s takes no arguments.", program_invocation_short_name
);
515 if (arg_plymouth
|| arg_console
) {
517 if (!IN_SET(arg_action
, ACTION_QUERY
, ACTION_WATCH
))
518 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
519 "Options --query and --watch conflict.");
521 if (arg_plymouth
&& arg_console
)
522 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
523 "Options --plymouth and --console conflict.");
530 * To be able to ask on all terminal devices of /dev/console the devices are collected. If more than one
531 * device is found, then on each of the terminals a inquiring task is forked. Every task has its own session
532 * and its own controlling terminal. If one of the tasks does handle a password, the remaining tasks will be
535 static int ask_on_this_console(const char *tty
, pid_t
*ret_pid
, char **arguments
) {
536 static const struct sigaction sigchld
= {
537 .sa_handler
= nop_signal_handler
,
538 .sa_flags
= SA_NOCLDSTOP
| SA_RESTART
,
540 static const struct sigaction sighup
= {
541 .sa_handler
= SIG_DFL
,
542 .sa_flags
= SA_RESTART
,
546 assert_se(sigaction(SIGCHLD
, &sigchld
, NULL
) >= 0);
547 assert_se(sigaction(SIGHUP
, &sighup
, NULL
) >= 0);
548 assert_se(sigprocmask_many(SIG_UNBLOCK
, NULL
, SIGHUP
, SIGCHLD
, -1) >= 0);
550 r
= safe_fork("(sd-passwd)", FORK_RESET_SIGNALS
|FORK_LOG
, ret_pid
);
556 assert_se(prctl(PR_SET_PDEATHSIG
, SIGHUP
) >= 0);
558 STRV_FOREACH(i
, arguments
) {
561 if (!streq(*i
, "--console"))
564 k
= strjoin("--console=", tty
);
570 free_and_replace(*i
, k
);
573 execv(SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH
, arguments
);
580 static void terminate_agents(Set
*pids
) {
582 siginfo_t status
= {};
589 * Request termination of the remaining processes as those
590 * are not required anymore.
592 SET_FOREACH(p
, pids
, i
)
593 (void) kill(PTR_TO_PID(p
), SIGTERM
);
596 * Collect the processes which have go away.
598 assert_se(sigemptyset(&set
) >= 0);
599 assert_se(sigaddset(&set
, SIGCHLD
) >= 0);
600 timespec_store(&ts
, 50 * USEC_PER_MSEC
);
602 while (!set_isempty(pids
)) {
605 r
= waitid(P_ALL
, 0, &status
, WEXITED
|WNOHANG
);
606 if (r
< 0 && errno
== EINTR
)
609 if (r
== 0 && status
.si_pid
> 0) {
610 set_remove(pids
, PID_TO_PTR(status
.si_pid
));
614 signum
= sigtimedwait(&set
, NULL
, &ts
);
617 log_error_errno(errno
, "sigtimedwait() failed: %m");
620 assert(signum
== SIGCHLD
);
624 * Kill hanging processes.
626 SET_FOREACH(p
, pids
, i
) {
627 log_warning("Failed to terminate child %d, killing it", PTR_TO_PID(p
));
628 (void) kill(PTR_TO_PID(p
), SIGKILL
);
632 static int ask_on_consoles(char *argv
[]) {
633 _cleanup_set_free_ Set
*pids
= NULL
;
634 _cleanup_strv_free_
char **consoles
= NULL
, **arguments
= NULL
;
635 siginfo_t status
= {};
640 r
= get_kernel_consoles(&consoles
);
642 return log_error_errno(r
, "Failed to determine devices of /dev/console: %m");
644 pids
= set_new(NULL
);
648 arguments
= strv_copy(argv
);
652 /* Start an agent on each console. */
653 STRV_FOREACH(tty
, consoles
) {
654 r
= ask_on_this_console(*tty
, &pid
, arguments
);
658 if (set_put(pids
, PID_TO_PTR(pid
)) < 0)
662 /* Wait for an agent to exit. */
666 if (waitid(P_ALL
, 0, &status
, WEXITED
) < 0) {
670 return log_error_errno(errno
, "waitid() failed: %m");
673 set_remove(pids
, PID_TO_PTR(status
.si_pid
));
677 if (!is_clean_exit(status
.si_code
, status
.si_status
, EXIT_CLEAN_DAEMON
, NULL
))
678 log_error("Password agent failed with: %d", status
.si_status
);
680 terminate_agents(pids
);
684 static int run(int argc
, char *argv
[]) {
691 r
= parse_argv(argc
, argv
);
695 if (arg_console
&& !arg_device
)
697 * Spawn a separate process for each console device.
699 return ask_on_consoles(argv
);
703 * Later on, a controlling terminal will be acquired,
704 * therefore the current process has to become a session
705 * leader and should not have a controlling terminal already.
708 (void) release_terminal();
711 return process_and_watch_password_files(arg_action
!= ACTION_QUERY
);
714 DEFINE_MAIN_FUNCTION(run
);