1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
12 #include <sys/inotify.h>
13 #include <sys/signalfd.h>
21 #include "alloc-util.h"
22 #include "ask-password-api.h"
26 #include "format-util.h"
29 #include "locale-util.h"
32 #include "memory-util.h"
33 #include "missing_syscall.h"
35 #include "process-util.h"
36 #include "random-util.h"
37 #include "signal-util.h"
38 #include "socket-util.h"
39 #include "string-util.h"
41 #include "terminal-util.h"
42 #include "time-util.h"
43 #include "tmpfile-util.h"
44 #include "umask-util.h"
47 #define KEYRING_TIMEOUT_USEC ((5 * USEC_PER_MINUTE) / 2)
49 static int lookup_key(const char *keyname
, key_serial_t
*ret
) {
55 serial
= request_key("user", keyname
, NULL
, 0);
57 return negative_errno();
63 static int retrieve_key(key_serial_t serial
, char ***ret
) {
64 size_t nfinal
, m
= 100;
66 _cleanup_(erase_and_freep
) char *pfinal
= NULL
;
71 _cleanup_(erase_and_freep
) char *p
= NULL
;
78 n
= keyctl(KEYCTL_READ
, (unsigned long) serial
, (unsigned long) p
, (unsigned long) m
, 0);
81 if ((size_t) n
<= m
) {
87 if (m
> LONG_MAX
/ 2) /* overflow check */
92 l
= strv_parse_nulstr(pfinal
, nfinal
);
100 static int add_to_keyring(const char *keyname
, AskPasswordFlags flags
, char **passwords
) {
101 _cleanup_strv_free_erase_
char **l
= NULL
;
102 _cleanup_(erase_and_freep
) char *p
= NULL
;
109 if (!(flags
& ASK_PASSWORD_PUSH_CACHE
))
111 if (strv_isempty(passwords
))
114 r
= lookup_key(keyname
, &serial
);
116 r
= retrieve_key(serial
, &l
);
119 } else if (r
!= -ENOKEY
)
122 r
= strv_extend_strv(&l
, passwords
, true);
126 r
= strv_make_nulstr(l
, &p
, &n
);
130 serial
= add_key("user", keyname
, p
, n
, KEY_SPEC_USER_KEYRING
);
134 if (keyctl(KEYCTL_SET_TIMEOUT
,
135 (unsigned long) serial
,
136 (unsigned long) DIV_ROUND_UP(KEYRING_TIMEOUT_USEC
, USEC_PER_SEC
), 0, 0) < 0)
137 log_debug_errno(errno
, "Failed to adjust kernel keyring key timeout: %m");
139 /* Tell everyone to check the keyring */
140 (void) touch("/run/systemd/ask-password");
142 log_debug("Added key to kernel keyring as %" PRIi32
".", serial
);
147 static int add_to_keyring_and_log(const char *keyname
, AskPasswordFlags flags
, char **passwords
) {
152 r
= add_to_keyring(keyname
, flags
, passwords
);
154 return log_debug_errno(r
, "Failed to add password to kernel keyring: %m");
159 static int ask_password_keyring(const char *keyname
, AskPasswordFlags flags
, char ***ret
) {
167 if (!(flags
& ASK_PASSWORD_ACCEPT_CACHED
))
170 r
= lookup_key(keyname
, &serial
);
171 if (ERRNO_IS_NOT_SUPPORTED(r
) || r
== -EPERM
) /* when retrieving the distinction between "kernel or
172 * container manager don't support or allow this" and
173 * "no matching key known" doesn't matter. Note that we
174 * propagate EACCESS here (even if EPERM not) since
175 * that is used if the keyring is available but we lack
176 * access to the key. */
181 return retrieve_key(serial
, ret
);
184 static int backspace_chars(int ttyfd
, size_t p
) {
188 _cleanup_free_
char *buf
= malloc_multiply(3, p
);
192 for (size_t i
= 0; i
< p
; i
++)
193 memcpy(buf
+ 3 * i
, "\b \b", 3);
195 return loop_write(ttyfd
, buf
, 3*p
, false);
198 static int backspace_string(int ttyfd
, const char *str
) {
201 /* Backspaces through enough characters to entirely undo printing of the specified string. */
206 size_t m
= utf8_n_codepoints(str
);
208 m
= strlen(str
); /* Not a valid UTF-8 string? If so, let's backspace the number of bytes
209 * output. Most likely this happened because we are not in an UTF-8 locale,
210 * and in that case that is the correct thing to do. And even if it's not,
211 * terminals tend to stop backspacing at the leftmost column, hence
212 * backspacing too much should be mostly OK. */
214 return backspace_chars(ttyfd
, m
);
217 int ask_password_plymouth(
220 AskPasswordFlags flags
,
221 const char *flag_file
,
224 static const union sockaddr_union sa
= PLYMOUTH_SOCKET
;
225 _cleanup_close_
int fd
= -1, notify
= -1;
226 _cleanup_free_
char *packet
= NULL
;
229 struct pollfd pollfd
[2] = {};
230 char buffer
[LINE_MAX
];
240 message
= "Password:";
243 notify
= inotify_init1(IN_CLOEXEC
|IN_NONBLOCK
);
247 r
= inotify_add_watch(notify
, flag_file
, IN_ATTRIB
); /* for the link count */
252 fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
256 r
= connect(fd
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
));
260 if (flags
& ASK_PASSWORD_ACCEPT_CACHED
) {
261 packet
= strdup("c");
263 } else if (asprintf(&packet
, "*\002%c%s%n", (int) (strlen(message
) + 1), message
, &n
) < 0)
268 r
= loop_write(fd
, packet
, n
+ 1, true);
272 pollfd
[POLL_SOCKET
].fd
= fd
;
273 pollfd
[POLL_SOCKET
].events
= POLLIN
;
274 pollfd
[POLL_INOTIFY
].fd
= notify
;
275 pollfd
[POLL_INOTIFY
].events
= POLLIN
;
281 timeout
= usec_sub_unsigned(until
, now(CLOCK_MONOTONIC
));
283 timeout
= USEC_INFINITY
;
285 if (flag_file
&& access(flag_file
, F_OK
) < 0) {
290 r
= ppoll_usec(pollfd
, notify
>= 0 ? 2 : 1, timeout
);
300 if (notify
>= 0 && pollfd
[POLL_INOTIFY
].revents
!= 0)
301 (void) flush_fd(notify
);
303 if (pollfd
[POLL_SOCKET
].revents
== 0)
306 k
= read(fd
, buffer
+ p
, sizeof(buffer
) - p
);
308 if (IN_SET(errno
, EINTR
, EAGAIN
))
320 if (buffer
[0] == 5) {
322 if (flags
& ASK_PASSWORD_ACCEPT_CACHED
) {
323 /* Hmm, first try with cached
324 * passwords failed, so let's retry
325 * with a normal password request */
326 packet
= mfree(packet
);
328 if (asprintf(&packet
, "*\002%c%s%n", (int) (strlen(message
) + 1), message
, &n
) < 0) {
333 r
= loop_write(fd
, packet
, n
+1, true);
337 flags
&= ~ASK_PASSWORD_ACCEPT_CACHED
;
342 /* No password, because UI not shown */
346 } else if (IN_SET(buffer
[0], 2, 9)) {
350 /* One or more answers */
354 memcpy(&size
, buffer
+1, sizeof(size
));
355 size
= le32toh(size
);
356 if (size
+ 5 > sizeof(buffer
)) {
364 l
= strv_parse_nulstr(buffer
+ 5, size
);
383 explicit_bzero_safe(buffer
, sizeof(buffer
));
387 #define NO_ECHO "(no echo) "
388 #define PRESS_TAB "(press TAB for no echo) "
389 #define SKIPPED "(skipped)"
391 int ask_password_tty(
396 AskPasswordFlags flags
,
397 const char *flag_file
,
406 bool reset_tty
= false, dirty
= false, use_color
= false, press_tab_visible
= false;
407 _cleanup_close_
int cttyfd
= -1, notify
= -1;
408 struct termios old_termios
, new_termios
;
409 char passphrase
[LINE_MAX
+ 1] = {}, *x
;
410 _cleanup_strv_free_erase_
char **l
= NULL
;
411 struct pollfd pollfd
[_POLL_MAX
];
412 size_t p
= 0, codepoint
= 0;
417 if (flags
& ASK_PASSWORD_NO_TTY
)
421 message
= "Password:";
424 message
= strjoina(special_glyph(SPECIAL_GLYPH_LOCK_AND_KEY
), " ", message
);
426 if (flag_file
|| ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
)) {
427 notify
= inotify_init1(IN_CLOEXEC
|IN_NONBLOCK
);
432 if (inotify_add_watch(notify
, flag_file
, IN_ATTRIB
/* for the link count */) < 0)
435 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
) {
436 r
= ask_password_keyring(keyname
, flags
, ret
);
439 else if (r
!= -ENOKEY
)
442 if (inotify_add_watch(notify
, "/run/systemd/ask-password", IN_ATTRIB
/* for mtime */) < 0)
446 /* If the caller didn't specify a TTY, then use the controlling tty, if we can. */
448 ttyfd
= cttyfd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
451 if (tcgetattr(ttyfd
, &old_termios
) < 0)
454 if (flags
& ASK_PASSWORD_CONSOLE_COLOR
)
455 use_color
= dev_console_colors_enabled();
457 use_color
= colors_enabled();
460 (void) loop_write(ttyfd
, ANSI_HIGHLIGHT
, STRLEN(ANSI_HIGHLIGHT
), false);
462 (void) loop_write(ttyfd
, message
, strlen(message
), false);
463 (void) loop_write(ttyfd
, " ", 1, false);
465 if (!(flags
& ASK_PASSWORD_SILENT
) && !(flags
& ASK_PASSWORD_ECHO
)) {
467 (void) loop_write(ttyfd
, ansi_grey(), strlen(ansi_grey()), false);
468 (void) loop_write(ttyfd
, PRESS_TAB
, strlen(PRESS_TAB
), false);
469 press_tab_visible
= true;
473 (void) loop_write(ttyfd
, ANSI_NORMAL
, STRLEN(ANSI_NORMAL
), false);
475 new_termios
= old_termios
;
476 new_termios
.c_lflag
&= ~(ICANON
|ECHO
);
477 new_termios
.c_cc
[VMIN
] = 1;
478 new_termios
.c_cc
[VTIME
] = 0;
480 if (tcsetattr(ttyfd
, TCSADRAIN
, &new_termios
) < 0) {
488 pollfd
[POLL_TTY
] = (struct pollfd
) {
489 .fd
= ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
,
492 pollfd
[POLL_INOTIFY
] = (struct pollfd
) {
498 _cleanup_(erase_char
) char c
;
503 timeout
= usec_sub_unsigned(until
, now(CLOCK_MONOTONIC
));
505 timeout
= USEC_INFINITY
;
508 if (access(flag_file
, F_OK
) < 0) {
513 r
= ppoll_usec(pollfd
, notify
>= 0 ? 2 : 1, timeout
);
523 if (notify
>= 0 && pollfd
[POLL_INOTIFY
].revents
!= 0 && keyname
) {
524 (void) flush_fd(notify
);
526 r
= ask_password_keyring(keyname
, flags
, ret
);
530 } else if (r
!= -ENOKEY
)
534 if (pollfd
[POLL_TTY
].revents
== 0)
537 n
= read(ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
, &c
, 1);
539 if (IN_SET(errno
, EINTR
, EAGAIN
))
547 if (press_tab_visible
) {
549 backspace_chars(ttyfd
, strlen(PRESS_TAB
));
550 press_tab_visible
= false;
553 /* We treat EOF, newline and NUL byte all as valid end markers */
554 if (n
== 0 || c
== '\n' || c
== 0)
557 if (c
== 4) { /* C-d also known as EOT */
559 (void) loop_write(ttyfd
, SKIPPED
, strlen(SKIPPED
), false);
564 if (c
== 21) { /* C-u */
566 if (!(flags
& ASK_PASSWORD_SILENT
))
567 (void) backspace_string(ttyfd
, passphrase
);
569 explicit_bzero_safe(passphrase
, sizeof(passphrase
));
572 } else if (IN_SET(c
, '\b', 127)) {
577 if (!(flags
& ASK_PASSWORD_SILENT
))
578 (void) backspace_chars(ttyfd
, 1);
580 /* Remove a full UTF-8 codepoint from the end. For that, figure out where the
586 z
= utf8_encoded_valid_unichar(passphrase
+ q
, SIZE_MAX
);
588 q
= SIZE_MAX
; /* Invalid UTF8! */
592 if (q
+ z
>= p
) /* This one brings us over the edge */
598 p
= codepoint
= q
== SIZE_MAX
? p
- 1 : q
;
599 explicit_bzero_safe(passphrase
+ p
, sizeof(passphrase
) - p
);
601 } else if (!dirty
&& !(flags
& ASK_PASSWORD_SILENT
)) {
603 flags
|= ASK_PASSWORD_SILENT
;
605 /* There are two ways to enter silent mode. Either by pressing backspace as
606 * first key (and only as first key), or ... */
609 (void) loop_write(ttyfd
, NO_ECHO
, strlen(NO_ECHO
), false);
611 } else if (ttyfd
>= 0)
612 (void) loop_write(ttyfd
, "\a", 1, false);
614 } else if (c
== '\t' && !(flags
& ASK_PASSWORD_SILENT
)) {
616 (void) backspace_string(ttyfd
, passphrase
);
617 flags
|= ASK_PASSWORD_SILENT
;
619 /* ... or by pressing TAB at any time. */
622 (void) loop_write(ttyfd
, NO_ECHO
, strlen(NO_ECHO
), false);
624 } else if (p
>= sizeof(passphrase
)-1) {
626 /* Reached the size limit */
628 (void) loop_write(ttyfd
, "\a", 1, false);
633 if (!(flags
& ASK_PASSWORD_SILENT
) && ttyfd
>= 0) {
634 /* Check if we got a complete UTF-8 character now. If so, let's output one '*'. */
635 n
= utf8_encoded_valid_unichar(passphrase
+ codepoint
, SIZE_MAX
);
637 if (flags
& ASK_PASSWORD_ECHO
)
638 (void) loop_write(ttyfd
, passphrase
+ codepoint
, n
, false);
640 (void) loop_write(ttyfd
, "*", 1, false);
649 x
= strndup(passphrase
, p
);
650 explicit_bzero_safe(passphrase
, sizeof(passphrase
));
656 r
= strv_consume(&l
, x
);
662 r
= log_debug_errno(SYNTHETIC_ERRNO(ECANCELED
), "Password query was cancelled.");
665 (void) add_to_keyring_and_log(keyname
, flags
, l
);
672 if (ttyfd
>= 0 && reset_tty
) {
673 (void) loop_write(ttyfd
, "\n", 1, false);
674 (void) tcsetattr(ttyfd
, TCSADRAIN
, &old_termios
);
680 static int create_socket(char **ret
) {
681 _cleanup_free_
char *path
= NULL
;
682 union sockaddr_union sa
;
684 _cleanup_close_
int fd
= -1;
689 fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
693 if (asprintf(&path
, "/run/systemd/ask-password/sck.%" PRIx64
, random_u64()) < 0)
696 r
= sockaddr_un_set_path(&sa
.un
, path
);
702 if (bind(fd
, &sa
.sa
, sa_len
) < 0)
705 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSCRED
, true);
709 *ret
= TAKE_PTR(path
);
713 int ask_password_agent(
719 AskPasswordFlags flags
,
729 _cleanup_close_
int socket_fd
= -1, signal_fd
= -1, notify
= -1, fd
= -1;
730 char temp
[] = "/run/systemd/ask-password/tmp.XXXXXX";
731 char final
[sizeof(temp
)] = "";
732 _cleanup_free_
char *socket_name
= NULL
;
733 _cleanup_strv_free_erase_
char **l
= NULL
;
734 _cleanup_fclose_
FILE *f
= NULL
;
735 struct pollfd pollfd
[_FD_MAX
];
736 sigset_t mask
, oldmask
;
741 if (flags
& ASK_PASSWORD_NO_AGENT
)
744 assert_se(sigemptyset(&mask
) >= 0);
745 assert_se(sigset_add_many(&mask
, SIGINT
, SIGTERM
, -1) >= 0);
746 assert_se(sigprocmask(SIG_BLOCK
, &mask
, &oldmask
) >= 0);
748 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
750 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
) {
751 r
= ask_password_keyring(keyname
, flags
, ret
);
755 } else if (r
!= -ENOKEY
)
758 notify
= inotify_init1(IN_CLOEXEC
| IN_NONBLOCK
);
763 if (inotify_add_watch(notify
, "/run/systemd/ask-password", IN_ATTRIB
/* for mtime */) < 0) {
769 fd
= mkostemp_safe(temp
);
775 (void) fchmod(fd
, 0644);
777 f
= take_fdopen(&fd
, "w");
783 signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
789 socket_fd
= create_socket(&socket_name
);
801 "NotAfter="USEC_FMT
"\n",
804 (flags
& ASK_PASSWORD_ACCEPT_CACHED
) ? 1 : 0,
805 (flags
& ASK_PASSWORD_ECHO
) ? 1 : 0,
809 fprintf(f
, "Message=%s\n", message
);
812 fprintf(f
, "Icon=%s\n", icon
);
815 fprintf(f
, "Id=%s\n", id
);
817 r
= fflush_and_check(f
);
821 memcpy(final
, temp
, sizeof(temp
));
823 final
[sizeof(final
)-11] = 'a';
824 final
[sizeof(final
)-10] = 's';
825 final
[sizeof(final
)-9] = 'k';
827 if (rename(temp
, final
) < 0) {
833 pollfd
[FD_SOCKET
].fd
= socket_fd
;
834 pollfd
[FD_SOCKET
].events
= POLLIN
;
835 pollfd
[FD_SIGNAL
].fd
= signal_fd
;
836 pollfd
[FD_SIGNAL
].events
= POLLIN
;
837 pollfd
[FD_INOTIFY
].fd
= notify
;
838 pollfd
[FD_INOTIFY
].events
= POLLIN
;
841 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred
))) control
;
842 char passphrase
[LINE_MAX
+1];
849 timeout
= usec_sub_unsigned(until
, now(CLOCK_MONOTONIC
));
851 timeout
= USEC_INFINITY
;
853 r
= ppoll_usec(pollfd
, notify
>= 0 ? _FD_MAX
: _FD_MAX
- 1, timeout
);
863 if (pollfd
[FD_SIGNAL
].revents
& POLLIN
) {
868 if (notify
>= 0 && pollfd
[FD_INOTIFY
].revents
!= 0) {
869 (void) flush_fd(notify
);
871 r
= ask_password_keyring(keyname
, flags
, ret
);
875 } else if (r
!= -ENOKEY
)
879 if (pollfd
[FD_SOCKET
].revents
== 0)
882 if (pollfd
[FD_SOCKET
].revents
!= POLLIN
) {
887 iovec
= IOVEC_MAKE(passphrase
, sizeof(passphrase
));
889 struct msghdr msghdr
= {
892 .msg_control
= &control
,
893 .msg_controllen
= sizeof(control
),
896 n
= recvmsg_safe(socket_fd
, &msghdr
, 0);
897 if (IN_SET(n
, -EAGAIN
, -EINTR
))
900 log_debug("Got message with truncated control data, ignoring.");
908 cmsg_close_all(&msghdr
);
911 log_debug("Message too short");
915 ucred
= CMSG_FIND_DATA(&msghdr
, SOL_SOCKET
, SCM_CREDENTIALS
, struct ucred
);
917 log_debug("Received message without credentials. Ignoring.");
921 if (ucred
->uid
!= 0) {
922 log_debug("Got request from unprivileged user. Ignoring.");
926 if (passphrase
[0] == '+') {
927 /* An empty message refers to the empty password */
931 l
= strv_parse_nulstr(passphrase
+1, n
-1);
932 explicit_bzero_safe(passphrase
, n
);
938 if (strv_isempty(l
)) {
940 log_debug("Invalid packet");
947 if (passphrase
[0] == '-') {
952 log_debug("Invalid packet");
956 (void) add_to_keyring_and_log(keyname
, flags
, l
);
963 (void) unlink(socket_name
);
968 (void) unlink(final
);
970 assert_se(sigprocmask(SIG_SETMASK
, &oldmask
, NULL
) == 0);
974 int ask_password_auto(
980 AskPasswordFlags flags
,
987 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) &&
989 ((flags
& ASK_PASSWORD_NO_TTY
) || !isatty(STDIN_FILENO
)) &&
990 (flags
& ASK_PASSWORD_NO_AGENT
)) {
991 r
= ask_password_keyring(keyname
, flags
, ret
);
996 if (!(flags
& ASK_PASSWORD_NO_TTY
) && isatty(STDIN_FILENO
))
997 return ask_password_tty(-1, message
, keyname
, until
, flags
, NULL
, ret
);
999 if (!(flags
& ASK_PASSWORD_NO_AGENT
))
1000 return ask_password_agent(message
, icon
, id
, keyname
, until
, flags
, ret
);