1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
13 #include <sys/inotify.h>
14 #include <sys/signalfd.h>
22 #include "alloc-util.h"
23 #include "ask-password-api.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
);
208 if (m
== (size_t) -1)
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
;
279 int sleep_for
= -1, j
;
284 y
= now(CLOCK_MONOTONIC
);
291 sleep_for
= (int) ((until
- y
) / USEC_PER_MSEC
);
294 if (flag_file
&& access(flag_file
, F_OK
) < 0) {
299 j
= poll(pollfd
, notify
>= 0 ? 2 : 1, sleep_for
);
311 if (pollfd
[POLL_SOCKET
].revents
& POLLNVAL
||
312 (notify
>= 0 && pollfd
[POLL_INOTIFY
].revents
& POLLNVAL
)) {
317 if (notify
>= 0 && pollfd
[POLL_INOTIFY
].revents
!= 0)
318 (void) flush_fd(notify
);
320 if (pollfd
[POLL_SOCKET
].revents
== 0)
323 k
= read(fd
, buffer
+ p
, sizeof(buffer
) - p
);
325 if (IN_SET(errno
, EINTR
, EAGAIN
))
340 if (buffer
[0] == 5) {
342 if (flags
& ASK_PASSWORD_ACCEPT_CACHED
) {
343 /* Hmm, first try with cached
344 * passwords failed, so let's retry
345 * with a normal password request */
346 packet
= mfree(packet
);
348 if (asprintf(&packet
, "*\002%c%s%n", (int) (strlen(message
) + 1), message
, &n
) < 0) {
353 r
= loop_write(fd
, packet
, n
+1, true);
357 flags
&= ~ASK_PASSWORD_ACCEPT_CACHED
;
362 /* No password, because UI not shown */
366 } else if (IN_SET(buffer
[0], 2, 9)) {
370 /* One or more answers */
374 memcpy(&size
, buffer
+1, sizeof(size
));
375 size
= le32toh(size
);
376 if (size
+ 5 > sizeof(buffer
)) {
384 l
= strv_parse_nulstr(buffer
+ 5, size
);
403 explicit_bzero_safe(buffer
, sizeof(buffer
));
407 #define NO_ECHO "(no echo) "
408 #define PRESS_TAB "(press TAB for no echo) "
409 #define SKIPPED "(skipped)"
411 int ask_password_tty(
416 AskPasswordFlags flags
,
417 const char *flag_file
,
426 bool reset_tty
= false, dirty
= false, use_color
= false, press_tab_visible
= false;
427 _cleanup_close_
int cttyfd
= -1, notify
= -1;
428 struct termios old_termios
, new_termios
;
429 char passphrase
[LINE_MAX
+ 1] = {}, *x
;
430 _cleanup_strv_free_erase_
char **l
= NULL
;
431 struct pollfd pollfd
[_POLL_MAX
];
432 size_t p
= 0, codepoint
= 0;
437 if (flags
& ASK_PASSWORD_NO_TTY
)
441 message
= "Password:";
444 message
= strjoina(special_glyph(SPECIAL_GLYPH_LOCK_AND_KEY
), " ", message
);
446 if (flag_file
|| ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
)) {
447 notify
= inotify_init1(IN_CLOEXEC
|IN_NONBLOCK
);
452 if (inotify_add_watch(notify
, flag_file
, IN_ATTRIB
/* for the link count */) < 0)
455 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
) {
456 r
= ask_password_keyring(keyname
, flags
, ret
);
459 else if (r
!= -ENOKEY
)
462 if (inotify_add_watch(notify
, "/run/systemd/ask-password", IN_ATTRIB
/* for mtime */) < 0)
466 /* If the caller didn't specify a TTY, then use the controlling tty, if we can. */
468 ttyfd
= cttyfd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
471 if (tcgetattr(ttyfd
, &old_termios
) < 0)
474 if (flags
& ASK_PASSWORD_CONSOLE_COLOR
)
475 use_color
= dev_console_colors_enabled();
477 use_color
= colors_enabled();
480 (void) loop_write(ttyfd
, ANSI_HIGHLIGHT
, STRLEN(ANSI_HIGHLIGHT
), false);
482 (void) loop_write(ttyfd
, message
, strlen(message
), false);
483 (void) loop_write(ttyfd
, " ", 1, false);
485 if (!(flags
& ASK_PASSWORD_SILENT
) && !(flags
& ASK_PASSWORD_ECHO
)) {
487 (void) loop_write(ttyfd
, ANSI_GREY
, STRLEN(ANSI_GREY
), false);
488 (void) loop_write(ttyfd
, PRESS_TAB
, strlen(PRESS_TAB
), false);
489 press_tab_visible
= true;
493 (void) loop_write(ttyfd
, ANSI_NORMAL
, STRLEN(ANSI_NORMAL
), false);
495 new_termios
= old_termios
;
496 new_termios
.c_lflag
&= ~(ICANON
|ECHO
);
497 new_termios
.c_cc
[VMIN
] = 1;
498 new_termios
.c_cc
[VTIME
] = 0;
500 if (tcsetattr(ttyfd
, TCSADRAIN
, &new_termios
) < 0) {
508 pollfd
[POLL_TTY
] = (struct pollfd
) {
509 .fd
= ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
,
512 pollfd
[POLL_INOTIFY
] = (struct pollfd
) {
518 _cleanup_(erase_char
) char c
;
519 int sleep_for
= -1, k
;
525 y
= now(CLOCK_MONOTONIC
);
532 sleep_for
= (int) DIV_ROUND_UP(until
- y
, USEC_PER_MSEC
);
536 if (access(flag_file
, F_OK
) < 0) {
541 k
= poll(pollfd
, notify
>= 0 ? 2 : 1, sleep_for
);
553 if ((pollfd
[POLL_TTY
].revents
& POLLNVAL
) ||
554 (notify
>= 0 && (pollfd
[POLL_INOTIFY
].revents
& POLLNVAL
))) {
559 if (notify
>= 0 && pollfd
[POLL_INOTIFY
].revents
!= 0 && keyname
) {
560 (void) flush_fd(notify
);
562 r
= ask_password_keyring(keyname
, flags
, ret
);
566 } else if (r
!= -ENOKEY
)
570 if (pollfd
[POLL_TTY
].revents
== 0)
573 n
= read(ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
, &c
, 1);
575 if (IN_SET(errno
, EINTR
, EAGAIN
))
583 if (press_tab_visible
) {
585 backspace_chars(ttyfd
, strlen(PRESS_TAB
));
586 press_tab_visible
= false;
589 /* We treat EOF, newline and NUL byte all as valid end markers */
590 if (n
== 0 || c
== '\n' || c
== 0)
593 if (c
== 4) { /* C-d also known as EOT */
595 (void) loop_write(ttyfd
, SKIPPED
, strlen(SKIPPED
), false);
600 if (c
== 21) { /* C-u */
602 if (!(flags
& ASK_PASSWORD_SILENT
))
603 (void) backspace_string(ttyfd
, passphrase
);
605 explicit_bzero_safe(passphrase
, sizeof(passphrase
));
608 } else if (IN_SET(c
, '\b', 127)) {
613 if (!(flags
& ASK_PASSWORD_SILENT
))
614 (void) backspace_chars(ttyfd
, 1);
616 /* Remove a full UTF-8 codepoint from the end. For that, figure out where the
622 z
= utf8_encoded_valid_unichar(passphrase
+ q
, (size_t) -1);
624 q
= (size_t) -1; /* Invalid UTF8! */
628 if (q
+ z
>= p
) /* This one brings us over the edge */
634 p
= codepoint
= q
== (size_t) -1 ? p
- 1 : q
;
635 explicit_bzero_safe(passphrase
+ p
, sizeof(passphrase
) - p
);
637 } else if (!dirty
&& !(flags
& ASK_PASSWORD_SILENT
)) {
639 flags
|= ASK_PASSWORD_SILENT
;
641 /* There are two ways to enter silent mode. Either by pressing backspace as
642 * first key (and only as first key), or ... */
645 (void) loop_write(ttyfd
, NO_ECHO
, strlen(NO_ECHO
), false);
647 } else if (ttyfd
>= 0)
648 (void) loop_write(ttyfd
, "\a", 1, false);
650 } else if (c
== '\t' && !(flags
& ASK_PASSWORD_SILENT
)) {
652 (void) backspace_string(ttyfd
, passphrase
);
653 flags
|= ASK_PASSWORD_SILENT
;
655 /* ... or by pressing TAB at any time. */
658 (void) loop_write(ttyfd
, NO_ECHO
, strlen(NO_ECHO
), false);
660 } else if (p
>= sizeof(passphrase
)-1) {
662 /* Reached the size limit */
664 (void) loop_write(ttyfd
, "\a", 1, false);
669 if (!(flags
& ASK_PASSWORD_SILENT
) && ttyfd
>= 0) {
670 /* Check if we got a complete UTF-8 character now. If so, let's output one '*'. */
671 n
= utf8_encoded_valid_unichar(passphrase
+ codepoint
, (size_t) -1);
673 if (flags
& ASK_PASSWORD_ECHO
)
674 (void) loop_write(ttyfd
, passphrase
+ codepoint
, n
, false);
676 (void) loop_write(ttyfd
, "*", 1, false);
685 x
= strndup(passphrase
, p
);
686 explicit_bzero_safe(passphrase
, sizeof(passphrase
));
692 r
= strv_consume(&l
, x
);
698 r
= log_debug_errno(SYNTHETIC_ERRNO(ECANCELED
), "Password query was cancelled.");
701 (void) add_to_keyring_and_log(keyname
, flags
, l
);
708 if (ttyfd
>= 0 && reset_tty
) {
709 (void) loop_write(ttyfd
, "\n", 1, false);
710 (void) tcsetattr(ttyfd
, TCSADRAIN
, &old_termios
);
716 static int create_socket(char **ret
) {
717 _cleanup_free_
char *path
= NULL
;
718 union sockaddr_union sa
;
720 _cleanup_close_
int fd
= -1;
725 fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
729 if (asprintf(&path
, "/run/systemd/ask-password/sck.%" PRIx64
, random_u64()) < 0)
732 r
= sockaddr_un_set_path(&sa
.un
, path
);
738 if (bind(fd
, &sa
.sa
, sa_len
) < 0)
741 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSCRED
, true);
745 *ret
= TAKE_PTR(path
);
749 int ask_password_agent(
755 AskPasswordFlags flags
,
765 _cleanup_close_
int socket_fd
= -1, signal_fd
= -1, notify
= -1, fd
= -1;
766 char temp
[] = "/run/systemd/ask-password/tmp.XXXXXX";
767 char final
[sizeof(temp
)] = "";
768 _cleanup_free_
char *socket_name
= NULL
;
769 _cleanup_strv_free_erase_
char **l
= NULL
;
770 _cleanup_fclose_
FILE *f
= NULL
;
771 struct pollfd pollfd
[_FD_MAX
];
772 sigset_t mask
, oldmask
;
777 if (flags
& ASK_PASSWORD_NO_AGENT
)
780 assert_se(sigemptyset(&mask
) >= 0);
781 assert_se(sigset_add_many(&mask
, SIGINT
, SIGTERM
, -1) >= 0);
782 assert_se(sigprocmask(SIG_BLOCK
, &mask
, &oldmask
) >= 0);
784 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
786 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
) {
787 r
= ask_password_keyring(keyname
, flags
, ret
);
791 } else if (r
!= -ENOKEY
)
794 notify
= inotify_init1(IN_CLOEXEC
| IN_NONBLOCK
);
799 if (inotify_add_watch(notify
, "/run/systemd/ask-password", IN_ATTRIB
/* for mtime */) < 0) {
805 fd
= mkostemp_safe(temp
);
811 (void) fchmod(fd
, 0644);
813 f
= take_fdopen(&fd
, "w");
819 signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
825 socket_fd
= create_socket(&socket_name
);
837 "NotAfter="USEC_FMT
"\n",
840 (flags
& ASK_PASSWORD_ACCEPT_CACHED
) ? 1 : 0,
841 (flags
& ASK_PASSWORD_ECHO
) ? 1 : 0,
845 fprintf(f
, "Message=%s\n", message
);
848 fprintf(f
, "Icon=%s\n", icon
);
851 fprintf(f
, "Id=%s\n", id
);
853 r
= fflush_and_check(f
);
857 memcpy(final
, temp
, sizeof(temp
));
859 final
[sizeof(final
)-11] = 'a';
860 final
[sizeof(final
)-10] = 's';
861 final
[sizeof(final
)-9] = 'k';
863 if (rename(temp
, final
) < 0) {
869 pollfd
[FD_SOCKET
].fd
= socket_fd
;
870 pollfd
[FD_SOCKET
].events
= POLLIN
;
871 pollfd
[FD_SIGNAL
].fd
= signal_fd
;
872 pollfd
[FD_SIGNAL
].events
= POLLIN
;
873 pollfd
[FD_INOTIFY
].fd
= notify
;
874 pollfd
[FD_INOTIFY
].events
= POLLIN
;
877 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred
))) control
;
878 char passphrase
[LINE_MAX
+1];
885 t
= now(CLOCK_MONOTONIC
);
887 if (until
> 0 && until
<= t
) {
892 k
= poll(pollfd
, notify
>= 0 ? _FD_MAX
: _FD_MAX
- 1, until
> 0 ? (int) ((until
-t
)/USEC_PER_MSEC
) : -1);
906 if (pollfd
[FD_SOCKET
].revents
& POLLNVAL
||
907 pollfd
[FD_SIGNAL
].revents
& POLLNVAL
||
908 (notify
>= 0 && pollfd
[FD_INOTIFY
].revents
& POLLNVAL
)) {
913 if (pollfd
[FD_SIGNAL
].revents
& POLLIN
) {
918 if (notify
>= 0 && pollfd
[FD_INOTIFY
].revents
!= 0) {
919 (void) flush_fd(notify
);
921 r
= ask_password_keyring(keyname
, flags
, ret
);
925 } else if (r
!= -ENOKEY
)
929 if (pollfd
[FD_SOCKET
].revents
== 0)
932 if (pollfd
[FD_SOCKET
].revents
!= POLLIN
) {
937 iovec
= IOVEC_MAKE(passphrase
, sizeof(passphrase
));
939 struct msghdr msghdr
= {
942 .msg_control
= &control
,
943 .msg_controllen
= sizeof(control
),
946 n
= recvmsg_safe(socket_fd
, &msghdr
, 0);
947 if (IN_SET(n
, -EAGAIN
, -EINTR
))
954 cmsg_close_all(&msghdr
);
957 log_debug("Message too short");
961 ucred
= CMSG_FIND_DATA(&msghdr
, SOL_SOCKET
, SCM_CREDENTIALS
, struct ucred
);
963 log_debug("Received message without credentials. Ignoring.");
967 if (ucred
->uid
!= 0) {
968 log_debug("Got request from unprivileged user. Ignoring.");
972 if (passphrase
[0] == '+') {
973 /* An empty message refers to the empty password */
977 l
= strv_parse_nulstr(passphrase
+1, n
-1);
978 explicit_bzero_safe(passphrase
, n
);
984 if (strv_isempty(l
)) {
986 log_debug("Invalid packet");
993 if (passphrase
[0] == '-') {
998 log_debug("Invalid packet");
1002 (void) add_to_keyring_and_log(keyname
, flags
, l
);
1009 (void) unlink(socket_name
);
1011 (void) unlink(temp
);
1014 (void) unlink(final
);
1016 assert_se(sigprocmask(SIG_SETMASK
, &oldmask
, NULL
) == 0);
1020 int ask_password_auto(
1021 const char *message
,
1024 const char *keyname
,
1026 AskPasswordFlags flags
,
1033 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) &&
1035 ((flags
& ASK_PASSWORD_NO_TTY
) || !isatty(STDIN_FILENO
)) &&
1036 (flags
& ASK_PASSWORD_NO_AGENT
)) {
1037 r
= ask_password_keyring(keyname
, flags
, ret
);
1042 if (!(flags
& ASK_PASSWORD_NO_TTY
) && isatty(STDIN_FILENO
))
1043 return ask_password_tty(-1, message
, keyname
, until
, flags
, NULL
, ret
);
1045 if (!(flags
& ASK_PASSWORD_NO_AGENT
))
1046 return ask_password_agent(message
, icon
, id
, keyname
, until
, flags
, ret
);