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
))
337 if (buffer
[0] == 5) {
339 if (flags
& ASK_PASSWORD_ACCEPT_CACHED
) {
340 /* Hmm, first try with cached
341 * passwords failed, so let's retry
342 * with a normal password request */
343 packet
= mfree(packet
);
345 if (asprintf(&packet
, "*\002%c%s%n", (int) (strlen(message
) + 1), message
, &n
) < 0) {
350 r
= loop_write(fd
, packet
, n
+1, true);
354 flags
&= ~ASK_PASSWORD_ACCEPT_CACHED
;
359 /* No password, because UI not shown */
363 } else if (IN_SET(buffer
[0], 2, 9)) {
367 /* One or more answers */
371 memcpy(&size
, buffer
+1, sizeof(size
));
372 size
= le32toh(size
);
373 if (size
+ 5 > sizeof(buffer
)) {
381 l
= strv_parse_nulstr(buffer
+ 5, size
);
400 explicit_bzero_safe(buffer
, sizeof(buffer
));
404 #define NO_ECHO "(no echo) "
405 #define PRESS_TAB "(press TAB for no echo) "
406 #define SKIPPED "(skipped)"
408 int ask_password_tty(
413 AskPasswordFlags flags
,
414 const char *flag_file
,
423 bool reset_tty
= false, dirty
= false, use_color
= false, press_tab_visible
= false;
424 _cleanup_close_
int cttyfd
= -1, notify
= -1;
425 struct termios old_termios
, new_termios
;
426 char passphrase
[LINE_MAX
+ 1] = {}, *x
;
427 _cleanup_strv_free_erase_
char **l
= NULL
;
428 struct pollfd pollfd
[_POLL_MAX
];
429 size_t p
= 0, codepoint
= 0;
434 if (flags
& ASK_PASSWORD_NO_TTY
)
438 message
= "Password:";
441 message
= strjoina(special_glyph(SPECIAL_GLYPH_LOCK_AND_KEY
), " ", message
);
443 if (flag_file
|| ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
)) {
444 notify
= inotify_init1(IN_CLOEXEC
|IN_NONBLOCK
);
449 if (inotify_add_watch(notify
, flag_file
, IN_ATTRIB
/* for the link count */) < 0)
452 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
) {
453 r
= ask_password_keyring(keyname
, flags
, ret
);
456 else if (r
!= -ENOKEY
)
459 if (inotify_add_watch(notify
, "/run/systemd/ask-password", IN_ATTRIB
/* for mtime */) < 0)
463 /* If the caller didn't specify a TTY, then use the controlling tty, if we can. */
465 ttyfd
= cttyfd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
468 if (tcgetattr(ttyfd
, &old_termios
) < 0)
471 if (flags
& ASK_PASSWORD_CONSOLE_COLOR
)
472 use_color
= dev_console_colors_enabled();
474 use_color
= colors_enabled();
477 (void) loop_write(ttyfd
, ANSI_HIGHLIGHT
, STRLEN(ANSI_HIGHLIGHT
), false);
479 (void) loop_write(ttyfd
, message
, strlen(message
), false);
480 (void) loop_write(ttyfd
, " ", 1, false);
482 if (!(flags
& ASK_PASSWORD_SILENT
) && !(flags
& ASK_PASSWORD_ECHO
)) {
484 (void) loop_write(ttyfd
, ansi_grey(), strlen(ansi_grey()), false);
485 (void) loop_write(ttyfd
, PRESS_TAB
, strlen(PRESS_TAB
), false);
486 press_tab_visible
= true;
490 (void) loop_write(ttyfd
, ANSI_NORMAL
, STRLEN(ANSI_NORMAL
), false);
492 new_termios
= old_termios
;
493 new_termios
.c_lflag
&= ~(ICANON
|ECHO
);
494 new_termios
.c_cc
[VMIN
] = 1;
495 new_termios
.c_cc
[VTIME
] = 0;
497 if (tcsetattr(ttyfd
, TCSADRAIN
, &new_termios
) < 0) {
505 pollfd
[POLL_TTY
] = (struct pollfd
) {
506 .fd
= ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
,
509 pollfd
[POLL_INOTIFY
] = (struct pollfd
) {
515 _cleanup_(erase_char
) char c
;
516 int sleep_for
= -1, k
;
522 y
= now(CLOCK_MONOTONIC
);
529 sleep_for
= (int) DIV_ROUND_UP(until
- y
, USEC_PER_MSEC
);
533 if (access(flag_file
, F_OK
) < 0) {
538 k
= poll(pollfd
, notify
>= 0 ? 2 : 1, sleep_for
);
550 if ((pollfd
[POLL_TTY
].revents
& POLLNVAL
) ||
551 (notify
>= 0 && (pollfd
[POLL_INOTIFY
].revents
& POLLNVAL
))) {
556 if (notify
>= 0 && pollfd
[POLL_INOTIFY
].revents
!= 0 && keyname
) {
557 (void) flush_fd(notify
);
559 r
= ask_password_keyring(keyname
, flags
, ret
);
563 } else if (r
!= -ENOKEY
)
567 if (pollfd
[POLL_TTY
].revents
== 0)
570 n
= read(ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
, &c
, 1);
572 if (IN_SET(errno
, EINTR
, EAGAIN
))
580 if (press_tab_visible
) {
582 backspace_chars(ttyfd
, strlen(PRESS_TAB
));
583 press_tab_visible
= false;
586 /* We treat EOF, newline and NUL byte all as valid end markers */
587 if (n
== 0 || c
== '\n' || c
== 0)
590 if (c
== 4) { /* C-d also known as EOT */
592 (void) loop_write(ttyfd
, SKIPPED
, strlen(SKIPPED
), false);
597 if (c
== 21) { /* C-u */
599 if (!(flags
& ASK_PASSWORD_SILENT
))
600 (void) backspace_string(ttyfd
, passphrase
);
602 explicit_bzero_safe(passphrase
, sizeof(passphrase
));
605 } else if (IN_SET(c
, '\b', 127)) {
610 if (!(flags
& ASK_PASSWORD_SILENT
))
611 (void) backspace_chars(ttyfd
, 1);
613 /* Remove a full UTF-8 codepoint from the end. For that, figure out where the
619 z
= utf8_encoded_valid_unichar(passphrase
+ q
, (size_t) -1);
621 q
= (size_t) -1; /* Invalid UTF8! */
625 if (q
+ z
>= p
) /* This one brings us over the edge */
631 p
= codepoint
= q
== (size_t) -1 ? p
- 1 : q
;
632 explicit_bzero_safe(passphrase
+ p
, sizeof(passphrase
) - p
);
634 } else if (!dirty
&& !(flags
& ASK_PASSWORD_SILENT
)) {
636 flags
|= ASK_PASSWORD_SILENT
;
638 /* There are two ways to enter silent mode. Either by pressing backspace as
639 * first key (and only as first key), or ... */
642 (void) loop_write(ttyfd
, NO_ECHO
, strlen(NO_ECHO
), false);
644 } else if (ttyfd
>= 0)
645 (void) loop_write(ttyfd
, "\a", 1, false);
647 } else if (c
== '\t' && !(flags
& ASK_PASSWORD_SILENT
)) {
649 (void) backspace_string(ttyfd
, passphrase
);
650 flags
|= ASK_PASSWORD_SILENT
;
652 /* ... or by pressing TAB at any time. */
655 (void) loop_write(ttyfd
, NO_ECHO
, strlen(NO_ECHO
), false);
657 } else if (p
>= sizeof(passphrase
)-1) {
659 /* Reached the size limit */
661 (void) loop_write(ttyfd
, "\a", 1, false);
666 if (!(flags
& ASK_PASSWORD_SILENT
) && ttyfd
>= 0) {
667 /* Check if we got a complete UTF-8 character now. If so, let's output one '*'. */
668 n
= utf8_encoded_valid_unichar(passphrase
+ codepoint
, (size_t) -1);
670 if (flags
& ASK_PASSWORD_ECHO
)
671 (void) loop_write(ttyfd
, passphrase
+ codepoint
, n
, false);
673 (void) loop_write(ttyfd
, "*", 1, false);
682 x
= strndup(passphrase
, p
);
683 explicit_bzero_safe(passphrase
, sizeof(passphrase
));
689 r
= strv_consume(&l
, x
);
695 r
= log_debug_errno(SYNTHETIC_ERRNO(ECANCELED
), "Password query was cancelled.");
698 (void) add_to_keyring_and_log(keyname
, flags
, l
);
705 if (ttyfd
>= 0 && reset_tty
) {
706 (void) loop_write(ttyfd
, "\n", 1, false);
707 (void) tcsetattr(ttyfd
, TCSADRAIN
, &old_termios
);
713 static int create_socket(char **ret
) {
714 _cleanup_free_
char *path
= NULL
;
715 union sockaddr_union sa
;
717 _cleanup_close_
int fd
= -1;
722 fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
726 if (asprintf(&path
, "/run/systemd/ask-password/sck.%" PRIx64
, random_u64()) < 0)
729 r
= sockaddr_un_set_path(&sa
.un
, path
);
735 if (bind(fd
, &sa
.sa
, sa_len
) < 0)
738 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSCRED
, true);
742 *ret
= TAKE_PTR(path
);
746 int ask_password_agent(
752 AskPasswordFlags flags
,
762 _cleanup_close_
int socket_fd
= -1, signal_fd
= -1, notify
= -1, fd
= -1;
763 char temp
[] = "/run/systemd/ask-password/tmp.XXXXXX";
764 char final
[sizeof(temp
)] = "";
765 _cleanup_free_
char *socket_name
= NULL
;
766 _cleanup_strv_free_erase_
char **l
= NULL
;
767 _cleanup_fclose_
FILE *f
= NULL
;
768 struct pollfd pollfd
[_FD_MAX
];
769 sigset_t mask
, oldmask
;
774 if (flags
& ASK_PASSWORD_NO_AGENT
)
777 assert_se(sigemptyset(&mask
) >= 0);
778 assert_se(sigset_add_many(&mask
, SIGINT
, SIGTERM
, -1) >= 0);
779 assert_se(sigprocmask(SIG_BLOCK
, &mask
, &oldmask
) >= 0);
781 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
783 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
) {
784 r
= ask_password_keyring(keyname
, flags
, ret
);
788 } else if (r
!= -ENOKEY
)
791 notify
= inotify_init1(IN_CLOEXEC
| IN_NONBLOCK
);
796 if (inotify_add_watch(notify
, "/run/systemd/ask-password", IN_ATTRIB
/* for mtime */) < 0) {
802 fd
= mkostemp_safe(temp
);
808 (void) fchmod(fd
, 0644);
810 f
= take_fdopen(&fd
, "w");
816 signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
822 socket_fd
= create_socket(&socket_name
);
834 "NotAfter="USEC_FMT
"\n",
837 (flags
& ASK_PASSWORD_ACCEPT_CACHED
) ? 1 : 0,
838 (flags
& ASK_PASSWORD_ECHO
) ? 1 : 0,
842 fprintf(f
, "Message=%s\n", message
);
845 fprintf(f
, "Icon=%s\n", icon
);
848 fprintf(f
, "Id=%s\n", id
);
850 r
= fflush_and_check(f
);
854 memcpy(final
, temp
, sizeof(temp
));
856 final
[sizeof(final
)-11] = 'a';
857 final
[sizeof(final
)-10] = 's';
858 final
[sizeof(final
)-9] = 'k';
860 if (rename(temp
, final
) < 0) {
866 pollfd
[FD_SOCKET
].fd
= socket_fd
;
867 pollfd
[FD_SOCKET
].events
= POLLIN
;
868 pollfd
[FD_SIGNAL
].fd
= signal_fd
;
869 pollfd
[FD_SIGNAL
].events
= POLLIN
;
870 pollfd
[FD_INOTIFY
].fd
= notify
;
871 pollfd
[FD_INOTIFY
].events
= POLLIN
;
874 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred
))) control
;
875 char passphrase
[LINE_MAX
+1];
882 t
= now(CLOCK_MONOTONIC
);
884 if (until
> 0 && until
<= t
) {
889 k
= poll(pollfd
, notify
>= 0 ? _FD_MAX
: _FD_MAX
- 1, until
> 0 ? (int) ((until
-t
)/USEC_PER_MSEC
) : -1);
903 if (pollfd
[FD_SOCKET
].revents
& POLLNVAL
||
904 pollfd
[FD_SIGNAL
].revents
& POLLNVAL
||
905 (notify
>= 0 && pollfd
[FD_INOTIFY
].revents
& POLLNVAL
)) {
910 if (pollfd
[FD_SIGNAL
].revents
& POLLIN
) {
915 if (notify
>= 0 && pollfd
[FD_INOTIFY
].revents
!= 0) {
916 (void) flush_fd(notify
);
918 r
= ask_password_keyring(keyname
, flags
, ret
);
922 } else if (r
!= -ENOKEY
)
926 if (pollfd
[FD_SOCKET
].revents
== 0)
929 if (pollfd
[FD_SOCKET
].revents
!= POLLIN
) {
934 iovec
= IOVEC_MAKE(passphrase
, sizeof(passphrase
));
936 struct msghdr msghdr
= {
939 .msg_control
= &control
,
940 .msg_controllen
= sizeof(control
),
943 n
= recvmsg_safe(socket_fd
, &msghdr
, 0);
944 if (IN_SET(n
, -EAGAIN
, -EINTR
))
951 cmsg_close_all(&msghdr
);
954 log_debug("Message too short");
958 ucred
= CMSG_FIND_DATA(&msghdr
, SOL_SOCKET
, SCM_CREDENTIALS
, struct ucred
);
960 log_debug("Received message without credentials. Ignoring.");
964 if (ucred
->uid
!= 0) {
965 log_debug("Got request from unprivileged user. Ignoring.");
969 if (passphrase
[0] == '+') {
970 /* An empty message refers to the empty password */
974 l
= strv_parse_nulstr(passphrase
+1, n
-1);
975 explicit_bzero_safe(passphrase
, n
);
981 if (strv_isempty(l
)) {
983 log_debug("Invalid packet");
990 if (passphrase
[0] == '-') {
995 log_debug("Invalid packet");
999 (void) add_to_keyring_and_log(keyname
, flags
, l
);
1006 (void) unlink(socket_name
);
1008 (void) unlink(temp
);
1011 (void) unlink(final
);
1013 assert_se(sigprocmask(SIG_SETMASK
, &oldmask
, NULL
) == 0);
1017 int ask_password_auto(
1018 const char *message
,
1021 const char *keyname
,
1023 AskPasswordFlags flags
,
1030 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) &&
1032 ((flags
& ASK_PASSWORD_NO_TTY
) || !isatty(STDIN_FILENO
)) &&
1033 (flags
& ASK_PASSWORD_NO_AGENT
)) {
1034 r
= ask_password_keyring(keyname
, flags
, ret
);
1039 if (!(flags
& ASK_PASSWORD_NO_TTY
) && isatty(STDIN_FILENO
))
1040 return ask_password_tty(-1, message
, keyname
, until
, flags
, NULL
, ret
);
1042 if (!(flags
& ASK_PASSWORD_NO_AGENT
))
1043 return ask_password_agent(message
, icon
, id
, keyname
, until
, flags
, ret
);