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"
27 #include "format-util.h"
30 #include "locale-util.h"
33 #include "memory-util.h"
34 #include "missing_syscall.h"
36 #include "process-util.h"
37 #include "random-util.h"
38 #include "signal-util.h"
39 #include "socket-util.h"
40 #include "string-util.h"
42 #include "terminal-util.h"
43 #include "time-util.h"
44 #include "tmpfile-util.h"
45 #include "umask-util.h"
48 #define KEYRING_TIMEOUT_USEC ((5 * USEC_PER_MINUTE) / 2)
50 static int lookup_key(const char *keyname
, key_serial_t
*ret
) {
56 serial
= request_key("user", keyname
, NULL
, 0);
58 return negative_errno();
64 static int retrieve_key(key_serial_t serial
, char ***ret
) {
65 size_t nfinal
, m
= 100;
67 _cleanup_(erase_and_freep
) char *pfinal
= NULL
;
72 _cleanup_(erase_and_freep
) char *p
= NULL
;
79 n
= keyctl(KEYCTL_READ
, (unsigned long) serial
, (unsigned long) p
, (unsigned long) m
, 0);
82 if ((size_t) n
<= m
) {
88 if (m
> LONG_MAX
/ 2) /* overflow check */
93 l
= strv_parse_nulstr(pfinal
, nfinal
);
101 static int add_to_keyring(const char *keyname
, AskPasswordFlags flags
, char **passwords
) {
102 _cleanup_strv_free_erase_
char **l
= NULL
;
103 _cleanup_(erase_and_freep
) char *p
= NULL
;
110 if (!(flags
& ASK_PASSWORD_PUSH_CACHE
))
112 if (strv_isempty(passwords
))
115 r
= lookup_key(keyname
, &serial
);
117 r
= retrieve_key(serial
, &l
);
120 } else if (r
!= -ENOKEY
)
123 r
= strv_extend_strv(&l
, passwords
, true);
127 r
= strv_make_nulstr(l
, &p
, &n
);
131 serial
= add_key("user", keyname
, p
, n
, KEY_SPEC_USER_KEYRING
);
135 if (keyctl(KEYCTL_SET_TIMEOUT
,
136 (unsigned long) serial
,
137 (unsigned long) DIV_ROUND_UP(KEYRING_TIMEOUT_USEC
, USEC_PER_SEC
), 0, 0) < 0)
138 log_debug_errno(errno
, "Failed to adjust kernel keyring key timeout: %m");
140 /* Tell everyone to check the keyring */
141 (void) touch("/run/systemd/ask-password");
143 log_debug("Added key to kernel keyring as %" PRIi32
".", serial
);
148 static int add_to_keyring_and_log(const char *keyname
, AskPasswordFlags flags
, char **passwords
) {
153 r
= add_to_keyring(keyname
, flags
, passwords
);
155 return log_debug_errno(r
, "Failed to add password to kernel keyring: %m");
160 static int ask_password_keyring(const char *keyname
, AskPasswordFlags flags
, char ***ret
) {
168 if (!(flags
& ASK_PASSWORD_ACCEPT_CACHED
))
171 r
= lookup_key(keyname
, &serial
);
172 if (ERRNO_IS_NOT_SUPPORTED(r
) || r
== -EPERM
) /* when retrieving the distinction between "kernel or
173 * container manager don't support or allow this" and
174 * "no matching key known" doesn't matter. Note that we
175 * propagate EACCESS here (even if EPERM not) since
176 * that is used if the keyring is available but we lack
177 * access to the key. */
182 return retrieve_key(serial
, ret
);
185 static int backspace_chars(int ttyfd
, size_t p
) {
189 _cleanup_free_
char *buf
= malloc_multiply(3, p
);
193 for (size_t i
= 0; i
< p
; i
++)
194 memcpy(buf
+ 3 * i
, "\b \b", 3);
196 return loop_write(ttyfd
, buf
, 3*p
, false);
199 static int backspace_string(int ttyfd
, const char *str
) {
202 /* Backspaces through enough characters to entirely undo printing of the specified string. */
207 size_t m
= utf8_n_codepoints(str
);
209 m
= strlen(str
); /* Not a valid UTF-8 string? If so, let's backspace the number of bytes
210 * output. Most likely this happened because we are not in an UTF-8 locale,
211 * and in that case that is the correct thing to do. And even if it's not,
212 * terminals tend to stop backspacing at the leftmost column, hence
213 * backspacing too much should be mostly OK. */
215 return backspace_chars(ttyfd
, m
);
218 int ask_password_plymouth(
221 AskPasswordFlags flags
,
222 const char *flag_file
,
225 static const union sockaddr_union sa
= PLYMOUTH_SOCKET
;
226 _cleanup_close_
int fd
= -1, notify
= -1;
227 _cleanup_free_
char *packet
= NULL
;
230 struct pollfd pollfd
[2] = {};
231 char buffer
[LINE_MAX
];
241 message
= "Password:";
244 notify
= inotify_init1(IN_CLOEXEC
|IN_NONBLOCK
);
248 r
= inotify_add_watch(notify
, flag_file
, IN_ATTRIB
); /* for the link count */
253 fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
257 r
= connect(fd
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
));
261 if (flags
& ASK_PASSWORD_ACCEPT_CACHED
) {
262 packet
= strdup("c");
264 } else if (asprintf(&packet
, "*\002%c%s%n", (int) (strlen(message
) + 1), message
, &n
) < 0)
269 r
= loop_write(fd
, packet
, n
+ 1, true);
273 pollfd
[POLL_SOCKET
].fd
= fd
;
274 pollfd
[POLL_SOCKET
].events
= POLLIN
;
275 pollfd
[POLL_INOTIFY
].fd
= notify
;
276 pollfd
[POLL_INOTIFY
].events
= POLLIN
;
282 timeout
= usec_sub_unsigned(until
, now(CLOCK_MONOTONIC
));
284 timeout
= USEC_INFINITY
;
286 if (flag_file
&& access(flag_file
, F_OK
) < 0) {
291 r
= ppoll_usec(pollfd
, notify
>= 0 ? 2 : 1, timeout
);
301 if (notify
>= 0 && pollfd
[POLL_INOTIFY
].revents
!= 0)
302 (void) flush_fd(notify
);
304 if (pollfd
[POLL_SOCKET
].revents
== 0)
307 k
= read(fd
, buffer
+ p
, sizeof(buffer
) - p
);
309 if (IN_SET(errno
, EINTR
, EAGAIN
))
321 if (buffer
[0] == 5) {
323 if (flags
& ASK_PASSWORD_ACCEPT_CACHED
) {
324 /* Hmm, first try with cached
325 * passwords failed, so let's retry
326 * with a normal password request */
327 packet
= mfree(packet
);
329 if (asprintf(&packet
, "*\002%c%s%n", (int) (strlen(message
) + 1), message
, &n
) < 0) {
334 r
= loop_write(fd
, packet
, n
+1, true);
338 flags
&= ~ASK_PASSWORD_ACCEPT_CACHED
;
343 /* No password, because UI not shown */
347 } else if (IN_SET(buffer
[0], 2, 9)) {
351 /* One or more answers */
355 memcpy(&size
, buffer
+1, sizeof(size
));
356 size
= le32toh(size
);
357 if (size
+ 5 > sizeof(buffer
)) {
365 l
= strv_parse_nulstr(buffer
+ 5, size
);
384 explicit_bzero_safe(buffer
, sizeof(buffer
));
388 #define NO_ECHO "(no echo) "
389 #define PRESS_TAB "(press TAB for no echo) "
390 #define SKIPPED "(skipped)"
392 int ask_password_tty(
397 AskPasswordFlags flags
,
398 const char *flag_file
,
407 bool reset_tty
= false, dirty
= false, use_color
= false, press_tab_visible
= false;
408 _cleanup_close_
int cttyfd
= -1, notify
= -1;
409 struct termios old_termios
, new_termios
;
410 char passphrase
[LINE_MAX
+ 1] = {}, *x
;
411 _cleanup_strv_free_erase_
char **l
= NULL
;
412 struct pollfd pollfd
[_POLL_MAX
];
413 size_t p
= 0, codepoint
= 0;
418 if (flags
& ASK_PASSWORD_NO_TTY
)
422 message
= "Password:";
425 message
= strjoina(special_glyph(SPECIAL_GLYPH_LOCK_AND_KEY
), " ", message
);
427 if (flag_file
|| ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
)) {
428 notify
= inotify_init1(IN_CLOEXEC
|IN_NONBLOCK
);
433 if (inotify_add_watch(notify
, flag_file
, IN_ATTRIB
/* for the link count */) < 0)
436 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
) {
437 r
= ask_password_keyring(keyname
, flags
, ret
);
440 else if (r
!= -ENOKEY
)
443 if (inotify_add_watch(notify
, "/run/systemd/ask-password", IN_ATTRIB
/* for mtime */) < 0)
447 /* If the caller didn't specify a TTY, then use the controlling tty, if we can. */
449 ttyfd
= cttyfd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
452 if (tcgetattr(ttyfd
, &old_termios
) < 0)
455 if (flags
& ASK_PASSWORD_CONSOLE_COLOR
)
456 use_color
= dev_console_colors_enabled();
458 use_color
= colors_enabled();
461 (void) loop_write(ttyfd
, ANSI_HIGHLIGHT
, STRLEN(ANSI_HIGHLIGHT
), false);
463 (void) loop_write(ttyfd
, message
, strlen(message
), false);
464 (void) loop_write(ttyfd
, " ", 1, false);
466 if (!(flags
& ASK_PASSWORD_SILENT
) && !(flags
& ASK_PASSWORD_ECHO
)) {
468 (void) loop_write(ttyfd
, ansi_grey(), strlen(ansi_grey()), false);
469 (void) loop_write(ttyfd
, PRESS_TAB
, strlen(PRESS_TAB
), false);
470 press_tab_visible
= true;
474 (void) loop_write(ttyfd
, ANSI_NORMAL
, STRLEN(ANSI_NORMAL
), false);
476 new_termios
= old_termios
;
477 new_termios
.c_lflag
&= ~(ICANON
|ECHO
);
478 new_termios
.c_cc
[VMIN
] = 1;
479 new_termios
.c_cc
[VTIME
] = 0;
481 if (tcsetattr(ttyfd
, TCSADRAIN
, &new_termios
) < 0) {
489 pollfd
[POLL_TTY
] = (struct pollfd
) {
490 .fd
= ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
,
493 pollfd
[POLL_INOTIFY
] = (struct pollfd
) {
499 _cleanup_(erase_char
) char c
;
504 timeout
= usec_sub_unsigned(until
, now(CLOCK_MONOTONIC
));
506 timeout
= USEC_INFINITY
;
509 if (access(flag_file
, F_OK
) < 0) {
514 r
= ppoll_usec(pollfd
, notify
>= 0 ? 2 : 1, timeout
);
524 if (notify
>= 0 && pollfd
[POLL_INOTIFY
].revents
!= 0 && keyname
) {
525 (void) flush_fd(notify
);
527 r
= ask_password_keyring(keyname
, flags
, ret
);
531 } else if (r
!= -ENOKEY
)
535 if (pollfd
[POLL_TTY
].revents
== 0)
538 n
= read(ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
, &c
, 1);
540 if (IN_SET(errno
, EINTR
, EAGAIN
))
548 if (press_tab_visible
) {
550 backspace_chars(ttyfd
, strlen(PRESS_TAB
));
551 press_tab_visible
= false;
554 /* We treat EOF, newline and NUL byte all as valid end markers */
555 if (n
== 0 || c
== '\n' || c
== 0)
558 if (c
== 4) { /* C-d also known as EOT */
560 (void) loop_write(ttyfd
, SKIPPED
, strlen(SKIPPED
), false);
565 if (c
== 21) { /* C-u */
567 if (!(flags
& ASK_PASSWORD_SILENT
))
568 (void) backspace_string(ttyfd
, passphrase
);
570 explicit_bzero_safe(passphrase
, sizeof(passphrase
));
573 } else if (IN_SET(c
, '\b', 127)) {
578 if (!(flags
& ASK_PASSWORD_SILENT
))
579 (void) backspace_chars(ttyfd
, 1);
581 /* Remove a full UTF-8 codepoint from the end. For that, figure out where the
587 z
= utf8_encoded_valid_unichar(passphrase
+ q
, SIZE_MAX
);
589 q
= SIZE_MAX
; /* Invalid UTF8! */
593 if (q
+ z
>= p
) /* This one brings us over the edge */
599 p
= codepoint
= q
== SIZE_MAX
? p
- 1 : q
;
600 explicit_bzero_safe(passphrase
+ p
, sizeof(passphrase
) - p
);
602 } else if (!dirty
&& !(flags
& ASK_PASSWORD_SILENT
)) {
604 flags
|= ASK_PASSWORD_SILENT
;
606 /* There are two ways to enter silent mode. Either by pressing backspace as
607 * first key (and only as first key), or ... */
610 (void) loop_write(ttyfd
, NO_ECHO
, strlen(NO_ECHO
), false);
612 } else if (ttyfd
>= 0)
613 (void) loop_write(ttyfd
, "\a", 1, false);
615 } else if (c
== '\t' && !(flags
& ASK_PASSWORD_SILENT
)) {
617 (void) backspace_string(ttyfd
, passphrase
);
618 flags
|= ASK_PASSWORD_SILENT
;
620 /* ... or by pressing TAB at any time. */
623 (void) loop_write(ttyfd
, NO_ECHO
, strlen(NO_ECHO
), false);
625 } else if (p
>= sizeof(passphrase
)-1) {
627 /* Reached the size limit */
629 (void) loop_write(ttyfd
, "\a", 1, false);
634 if (!(flags
& ASK_PASSWORD_SILENT
) && ttyfd
>= 0) {
635 /* Check if we got a complete UTF-8 character now. If so, let's output one '*'. */
636 n
= utf8_encoded_valid_unichar(passphrase
+ codepoint
, SIZE_MAX
);
638 if (flags
& ASK_PASSWORD_ECHO
)
639 (void) loop_write(ttyfd
, passphrase
+ codepoint
, n
, false);
641 (void) loop_write(ttyfd
, "*", 1, false);
650 x
= strndup(passphrase
, p
);
651 explicit_bzero_safe(passphrase
, sizeof(passphrase
));
657 r
= strv_consume(&l
, x
);
663 r
= log_debug_errno(SYNTHETIC_ERRNO(ECANCELED
), "Password query was cancelled.");
666 (void) add_to_keyring_and_log(keyname
, flags
, l
);
673 if (ttyfd
>= 0 && reset_tty
) {
674 (void) loop_write(ttyfd
, "\n", 1, false);
675 (void) tcsetattr(ttyfd
, TCSADRAIN
, &old_termios
);
681 static int create_socket(char **ret
) {
682 _cleanup_free_
char *path
= NULL
;
683 union sockaddr_union sa
;
685 _cleanup_close_
int fd
= -1;
690 fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
694 if (asprintf(&path
, "/run/systemd/ask-password/sck.%" PRIx64
, random_u64()) < 0)
697 r
= sockaddr_un_set_path(&sa
.un
, path
);
703 if (bind(fd
, &sa
.sa
, sa_len
) < 0)
706 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSCRED
, true);
710 *ret
= TAKE_PTR(path
);
714 int ask_password_agent(
720 AskPasswordFlags flags
,
730 _cleanup_close_
int socket_fd
= -1, signal_fd
= -1, notify
= -1, fd
= -1;
731 char temp
[] = "/run/systemd/ask-password/tmp.XXXXXX";
732 char final
[sizeof(temp
)] = "";
733 _cleanup_free_
char *socket_name
= NULL
;
734 _cleanup_strv_free_erase_
char **l
= NULL
;
735 _cleanup_fclose_
FILE *f
= NULL
;
736 struct pollfd pollfd
[_FD_MAX
];
737 sigset_t mask
, oldmask
;
742 if (flags
& ASK_PASSWORD_NO_AGENT
)
745 assert_se(sigemptyset(&mask
) >= 0);
746 assert_se(sigset_add_many(&mask
, SIGINT
, SIGTERM
, -1) >= 0);
747 assert_se(sigprocmask(SIG_BLOCK
, &mask
, &oldmask
) >= 0);
749 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
751 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
) {
752 r
= ask_password_keyring(keyname
, flags
, ret
);
756 } else if (r
!= -ENOKEY
)
759 notify
= inotify_init1(IN_CLOEXEC
| IN_NONBLOCK
);
764 if (inotify_add_watch(notify
, "/run/systemd/ask-password", IN_ATTRIB
/* for mtime */) < 0) {
770 fd
= mkostemp_safe(temp
);
776 (void) fchmod(fd
, 0644);
778 f
= take_fdopen(&fd
, "w");
784 signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
790 socket_fd
= create_socket(&socket_name
);
802 "NotAfter="USEC_FMT
"\n",
805 (flags
& ASK_PASSWORD_ACCEPT_CACHED
) ? 1 : 0,
806 (flags
& ASK_PASSWORD_ECHO
) ? 1 : 0,
810 fprintf(f
, "Message=%s\n", message
);
813 fprintf(f
, "Icon=%s\n", icon
);
816 fprintf(f
, "Id=%s\n", id
);
818 r
= fflush_and_check(f
);
822 memcpy(final
, temp
, sizeof(temp
));
824 final
[sizeof(final
)-11] = 'a';
825 final
[sizeof(final
)-10] = 's';
826 final
[sizeof(final
)-9] = 'k';
828 if (rename(temp
, final
) < 0) {
834 pollfd
[FD_SOCKET
].fd
= socket_fd
;
835 pollfd
[FD_SOCKET
].events
= POLLIN
;
836 pollfd
[FD_SIGNAL
].fd
= signal_fd
;
837 pollfd
[FD_SIGNAL
].events
= POLLIN
;
838 pollfd
[FD_INOTIFY
].fd
= notify
;
839 pollfd
[FD_INOTIFY
].events
= POLLIN
;
842 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred
))) control
;
843 char passphrase
[LINE_MAX
+1];
850 timeout
= usec_sub_unsigned(until
, now(CLOCK_MONOTONIC
));
852 timeout
= USEC_INFINITY
;
854 r
= ppoll_usec(pollfd
, notify
>= 0 ? _FD_MAX
: _FD_MAX
- 1, timeout
);
864 if (pollfd
[FD_SIGNAL
].revents
& POLLIN
) {
869 if (notify
>= 0 && pollfd
[FD_INOTIFY
].revents
!= 0) {
870 (void) flush_fd(notify
);
872 r
= ask_password_keyring(keyname
, flags
, ret
);
876 } else if (r
!= -ENOKEY
)
880 if (pollfd
[FD_SOCKET
].revents
== 0)
883 if (pollfd
[FD_SOCKET
].revents
!= POLLIN
) {
888 iovec
= IOVEC_MAKE(passphrase
, sizeof(passphrase
));
890 struct msghdr msghdr
= {
893 .msg_control
= &control
,
894 .msg_controllen
= sizeof(control
),
897 n
= recvmsg_safe(socket_fd
, &msghdr
, 0);
898 if (IN_SET(n
, -EAGAIN
, -EINTR
))
901 log_debug("Got message with truncated control data, ignoring.");
909 cmsg_close_all(&msghdr
);
912 log_debug("Message too short");
916 ucred
= CMSG_FIND_DATA(&msghdr
, SOL_SOCKET
, SCM_CREDENTIALS
, struct ucred
);
918 log_debug("Received message without credentials. Ignoring.");
922 if (ucred
->uid
!= 0) {
923 log_debug("Got request from unprivileged user. Ignoring.");
927 if (passphrase
[0] == '+') {
928 /* An empty message refers to the empty password */
932 l
= strv_parse_nulstr(passphrase
+1, n
-1);
933 explicit_bzero_safe(passphrase
, n
);
939 if (strv_isempty(l
)) {
941 log_debug("Invalid packet");
948 if (passphrase
[0] == '-') {
953 log_debug("Invalid packet");
957 (void) add_to_keyring_and_log(keyname
, flags
, l
);
964 (void) unlink(socket_name
);
969 (void) unlink(final
);
971 assert_se(sigprocmask(SIG_SETMASK
, &oldmask
, NULL
) == 0);
975 static int ask_password_credential(const char *credential_name
, AskPasswordFlags flags
, char ***ret
) {
976 _cleanup_(erase_and_freep
) char *buffer
= NULL
;
981 assert(credential_name
);
984 r
= read_credential(credential_name
, (void**) &buffer
, &size
);
985 if (IN_SET(r
, -ENXIO
, -ENOENT
)) /* No credentials passed or this credential not defined? */
988 l
= strv_parse_nulstr(buffer
, size
);
996 int ask_password_auto(
999 const char *id
, /* id in "ask-password" protocol */
1000 const char *key_name
, /* name in kernel keyring */
1001 const char *credential_name
, /* name in $CREDENTIALS_DIRECTORY directory */
1003 AskPasswordFlags flags
,
1010 if (!(flags
& ASK_PASSWORD_NO_CREDENTIAL
) && credential_name
) {
1011 r
= ask_password_credential(credential_name
, flags
, ret
);
1016 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) &&
1018 ((flags
& ASK_PASSWORD_NO_TTY
) || !isatty(STDIN_FILENO
)) &&
1019 (flags
& ASK_PASSWORD_NO_AGENT
)) {
1020 r
= ask_password_keyring(key_name
, flags
, ret
);
1025 if (!(flags
& ASK_PASSWORD_NO_TTY
) && isatty(STDIN_FILENO
))
1026 return ask_password_tty(-1, message
, key_name
, until
, flags
, NULL
, ret
);
1028 if (!(flags
& ASK_PASSWORD_NO_AGENT
))
1029 return ask_password_agent(message
, icon
, id
, key_name
, until
, flags
, ret
);