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"
23 #include "constants.h"
24 #include "creds-util.h"
27 #include "format-util.h"
29 #include "glyph-util.h"
31 #include "keyring-util.h"
34 #include "memory-util.h"
35 #include "missing_syscall.h"
36 #include "mkdir-label.h"
37 #include "nulstr-util.h"
38 #include "process-util.h"
39 #include "random-util.h"
40 #include "signal-util.h"
41 #include "socket-util.h"
42 #include "string-util.h"
44 #include "terminal-util.h"
45 #include "time-util.h"
46 #include "tmpfile-util.h"
47 #include "umask-util.h"
50 #define KEYRING_TIMEOUT_USEC ((5 * USEC_PER_MINUTE) / 2)
52 static int lookup_key(const char *keyname
, key_serial_t
*ret
) {
58 serial
= request_key("user", keyname
, NULL
, 0);
60 return negative_errno();
66 static int retrieve_key(key_serial_t serial
, char ***ret
) {
67 _cleanup_(erase_and_freep
) void *p
= NULL
;
74 r
= keyring_read(serial
, &p
, &n
);
78 l
= strv_parse_nulstr(p
, n
);
86 static int add_to_keyring(const char *keyname
, AskPasswordFlags flags
, char **passwords
) {
87 _cleanup_strv_free_erase_
char **l
= NULL
;
88 _cleanup_(erase_and_freep
) char *p
= NULL
;
95 if (!FLAGS_SET(flags
, ASK_PASSWORD_PUSH_CACHE
))
97 if (strv_isempty(passwords
))
100 r
= lookup_key(keyname
, &serial
);
102 r
= retrieve_key(serial
, &l
);
105 } else if (r
!= -ENOKEY
)
108 r
= strv_extend_strv(&l
, passwords
, true);
112 r
= strv_make_nulstr(l
, &p
, &n
);
116 /* chop off the final NUL byte. We do this because we want to use the separator NUL bytes only if we
117 * have multiple passwords. */
118 n
= LESS_BY(n
, (size_t) 1);
120 serial
= add_key("user", keyname
, p
, n
, KEY_SPEC_USER_KEYRING
);
124 if (keyctl(KEYCTL_SET_TIMEOUT
,
125 (unsigned long) serial
,
126 (unsigned long) DIV_ROUND_UP(KEYRING_TIMEOUT_USEC
, USEC_PER_SEC
), 0, 0) < 0)
127 log_debug_errno(errno
, "Failed to adjust kernel keyring key timeout: %m");
129 /* Tell everyone to check the keyring */
130 (void) touch("/run/systemd/ask-password");
132 log_debug("Added key to kernel keyring as %" PRIi32
".", serial
);
137 static int add_to_keyring_and_log(const char *keyname
, AskPasswordFlags flags
, char **passwords
) {
142 r
= add_to_keyring(keyname
, flags
, passwords
);
144 return log_debug_errno(r
, "Failed to add password to kernel keyring: %m");
149 static int ask_password_keyring(const char *keyname
, AskPasswordFlags flags
, char ***ret
) {
157 if (!FLAGS_SET(flags
, ASK_PASSWORD_ACCEPT_CACHED
))
160 r
= lookup_key(keyname
, &serial
);
162 /* when retrieving the distinction between "kernel or container manager don't support
163 * or allow this" and "no matching key known" doesn't matter. Note that we propagate
164 * EACCESS here (even if EPERM not) since that is used if the keyring is available but
165 * we lack access to the key. */
166 if (ERRNO_IS_NOT_SUPPORTED(r
) || r
== -EPERM
)
172 return retrieve_key(serial
, ret
);
175 static int backspace_chars(int ttyfd
, size_t p
) {
179 _cleanup_free_
char *buf
= malloc_multiply(3, p
);
183 for (size_t i
= 0; i
< p
; i
++)
184 memcpy(buf
+ 3 * i
, "\b \b", 3);
186 return loop_write(ttyfd
, buf
, 3*p
, false);
189 static int backspace_string(int ttyfd
, const char *str
) {
192 /* Backspaces through enough characters to entirely undo printing of the specified string. */
197 size_t m
= utf8_n_codepoints(str
);
199 m
= strlen(str
); /* Not a valid UTF-8 string? If so, let's backspace the number of bytes
200 * output. Most likely this happened because we are not in an UTF-8 locale,
201 * and in that case that is the correct thing to do. And even if it's not,
202 * terminals tend to stop backspacing at the leftmost column, hence
203 * backspacing too much should be mostly OK. */
205 return backspace_chars(ttyfd
, m
);
208 int ask_password_plymouth(
211 AskPasswordFlags flags
,
212 const char *flag_file
,
215 static const union sockaddr_union sa
= PLYMOUTH_SOCKET
;
216 _cleanup_close_
int fd
= -1, notify
= -1;
217 _cleanup_free_
char *packet
= NULL
;
220 struct pollfd pollfd
[2] = {};
221 char buffer
[LINE_MAX
];
231 message
= "Password:";
234 notify
= inotify_init1(IN_CLOEXEC
|IN_NONBLOCK
);
238 if (inotify_add_watch(notify
, flag_file
, IN_ATTRIB
) < 0) /* for the link count */
242 fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
246 if (connect(fd
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
)) < 0)
249 if (FLAGS_SET(flags
, ASK_PASSWORD_ACCEPT_CACHED
)) {
250 packet
= strdup("c");
252 } else if (asprintf(&packet
, "*\002%c%s%n", (int) (strlen(message
) + 1), message
, &n
) < 0)
257 r
= loop_write(fd
, packet
, n
+ 1, true);
261 pollfd
[POLL_SOCKET
].fd
= fd
;
262 pollfd
[POLL_SOCKET
].events
= POLLIN
;
263 pollfd
[POLL_INOTIFY
].fd
= notify
;
264 pollfd
[POLL_INOTIFY
].events
= POLLIN
;
270 timeout
= usec_sub_unsigned(until
, now(CLOCK_MONOTONIC
));
272 timeout
= USEC_INFINITY
;
274 if (flag_file
&& access(flag_file
, F_OK
) < 0) {
279 r
= ppoll_usec(pollfd
, notify
>= 0 ? 2 : 1, timeout
);
289 if (notify
>= 0 && pollfd
[POLL_INOTIFY
].revents
!= 0)
290 (void) flush_fd(notify
);
292 if (pollfd
[POLL_SOCKET
].revents
== 0)
295 k
= read(fd
, buffer
+ p
, sizeof(buffer
) - p
);
297 if (ERRNO_IS_TRANSIENT(errno
))
310 if (buffer
[0] == 5) {
312 if (FLAGS_SET(flags
, ASK_PASSWORD_ACCEPT_CACHED
)) {
313 /* Hmm, first try with cached
314 * passwords failed, so let's retry
315 * with a normal password request */
316 packet
= mfree(packet
);
318 if (asprintf(&packet
, "*\002%c%s%n", (int) (strlen(message
) + 1), message
, &n
) < 0) {
323 r
= loop_write(fd
, packet
, n
+1, true);
327 flags
&= ~ASK_PASSWORD_ACCEPT_CACHED
;
332 /* No password, because UI not shown */
336 } else if (IN_SET(buffer
[0], 2, 9)) {
340 /* One or more answers */
344 memcpy(&size
, buffer
+1, sizeof(size
));
345 size
= le32toh(size
);
346 if (size
+ 5 > sizeof(buffer
)) {
354 l
= strv_parse_nulstr(buffer
+ 5, size
);
373 explicit_bzero_safe(buffer
, sizeof(buffer
));
377 #define NO_ECHO "(no echo) "
378 #define PRESS_TAB "(press TAB for no echo) "
379 #define SKIPPED "(skipped)"
381 int ask_password_tty(
386 AskPasswordFlags flags
,
387 const char *flag_file
,
396 bool reset_tty
= false, dirty
= false, use_color
= false, press_tab_visible
= false;
397 _cleanup_close_
int cttyfd
= -1, notify
= -1;
398 struct termios old_termios
, new_termios
;
399 char passphrase
[LINE_MAX
+ 1] = {}, *x
;
400 _cleanup_strv_free_erase_
char **l
= NULL
;
401 struct pollfd pollfd
[_POLL_MAX
];
402 size_t p
= 0, codepoint
= 0;
407 if (FLAGS_SET(flags
, ASK_PASSWORD_NO_TTY
))
411 message
= "Password:";
413 if (!FLAGS_SET(flags
, ASK_PASSWORD_HIDE_EMOJI
) && emoji_enabled())
414 message
= strjoina(special_glyph(SPECIAL_GLYPH_LOCK_AND_KEY
), " ", message
);
416 if (flag_file
|| (FLAGS_SET(flags
, ASK_PASSWORD_ACCEPT_CACHED
) && keyname
)) {
417 notify
= inotify_init1(IN_CLOEXEC
|IN_NONBLOCK
);
422 if (inotify_add_watch(notify
, flag_file
, IN_ATTRIB
/* for the link count */) < 0)
425 if (FLAGS_SET(flags
, ASK_PASSWORD_ACCEPT_CACHED
) && keyname
) {
426 r
= ask_password_keyring(keyname
, flags
, ret
);
429 else if (r
!= -ENOKEY
)
432 if (inotify_add_watch(notify
, "/run/systemd/ask-password", IN_ATTRIB
/* for mtime */) < 0)
436 /* If the caller didn't specify a TTY, then use the controlling tty, if we can. */
438 ttyfd
= cttyfd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
441 if (tcgetattr(ttyfd
, &old_termios
) < 0)
444 if (FLAGS_SET(flags
, ASK_PASSWORD_CONSOLE_COLOR
))
445 use_color
= dev_console_colors_enabled();
447 use_color
= colors_enabled();
450 (void) loop_write(ttyfd
, ANSI_HIGHLIGHT
, STRLEN(ANSI_HIGHLIGHT
), false);
452 (void) loop_write(ttyfd
, message
, strlen(message
), false);
453 (void) loop_write(ttyfd
, " ", 1, false);
455 if (!FLAGS_SET(flags
, ASK_PASSWORD_SILENT
) && !FLAGS_SET(flags
, ASK_PASSWORD_ECHO
)) {
457 (void) loop_write(ttyfd
, ansi_grey(), strlen(ansi_grey()), false);
458 (void) loop_write(ttyfd
, PRESS_TAB
, strlen(PRESS_TAB
), false);
459 press_tab_visible
= true;
463 (void) loop_write(ttyfd
, ANSI_NORMAL
, STRLEN(ANSI_NORMAL
), false);
465 new_termios
= old_termios
;
466 new_termios
.c_lflag
&= ~(ICANON
|ECHO
);
467 new_termios
.c_cc
[VMIN
] = 1;
468 new_termios
.c_cc
[VTIME
] = 0;
470 r
= RET_NERRNO(tcsetattr(ttyfd
, TCSADRAIN
, &new_termios
));
477 pollfd
[POLL_TTY
] = (struct pollfd
) {
478 .fd
= ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
,
481 pollfd
[POLL_INOTIFY
] = (struct pollfd
) {
487 _cleanup_(erase_char
) char c
;
492 timeout
= usec_sub_unsigned(until
, now(CLOCK_MONOTONIC
));
494 timeout
= USEC_INFINITY
;
497 r
= RET_NERRNO(access(flag_file
, F_OK
));
502 r
= ppoll_usec(pollfd
, notify
>= 0 ? 2 : 1, timeout
);
512 if (notify
>= 0 && pollfd
[POLL_INOTIFY
].revents
!= 0 && keyname
) {
513 (void) flush_fd(notify
);
515 r
= ask_password_keyring(keyname
, flags
, ret
);
519 } else if (r
!= -ENOKEY
)
523 if (pollfd
[POLL_TTY
].revents
== 0)
526 n
= read(ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
, &c
, 1);
528 if (ERRNO_IS_TRANSIENT(errno
))
536 if (press_tab_visible
) {
538 backspace_chars(ttyfd
, strlen(PRESS_TAB
));
539 press_tab_visible
= false;
542 /* We treat EOF, newline and NUL byte all as valid end markers */
543 if (n
== 0 || c
== '\n' || c
== 0)
546 if (c
== 4) { /* C-d also known as EOT */
548 (void) loop_write(ttyfd
, SKIPPED
, strlen(SKIPPED
), false);
553 if (c
== 21) { /* C-u */
555 if (!FLAGS_SET(flags
, ASK_PASSWORD_SILENT
))
556 (void) backspace_string(ttyfd
, passphrase
);
558 explicit_bzero_safe(passphrase
, sizeof(passphrase
));
561 } else if (IN_SET(c
, '\b', 127)) {
566 if (!FLAGS_SET(flags
, ASK_PASSWORD_SILENT
))
567 (void) backspace_chars(ttyfd
, 1);
569 /* Remove a full UTF-8 codepoint from the end. For that, figure out where the
575 z
= utf8_encoded_valid_unichar(passphrase
+ q
, SIZE_MAX
);
577 q
= SIZE_MAX
; /* Invalid UTF8! */
581 if (q
+ z
>= p
) /* This one brings us over the edge */
587 p
= codepoint
= q
== SIZE_MAX
? p
- 1 : q
;
588 explicit_bzero_safe(passphrase
+ p
, sizeof(passphrase
) - p
);
590 } else if (!dirty
&& !FLAGS_SET(flags
, ASK_PASSWORD_SILENT
)) {
592 flags
|= ASK_PASSWORD_SILENT
;
594 /* There are two ways to enter silent mode. Either by pressing backspace as
595 * first key (and only as first key), or ... */
598 (void) loop_write(ttyfd
, NO_ECHO
, strlen(NO_ECHO
), false);
600 } else if (ttyfd
>= 0)
601 (void) loop_write(ttyfd
, "\a", 1, false);
603 } else if (c
== '\t' && !FLAGS_SET(flags
, ASK_PASSWORD_SILENT
)) {
605 (void) backspace_string(ttyfd
, passphrase
);
606 flags
|= ASK_PASSWORD_SILENT
;
608 /* ... or by pressing TAB at any time. */
611 (void) loop_write(ttyfd
, NO_ECHO
, strlen(NO_ECHO
), false);
613 } else if (p
>= sizeof(passphrase
)-1) {
615 /* Reached the size limit */
617 (void) loop_write(ttyfd
, "\a", 1, false);
622 if (!FLAGS_SET(flags
, ASK_PASSWORD_SILENT
) && ttyfd
>= 0) {
623 /* Check if we got a complete UTF-8 character now. If so, let's output one '*'. */
624 n
= utf8_encoded_valid_unichar(passphrase
+ codepoint
, SIZE_MAX
);
626 if (FLAGS_SET(flags
, ASK_PASSWORD_ECHO
))
627 (void) loop_write(ttyfd
, passphrase
+ codepoint
, n
, false);
629 (void) loop_write(ttyfd
, "*", 1, false);
638 x
= strndup(passphrase
, p
);
639 explicit_bzero_safe(passphrase
, sizeof(passphrase
));
645 r
= strv_consume(&l
, x
);
651 r
= log_debug_errno(SYNTHETIC_ERRNO(ECANCELED
), "Password query was cancelled.");
654 (void) add_to_keyring_and_log(keyname
, flags
, l
);
661 if (ttyfd
>= 0 && reset_tty
) {
662 (void) loop_write(ttyfd
, "\n", 1, false);
663 (void) tcsetattr(ttyfd
, TCSADRAIN
, &old_termios
);
669 static int create_socket(char **ret
) {
670 _cleanup_free_
char *path
= NULL
;
671 union sockaddr_union sa
;
673 _cleanup_close_
int fd
= -1;
678 fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
682 if (asprintf(&path
, "/run/systemd/ask-password/sck.%" PRIx64
, random_u64()) < 0)
685 r
= sockaddr_un_set_path(&sa
.un
, path
);
691 if (bind(fd
, &sa
.sa
, sa_len
) < 0)
694 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSCRED
, true);
698 *ret
= TAKE_PTR(path
);
702 int ask_password_agent(
708 AskPasswordFlags flags
,
718 _cleanup_close_
int socket_fd
= -1, signal_fd
= -1, notify
= -1, fd
= -1;
719 char temp
[] = "/run/systemd/ask-password/tmp.XXXXXX";
720 char final
[sizeof(temp
)] = "";
721 _cleanup_free_
char *socket_name
= NULL
;
722 _cleanup_strv_free_erase_
char **l
= NULL
;
723 _cleanup_fclose_
FILE *f
= NULL
;
724 struct pollfd pollfd
[_FD_MAX
];
725 sigset_t mask
, oldmask
;
730 if (FLAGS_SET(flags
, ASK_PASSWORD_NO_AGENT
))
733 assert_se(sigemptyset(&mask
) >= 0);
734 assert_se(sigset_add_many(&mask
, SIGINT
, SIGTERM
, -1) >= 0);
735 assert_se(sigprocmask(SIG_BLOCK
, &mask
, &oldmask
) >= 0);
737 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
739 if (FLAGS_SET(flags
, ASK_PASSWORD_ACCEPT_CACHED
) && keyname
) {
740 r
= ask_password_keyring(keyname
, flags
, ret
);
744 } else if (r
!= -ENOKEY
)
747 notify
= inotify_init1(IN_CLOEXEC
| IN_NONBLOCK
);
753 r
= RET_NERRNO(inotify_add_watch(notify
, "/run/systemd/ask-password", IN_ATTRIB
/* for mtime */));
758 fd
= mkostemp_safe(temp
);
764 (void) fchmod(fd
, 0644);
766 f
= take_fdopen(&fd
, "w");
772 signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
778 socket_fd
= create_socket(&socket_name
);
790 "NotAfter="USEC_FMT
"\n"
794 FLAGS_SET(flags
, ASK_PASSWORD_ACCEPT_CACHED
),
795 FLAGS_SET(flags
, ASK_PASSWORD_ECHO
),
797 FLAGS_SET(flags
, ASK_PASSWORD_SILENT
));
800 fprintf(f
, "Message=%s\n", message
);
803 fprintf(f
, "Icon=%s\n", icon
);
806 fprintf(f
, "Id=%s\n", id
);
808 r
= fflush_and_check(f
);
812 memcpy(final
, temp
, sizeof(temp
));
814 final
[sizeof(final
)-11] = 'a';
815 final
[sizeof(final
)-10] = 's';
816 final
[sizeof(final
)-9] = 'k';
818 r
= RET_NERRNO(rename(temp
, final
));
823 pollfd
[FD_SOCKET
].fd
= socket_fd
;
824 pollfd
[FD_SOCKET
].events
= POLLIN
;
825 pollfd
[FD_SIGNAL
].fd
= signal_fd
;
826 pollfd
[FD_SIGNAL
].events
= POLLIN
;
827 pollfd
[FD_INOTIFY
].fd
= notify
;
828 pollfd
[FD_INOTIFY
].events
= POLLIN
;
831 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred
))) control
;
832 char passphrase
[LINE_MAX
+1];
839 timeout
= usec_sub_unsigned(until
, now(CLOCK_MONOTONIC
));
841 timeout
= USEC_INFINITY
;
843 r
= ppoll_usec(pollfd
, notify
>= 0 ? _FD_MAX
: _FD_MAX
- 1, timeout
);
853 if (pollfd
[FD_SIGNAL
].revents
& POLLIN
) {
858 if (notify
>= 0 && pollfd
[FD_INOTIFY
].revents
!= 0) {
859 (void) flush_fd(notify
);
861 r
= ask_password_keyring(keyname
, flags
, ret
);
865 } else if (r
!= -ENOKEY
)
869 if (pollfd
[FD_SOCKET
].revents
== 0)
872 if (pollfd
[FD_SOCKET
].revents
!= POLLIN
) {
877 iovec
= IOVEC_MAKE(passphrase
, sizeof(passphrase
));
879 struct msghdr msghdr
= {
882 .msg_control
= &control
,
883 .msg_controllen
= sizeof(control
),
886 n
= recvmsg_safe(socket_fd
, &msghdr
, 0);
888 if (ERRNO_IS_TRANSIENT(n
))
891 log_debug("Got message with truncated control data, ignoring.");
899 cmsg_close_all(&msghdr
);
902 log_debug("Message too short");
906 ucred
= CMSG_FIND_DATA(&msghdr
, SOL_SOCKET
, SCM_CREDENTIALS
, struct ucred
);
908 log_debug("Received message without credentials. Ignoring.");
912 if (ucred
->uid
!= 0) {
913 log_debug("Got request from unprivileged user. Ignoring.");
917 if (passphrase
[0] == '+') {
918 /* An empty message refers to the empty password */
922 l
= strv_parse_nulstr(passphrase
+1, n
-1);
923 explicit_bzero_safe(passphrase
, n
);
929 if (strv_isempty(l
)) {
931 log_debug("Invalid packet");
938 if (passphrase
[0] == '-') {
943 log_debug("Invalid packet");
947 (void) add_to_keyring_and_log(keyname
, flags
, l
);
954 (void) unlink(socket_name
);
959 (void) unlink(final
);
961 assert_se(sigprocmask(SIG_SETMASK
, &oldmask
, NULL
) == 0);
965 static int ask_password_credential(const char *credential_name
, AskPasswordFlags flags
, char ***ret
) {
966 _cleanup_(erase_and_freep
) char *buffer
= NULL
;
971 assert(credential_name
);
974 r
= read_credential(credential_name
, (void**) &buffer
, &size
);
975 if (IN_SET(r
, -ENXIO
, -ENOENT
)) /* No credentials passed or this credential not defined? */
978 l
= strv_parse_nulstr(buffer
, size
);
986 int ask_password_auto(
989 const char *id
, /* id in "ask-password" protocol */
990 const char *key_name
, /* name in kernel keyring */
991 const char *credential_name
, /* name in $CREDENTIALS_DIRECTORY directory */
993 AskPasswordFlags flags
,
1000 if (!FLAGS_SET(flags
, ASK_PASSWORD_NO_CREDENTIAL
) && credential_name
) {
1001 r
= ask_password_credential(credential_name
, flags
, ret
);
1006 if (FLAGS_SET(flags
, ASK_PASSWORD_ACCEPT_CACHED
) &&
1008 (FLAGS_SET(flags
, ASK_PASSWORD_NO_TTY
) || !isatty(STDIN_FILENO
)) &&
1009 FLAGS_SET(flags
, ASK_PASSWORD_NO_AGENT
)) {
1010 r
= ask_password_keyring(key_name
, flags
, ret
);
1015 if (!FLAGS_SET(flags
, ASK_PASSWORD_NO_TTY
) && isatty(STDIN_FILENO
))
1016 return ask_password_tty(-1, message
, key_name
, until
, flags
, NULL
, ret
);
1018 if (!FLAGS_SET(flags
, ASK_PASSWORD_NO_AGENT
))
1019 return ask_password_agent(message
, icon
, id
, key_name
, until
, flags
, ret
);