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 "creds-util.h"
26 #include "format-util.h"
28 #include "glyph-util.h"
30 #include "iovec-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 "plymouth-util.h"
39 #include "process-util.h"
40 #include "random-util.h"
41 #include "signal-util.h"
42 #include "socket-util.h"
43 #include "string-util.h"
45 #include "terminal-util.h"
46 #include "time-util.h"
47 #include "tmpfile-util.h"
48 #include "umask-util.h"
51 #define KEYRING_TIMEOUT_USEC ((5 * USEC_PER_MINUTE) / 2)
53 static int lookup_key(const char *keyname
, key_serial_t
*ret
) {
59 serial
= request_key("user", keyname
, NULL
, 0);
61 return negative_errno();
67 static int retrieve_key(key_serial_t serial
, char ***ret
) {
68 _cleanup_(erase_and_freep
) void *p
= NULL
;
75 r
= keyring_read(serial
, &p
, &n
);
79 l
= strv_parse_nulstr(p
, n
);
87 static int add_to_keyring(const char *keyname
, AskPasswordFlags flags
, char **passwords
) {
88 _cleanup_strv_free_erase_
char **l
= NULL
;
89 _cleanup_(erase_and_freep
) char *p
= NULL
;
96 if (!FLAGS_SET(flags
, ASK_PASSWORD_PUSH_CACHE
))
98 if (strv_isempty(passwords
))
101 r
= lookup_key(keyname
, &serial
);
103 r
= retrieve_key(serial
, &l
);
106 } else if (r
!= -ENOKEY
)
109 r
= strv_extend_strv(&l
, passwords
, true);
113 r
= strv_make_nulstr(l
, &p
, &n
);
117 /* chop off the final NUL byte. We do this because we want to use the separator NUL bytes only if we
118 * have multiple passwords. */
119 n
= LESS_BY(n
, (size_t) 1);
121 serial
= add_key("user", keyname
, p
, n
, KEY_SPEC_USER_KEYRING
);
125 if (keyctl(KEYCTL_SET_TIMEOUT
,
126 (unsigned long) serial
,
127 (unsigned long) DIV_ROUND_UP(KEYRING_TIMEOUT_USEC
, USEC_PER_SEC
), 0, 0) < 0)
128 log_debug_errno(errno
, "Failed to adjust kernel keyring key timeout: %m");
130 /* Tell everyone to check the keyring */
131 (void) touch("/run/systemd/ask-password");
133 log_debug("Added key to kernel keyring as %" PRIi32
".", serial
);
138 static int add_to_keyring_and_log(const char *keyname
, AskPasswordFlags flags
, char **passwords
) {
143 r
= add_to_keyring(keyname
, flags
, passwords
);
145 return log_debug_errno(r
, "Failed to add password to kernel keyring: %m");
150 static int ask_password_keyring(const char *keyname
, AskPasswordFlags flags
, char ***ret
) {
158 if (!FLAGS_SET(flags
, ASK_PASSWORD_ACCEPT_CACHED
))
161 r
= lookup_key(keyname
, &serial
);
162 if (ERRNO_IS_NEG_NOT_SUPPORTED(r
) || r
== -EPERM
)
163 /* When retrieving, the distinction between "kernel or container manager don't support or
164 * allow this" and "no matching key known" doesn't matter. Note that we propagate EACCESS
165 * here (even if EPERM not) since that is used if the keyring is available, but we lack
166 * access to the key. */
171 return retrieve_key(serial
, ret
);
174 static int backspace_chars(int ttyfd
, size_t p
) {
178 _cleanup_free_
char *buf
= malloc_multiply(3, p
);
182 for (size_t i
= 0; i
< p
; i
++)
183 memcpy(buf
+ 3 * i
, "\b \b", 3);
185 return loop_write(ttyfd
, buf
, 3 * p
);
188 static int backspace_string(int ttyfd
, const char *str
) {
191 /* Backspaces through enough characters to entirely undo printing of the specified string. */
196 size_t m
= utf8_n_codepoints(str
);
198 m
= strlen(str
); /* Not a valid UTF-8 string? If so, let's backspace the number of bytes
199 * output. Most likely this happened because we are not in a UTF-8 locale,
200 * and in that case that is the correct thing to do. And even if it's not,
201 * terminals tend to stop backspacing at the leftmost column, hence
202 * backspacing too much should be mostly OK. */
204 return backspace_chars(ttyfd
, m
);
207 int ask_password_plymouth(
210 AskPasswordFlags flags
,
211 const char *flag_file
,
214 _cleanup_close_
int fd
= -EBADF
, notify
= -EBADF
;
215 _cleanup_free_
char *packet
= NULL
;
218 struct pollfd pollfd
[2] = {};
219 char buffer
[LINE_MAX
];
229 message
= "Password:";
232 notify
= inotify_init1(IN_CLOEXEC
|IN_NONBLOCK
);
236 if (inotify_add_watch(notify
, flag_file
, IN_ATTRIB
) < 0) /* for the link count */
240 fd
= plymouth_connect(SOCK_NONBLOCK
);
244 if (FLAGS_SET(flags
, ASK_PASSWORD_ACCEPT_CACHED
)) {
245 packet
= strdup("c");
247 } else if (asprintf(&packet
, "*\002%c%s%n", (int) (strlen(message
) + 1), message
, &n
) < 0)
252 r
= loop_write_full(fd
, packet
, n
+ 1, USEC_INFINITY
);
256 CLEANUP_ERASE(buffer
);
258 pollfd
[POLL_SOCKET
].fd
= fd
;
259 pollfd
[POLL_SOCKET
].events
= POLLIN
;
260 pollfd
[POLL_INOTIFY
].fd
= notify
;
261 pollfd
[POLL_INOTIFY
].events
= POLLIN
;
267 timeout
= usec_sub_unsigned(until
, now(CLOCK_MONOTONIC
));
269 timeout
= USEC_INFINITY
;
271 if (flag_file
&& access(flag_file
, F_OK
) < 0)
274 r
= ppoll_usec(pollfd
, notify
>= 0 ? 2 : 1, timeout
);
282 if (notify
>= 0 && pollfd
[POLL_INOTIFY
].revents
!= 0)
283 (void) flush_fd(notify
);
285 if (pollfd
[POLL_SOCKET
].revents
== 0)
288 k
= read(fd
, buffer
+ p
, sizeof(buffer
) - p
);
290 if (ERRNO_IS_TRANSIENT(errno
))
300 if (buffer
[0] == 5) {
302 if (FLAGS_SET(flags
, ASK_PASSWORD_ACCEPT_CACHED
)) {
303 /* Hmm, first try with cached
304 * passwords failed, so let's retry
305 * with a normal password request */
306 packet
= mfree(packet
);
308 if (asprintf(&packet
, "*\002%c%s%n", (int) (strlen(message
) + 1), message
, &n
) < 0)
311 r
= loop_write_full(fd
, packet
, n
+ 1, USEC_INFINITY
);
315 flags
&= ~ASK_PASSWORD_ACCEPT_CACHED
;
320 /* No password, because UI not shown */
323 } else if (IN_SET(buffer
[0], 2, 9)) {
327 /* One or more answers */
331 memcpy(&size
, buffer
+1, sizeof(size
));
332 size
= le32toh(size
);
333 if (size
+ 5 > sizeof(buffer
))
339 l
= strv_parse_nulstr(buffer
+ 5, size
);
354 #define NO_ECHO "(no echo) "
355 #define PRESS_TAB "(press TAB for no echo) "
356 #define SKIPPED "(skipped)"
358 int ask_password_tty(
363 AskPasswordFlags flags
,
364 const char *flag_file
,
373 bool reset_tty
= false, dirty
= false, use_color
= false, press_tab_visible
= false;
374 _cleanup_close_
int cttyfd
= -EBADF
, notify
= -EBADF
;
375 struct termios old_termios
, new_termios
;
376 char passphrase
[LINE_MAX
+ 1] = {}, *x
;
377 _cleanup_strv_free_erase_
char **l
= NULL
;
378 struct pollfd pollfd
[_POLL_MAX
];
379 size_t p
= 0, codepoint
= 0;
384 if (FLAGS_SET(flags
, ASK_PASSWORD_NO_TTY
))
388 message
= "Password:";
390 if (!FLAGS_SET(flags
, ASK_PASSWORD_HIDE_EMOJI
) && emoji_enabled())
391 message
= strjoina(special_glyph(SPECIAL_GLYPH_LOCK_AND_KEY
), " ", message
);
393 if (flag_file
|| (FLAGS_SET(flags
, ASK_PASSWORD_ACCEPT_CACHED
) && keyname
)) {
394 notify
= inotify_init1(IN_CLOEXEC
|IN_NONBLOCK
);
399 if (inotify_add_watch(notify
, flag_file
, IN_ATTRIB
/* for the link count */) < 0)
402 if (FLAGS_SET(flags
, ASK_PASSWORD_ACCEPT_CACHED
) && keyname
) {
403 r
= ask_password_keyring(keyname
, flags
, ret
);
406 else if (r
!= -ENOKEY
)
409 if (inotify_add_watch(notify
, "/run/systemd/ask-password", IN_ATTRIB
/* for mtime */) < 0)
413 CLEANUP_ERASE(passphrase
);
415 /* If the caller didn't specify a TTY, then use the controlling tty, if we can. */
417 ttyfd
= cttyfd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
420 if (tcgetattr(ttyfd
, &old_termios
) < 0)
423 if (FLAGS_SET(flags
, ASK_PASSWORD_CONSOLE_COLOR
))
424 use_color
= dev_console_colors_enabled();
426 use_color
= colors_enabled();
429 (void) loop_write(ttyfd
, ANSI_HIGHLIGHT
, SIZE_MAX
);
431 (void) loop_write(ttyfd
, message
, SIZE_MAX
);
432 (void) loop_write(ttyfd
, " ", 1);
434 if (!FLAGS_SET(flags
, ASK_PASSWORD_SILENT
) && !FLAGS_SET(flags
, ASK_PASSWORD_ECHO
)) {
436 (void) loop_write(ttyfd
, ansi_grey(), SIZE_MAX
);
438 (void) loop_write(ttyfd
, PRESS_TAB
, SIZE_MAX
);
439 press_tab_visible
= true;
443 (void) loop_write(ttyfd
, ANSI_NORMAL
, SIZE_MAX
);
445 new_termios
= old_termios
;
446 termios_disable_echo(&new_termios
);
448 r
= RET_NERRNO(tcsetattr(ttyfd
, TCSADRAIN
, &new_termios
));
455 pollfd
[POLL_TTY
] = (struct pollfd
) {
456 .fd
= ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
,
459 pollfd
[POLL_INOTIFY
] = (struct pollfd
) {
465 _cleanup_(erase_char
) char c
;
470 timeout
= usec_sub_unsigned(until
, now(CLOCK_MONOTONIC
));
472 timeout
= USEC_INFINITY
;
475 r
= RET_NERRNO(access(flag_file
, F_OK
));
480 r
= ppoll_usec(pollfd
, notify
>= 0 ? 2 : 1, timeout
);
490 if (notify
>= 0 && pollfd
[POLL_INOTIFY
].revents
!= 0 && keyname
) {
491 (void) flush_fd(notify
);
493 r
= ask_password_keyring(keyname
, flags
, ret
);
497 } else if (r
!= -ENOKEY
)
501 if (pollfd
[POLL_TTY
].revents
== 0)
504 n
= read(ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
, &c
, 1);
506 if (ERRNO_IS_TRANSIENT(errno
))
514 if (press_tab_visible
) {
516 backspace_chars(ttyfd
, strlen(PRESS_TAB
));
517 press_tab_visible
= false;
520 /* We treat EOF, newline and NUL byte all as valid end markers */
521 if (n
== 0 || c
== '\n' || c
== 0)
524 if (c
== 4) { /* C-d also known as EOT */
526 (void) loop_write(ttyfd
, SKIPPED
, SIZE_MAX
);
531 if (c
== 21) { /* C-u */
533 if (!FLAGS_SET(flags
, ASK_PASSWORD_SILENT
))
534 (void) backspace_string(ttyfd
, passphrase
);
536 explicit_bzero_safe(passphrase
, sizeof(passphrase
));
539 } else if (IN_SET(c
, '\b', 127)) {
544 if (!FLAGS_SET(flags
, ASK_PASSWORD_SILENT
))
545 (void) backspace_chars(ttyfd
, 1);
547 /* Remove a full UTF-8 codepoint from the end. For that, figure out where the
553 z
= utf8_encoded_valid_unichar(passphrase
+ q
, SIZE_MAX
);
555 q
= SIZE_MAX
; /* Invalid UTF8! */
559 if (q
+ z
>= p
) /* This one brings us over the edge */
565 p
= codepoint
= q
== SIZE_MAX
? p
- 1 : q
;
566 explicit_bzero_safe(passphrase
+ p
, sizeof(passphrase
) - p
);
568 } else if (!dirty
&& !FLAGS_SET(flags
, ASK_PASSWORD_SILENT
)) {
570 flags
|= ASK_PASSWORD_SILENT
;
572 /* There are two ways to enter silent mode. Either by pressing backspace as
573 * first key (and only as first key), or ... */
576 (void) loop_write(ttyfd
, NO_ECHO
, SIZE_MAX
);
578 } else if (ttyfd
>= 0)
579 (void) loop_write(ttyfd
, "\a", 1);
581 } else if (c
== '\t' && !FLAGS_SET(flags
, ASK_PASSWORD_SILENT
)) {
583 (void) backspace_string(ttyfd
, passphrase
);
584 flags
|= ASK_PASSWORD_SILENT
;
586 /* ... or by pressing TAB at any time. */
589 (void) loop_write(ttyfd
, NO_ECHO
, SIZE_MAX
);
591 } else if (p
>= sizeof(passphrase
)-1) {
593 /* Reached the size limit */
595 (void) loop_write(ttyfd
, "\a", 1);
600 if (!FLAGS_SET(flags
, ASK_PASSWORD_SILENT
) && ttyfd
>= 0) {
601 /* Check if we got a complete UTF-8 character now. If so, let's output one '*'. */
602 n
= utf8_encoded_valid_unichar(passphrase
+ codepoint
, SIZE_MAX
);
604 if (FLAGS_SET(flags
, ASK_PASSWORD_ECHO
))
605 (void) loop_write(ttyfd
, passphrase
+ codepoint
, n
);
607 (void) loop_write(ttyfd
,
608 special_glyph(SPECIAL_GLYPH_BULLET
),
618 x
= strndup(passphrase
, p
);
624 r
= strv_consume(&l
, x
);
630 r
= log_debug_errno(SYNTHETIC_ERRNO(ECANCELED
), "Password query was cancelled.");
633 (void) add_to_keyring_and_log(keyname
, flags
, l
);
640 if (ttyfd
>= 0 && reset_tty
) {
641 (void) loop_write(ttyfd
, "\n", 1);
642 (void) tcsetattr(ttyfd
, TCSADRAIN
, &old_termios
);
648 static int create_socket(char **ret
) {
649 _cleanup_free_
char *path
= NULL
;
650 union sockaddr_union sa
;
652 _cleanup_close_
int fd
= -EBADF
;
657 fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
661 if (asprintf(&path
, "/run/systemd/ask-password/sck.%" PRIx64
, random_u64()) < 0)
664 r
= sockaddr_un_set_path(&sa
.un
, path
);
670 if (bind(fd
, &sa
.sa
, sa_len
) < 0)
673 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSCRED
, true);
677 *ret
= TAKE_PTR(path
);
681 int ask_password_agent(
687 AskPasswordFlags flags
,
697 _cleanup_close_
int socket_fd
= -EBADF
, signal_fd
= -EBADF
, notify
= -EBADF
, fd
= -EBADF
;
698 char temp
[] = "/run/systemd/ask-password/tmp.XXXXXX";
699 char final
[sizeof(temp
)] = "";
700 _cleanup_free_
char *socket_name
= NULL
;
701 _cleanup_strv_free_erase_
char **l
= NULL
;
702 _cleanup_fclose_
FILE *f
= NULL
;
703 struct pollfd pollfd
[_FD_MAX
];
704 sigset_t mask
, oldmask
;
709 if (FLAGS_SET(flags
, ASK_PASSWORD_NO_AGENT
))
712 assert_se(sigemptyset(&mask
) >= 0);
713 assert_se(sigset_add_many(&mask
, SIGINT
, SIGTERM
, -1) >= 0);
714 assert_se(sigprocmask(SIG_BLOCK
, &mask
, &oldmask
) >= 0);
716 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
718 if (FLAGS_SET(flags
, ASK_PASSWORD_ACCEPT_CACHED
) && keyname
) {
719 r
= ask_password_keyring(keyname
, flags
, ret
);
723 } else if (r
!= -ENOKEY
)
726 notify
= inotify_init1(IN_CLOEXEC
| IN_NONBLOCK
);
732 r
= RET_NERRNO(inotify_add_watch(notify
, "/run/systemd/ask-password", IN_ATTRIB
/* for mtime */));
737 fd
= mkostemp_safe(temp
);
743 (void) fchmod(fd
, 0644);
745 f
= take_fdopen(&fd
, "w");
751 signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
757 socket_fd
= create_socket(&socket_name
);
769 "NotAfter="USEC_FMT
"\n"
773 FLAGS_SET(flags
, ASK_PASSWORD_ACCEPT_CACHED
),
774 FLAGS_SET(flags
, ASK_PASSWORD_ECHO
),
776 FLAGS_SET(flags
, ASK_PASSWORD_SILENT
));
779 fprintf(f
, "Message=%s\n", message
);
782 fprintf(f
, "Icon=%s\n", icon
);
785 fprintf(f
, "Id=%s\n", id
);
787 r
= fflush_and_check(f
);
791 memcpy(final
, temp
, sizeof(temp
));
793 final
[sizeof(final
)-11] = 'a';
794 final
[sizeof(final
)-10] = 's';
795 final
[sizeof(final
)-9] = 'k';
797 r
= RET_NERRNO(rename(temp
, final
));
802 pollfd
[FD_SOCKET
].fd
= socket_fd
;
803 pollfd
[FD_SOCKET
].events
= POLLIN
;
804 pollfd
[FD_SIGNAL
].fd
= signal_fd
;
805 pollfd
[FD_SIGNAL
].events
= POLLIN
;
806 pollfd
[FD_INOTIFY
].fd
= notify
;
807 pollfd
[FD_INOTIFY
].events
= POLLIN
;
810 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred
))) control
;
811 char passphrase
[LINE_MAX
+1];
818 timeout
= usec_sub_unsigned(until
, now(CLOCK_MONOTONIC
));
820 timeout
= USEC_INFINITY
;
822 r
= ppoll_usec(pollfd
, notify
>= 0 ? _FD_MAX
: _FD_MAX
- 1, timeout
);
832 if (pollfd
[FD_SIGNAL
].revents
& POLLIN
) {
837 if (notify
>= 0 && pollfd
[FD_INOTIFY
].revents
!= 0) {
838 (void) flush_fd(notify
);
840 r
= ask_password_keyring(keyname
, flags
, ret
);
844 } else if (r
!= -ENOKEY
)
848 if (pollfd
[FD_SOCKET
].revents
== 0)
851 if (pollfd
[FD_SOCKET
].revents
!= POLLIN
) {
856 iovec
= IOVEC_MAKE(passphrase
, sizeof(passphrase
));
858 struct msghdr msghdr
= {
861 .msg_control
= &control
,
862 .msg_controllen
= sizeof(control
),
865 n
= recvmsg_safe(socket_fd
, &msghdr
, 0);
866 if (ERRNO_IS_NEG_TRANSIENT(n
))
868 else if (n
== -EXFULL
) {
869 log_debug("Got message with truncated control data, ignoring.");
876 CLEANUP_ERASE(passphrase
);
878 cmsg_close_all(&msghdr
);
881 log_debug("Message too short");
885 ucred
= CMSG_FIND_DATA(&msghdr
, SOL_SOCKET
, SCM_CREDENTIALS
, struct ucred
);
887 log_debug("Received message without credentials. Ignoring.");
891 if (ucred
->uid
!= 0) {
892 log_debug("Got request from unprivileged user. Ignoring.");
896 if (passphrase
[0] == '+') {
897 /* An empty message refers to the empty password */
901 l
= strv_parse_nulstr(passphrase
+1, n
-1);
907 if (strv_isempty(l
)) {
909 log_debug("Invalid packet");
916 if (passphrase
[0] == '-') {
921 log_debug("Invalid packet");
925 (void) add_to_keyring_and_log(keyname
, flags
, l
);
932 (void) unlink(socket_name
);
937 (void) unlink(final
);
939 assert_se(sigprocmask(SIG_SETMASK
, &oldmask
, NULL
) == 0);
943 static int ask_password_credential(const char *credential_name
, AskPasswordFlags flags
, char ***ret
) {
944 _cleanup_(erase_and_freep
) char *buffer
= NULL
;
949 assert(credential_name
);
952 r
= read_credential(credential_name
, (void**) &buffer
, &size
);
953 if (IN_SET(r
, -ENXIO
, -ENOENT
)) /* No credentials passed or this credential not defined? */
956 l
= strv_parse_nulstr(buffer
, size
);
964 int ask_password_auto(
967 const char *id
, /* id in "ask-password" protocol */
968 const char *key_name
, /* name in kernel keyring */
969 const char *credential_name
, /* name in $CREDENTIALS_DIRECTORY directory */
971 AskPasswordFlags flags
,
978 if (!FLAGS_SET(flags
, ASK_PASSWORD_NO_CREDENTIAL
) && credential_name
) {
979 r
= ask_password_credential(credential_name
, flags
, ret
);
984 if (FLAGS_SET(flags
, ASK_PASSWORD_ACCEPT_CACHED
) &&
986 (FLAGS_SET(flags
, ASK_PASSWORD_NO_TTY
) || !isatty(STDIN_FILENO
)) &&
987 FLAGS_SET(flags
, ASK_PASSWORD_NO_AGENT
)) {
988 r
= ask_password_keyring(key_name
, flags
, ret
);
993 if (!FLAGS_SET(flags
, ASK_PASSWORD_NO_TTY
) && isatty(STDIN_FILENO
))
994 return ask_password_tty(-1, message
, key_name
, until
, flags
, NULL
, ret
);
996 if (!FLAGS_SET(flags
, ASK_PASSWORD_NO_AGENT
))
997 return ask_password_agent(message
, icon
, id
, key_name
, until
, flags
, ret
);