1 /* SPDX-License-Identifier: LGPL-2.1+ */
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"
32 #include "memory-util.h"
33 #include "missing_syscall.h"
35 #include "process-util.h"
36 #include "random-util.h"
37 #include "signal-util.h"
38 #include "socket-util.h"
39 #include "string-util.h"
41 #include "terminal-util.h"
42 #include "time-util.h"
43 #include "tmpfile-util.h"
44 #include "umask-util.h"
47 #define KEYRING_TIMEOUT_USEC ((5 * USEC_PER_MINUTE) / 2)
49 static int lookup_key(const char *keyname
, key_serial_t
*ret
) {
55 serial
= request_key("user", keyname
, NULL
, 0);
57 return negative_errno();
63 static int retrieve_key(key_serial_t serial
, char ***ret
) {
64 size_t nfinal
, m
= 100;
66 _cleanup_(erase_and_freep
) char *pfinal
= NULL
;
71 _cleanup_(erase_and_freep
) char *p
= NULL
;
78 n
= keyctl(KEYCTL_READ
, (unsigned long) serial
, (unsigned long) p
, (unsigned long) m
, 0);
87 if (m
> LONG_MAX
/ 2) /* overflow check */
92 l
= strv_parse_nulstr(pfinal
, nfinal
);
100 static int add_to_keyring(const char *keyname
, AskPasswordFlags flags
, char **passwords
) {
101 _cleanup_strv_free_erase_
char **l
= NULL
;
102 _cleanup_(erase_and_freep
) char *p
= NULL
;
109 if (!(flags
& ASK_PASSWORD_PUSH_CACHE
))
111 if (strv_isempty(passwords
))
114 r
= lookup_key(keyname
, &serial
);
116 r
= retrieve_key(serial
, &l
);
119 } else if (r
!= -ENOKEY
)
122 r
= strv_extend_strv(&l
, passwords
, true);
126 r
= strv_make_nulstr(l
, &p
, &n
);
130 serial
= add_key("user", keyname
, p
, n
, KEY_SPEC_USER_KEYRING
);
134 if (keyctl(KEYCTL_SET_TIMEOUT
,
135 (unsigned long) serial
,
136 (unsigned long) DIV_ROUND_UP(KEYRING_TIMEOUT_USEC
, USEC_PER_SEC
), 0, 0) < 0)
137 log_debug_errno(errno
, "Failed to adjust timeout: %m");
139 /* Tell everyone to check the keyring */
140 (void) touch("/run/systemd/ask-password");
142 log_debug("Added key to keyring as %" PRIi32
".", serial
);
147 static int add_to_keyring_and_log(const char *keyname
, AskPasswordFlags flags
, char **passwords
) {
152 r
= add_to_keyring(keyname
, flags
, passwords
);
154 return log_debug_errno(r
, "Failed to add password to keyring: %m");
159 static int ask_password_keyring(const char *keyname
, AskPasswordFlags flags
, char ***ret
) {
167 if (!(flags
& ASK_PASSWORD_ACCEPT_CACHED
))
170 r
= lookup_key(keyname
, &serial
);
171 if (r
== -ENOSYS
) /* when retrieving the distinction doesn't matter */
176 return retrieve_key(serial
, ret
);
179 static int backspace_chars(int ttyfd
, size_t p
) {
183 _cleanup_free_
char *buf
= malloc_multiply(3, p
);
187 for (size_t i
= 0; i
< p
; i
++)
188 memcpy(buf
+ 3 * i
, "\b \b", 3);
190 return loop_write(ttyfd
, buf
, 3*p
, false);
193 static int backspace_string(int ttyfd
, const char *str
) {
196 /* Backspaces through enough characters to entirely undo printing of the specified string. */
201 size_t m
= utf8_n_codepoints(str
);
202 if (m
== (size_t) -1)
203 m
= strlen(str
); /* Not a valid UTF-8 string? If so, let's backspace the number of bytes
204 * output. Most likely this happened because we are not in an UTF-8 locale,
205 * and in that case that is the correct thing to do. And even if it's not,
206 * terminals tend to stop backspacing at the leftmost column, hence
207 * backspacing too much should be mostly OK. */
209 return backspace_chars(ttyfd
, m
);
212 int ask_password_plymouth(
215 AskPasswordFlags flags
,
216 const char *flag_file
,
219 static const union sockaddr_union sa
= PLYMOUTH_SOCKET
;
220 _cleanup_close_
int fd
= -1, notify
= -1;
221 _cleanup_free_
char *packet
= NULL
;
224 struct pollfd pollfd
[2] = {};
225 char buffer
[LINE_MAX
];
235 notify
= inotify_init1(IN_CLOEXEC
|IN_NONBLOCK
);
239 r
= inotify_add_watch(notify
, flag_file
, IN_ATTRIB
); /* for the link count */
244 fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
248 r
= connect(fd
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
));
252 if (flags
& ASK_PASSWORD_ACCEPT_CACHED
) {
253 packet
= strdup("c");
255 } else if (asprintf(&packet
, "*\002%c%s%n", (int) (strlen(message
) + 1), message
, &n
) < 0)
260 r
= loop_write(fd
, packet
, n
+ 1, true);
264 pollfd
[POLL_SOCKET
].fd
= fd
;
265 pollfd
[POLL_SOCKET
].events
= POLLIN
;
266 pollfd
[POLL_INOTIFY
].fd
= notify
;
267 pollfd
[POLL_INOTIFY
].events
= POLLIN
;
270 int sleep_for
= -1, j
;
275 y
= now(CLOCK_MONOTONIC
);
282 sleep_for
= (int) ((until
- y
) / USEC_PER_MSEC
);
285 if (flag_file
&& access(flag_file
, F_OK
) < 0) {
290 j
= poll(pollfd
, notify
>= 0 ? 2 : 1, sleep_for
);
302 if (notify
>= 0 && pollfd
[POLL_INOTIFY
].revents
!= 0)
303 (void) flush_fd(notify
);
305 if (pollfd
[POLL_SOCKET
].revents
== 0)
308 k
= read(fd
, buffer
+ p
, sizeof(buffer
) - p
);
310 if (IN_SET(errno
, EINTR
, EAGAIN
))
325 if (buffer
[0] == 5) {
327 if (flags
& ASK_PASSWORD_ACCEPT_CACHED
) {
328 /* Hmm, first try with cached
329 * passwords failed, so let's retry
330 * with a normal password request */
331 packet
= mfree(packet
);
333 if (asprintf(&packet
, "*\002%c%s%n", (int) (strlen(message
) + 1), message
, &n
) < 0) {
338 r
= loop_write(fd
, packet
, n
+1, true);
342 flags
&= ~ASK_PASSWORD_ACCEPT_CACHED
;
347 /* No password, because UI not shown */
351 } else if (IN_SET(buffer
[0], 2, 9)) {
355 /* One or more answers */
359 memcpy(&size
, buffer
+1, sizeof(size
));
360 size
= le32toh(size
);
361 if (size
+ 5 > sizeof(buffer
)) {
369 l
= strv_parse_nulstr(buffer
+ 5, size
);
388 explicit_bzero_safe(buffer
, sizeof(buffer
));
392 int ask_password_tty(
397 AskPasswordFlags flags
,
398 const char *flag_file
,
407 bool reset_tty
= false, dirty
= false, use_color
= 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:";
424 if (flag_file
|| ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
)) {
425 notify
= inotify_init1(IN_CLOEXEC
|IN_NONBLOCK
);
430 if (inotify_add_watch(notify
, flag_file
, IN_ATTRIB
/* for the link count */) < 0)
433 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
) {
434 r
= ask_password_keyring(keyname
, flags
, ret
);
437 else if (r
!= -ENOKEY
)
440 if (inotify_add_watch(notify
, "/run/systemd/ask-password", IN_ATTRIB
/* for mtime */) < 0)
444 /* If the caller didn't specify a TTY, then use the controlling tty, if we can. */
446 ttyfd
= cttyfd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
449 if (tcgetattr(ttyfd
, &old_termios
) < 0)
452 if (flags
& ASK_PASSWORD_CONSOLE_COLOR
)
453 use_color
= dev_console_colors_enabled();
455 use_color
= colors_enabled();
458 (void) loop_write(ttyfd
, ANSI_HIGHLIGHT
, STRLEN(ANSI_HIGHLIGHT
), false);
460 (void) loop_write(ttyfd
, message
, strlen(message
), false);
461 (void) loop_write(ttyfd
, " ", 1, false);
464 (void) loop_write(ttyfd
, ANSI_NORMAL
, STRLEN(ANSI_NORMAL
), false);
466 new_termios
= old_termios
;
467 new_termios
.c_lflag
&= ~(ICANON
|ECHO
);
468 new_termios
.c_cc
[VMIN
] = 1;
469 new_termios
.c_cc
[VTIME
] = 0;
471 if (tcsetattr(ttyfd
, TCSADRAIN
, &new_termios
) < 0) {
479 pollfd
[POLL_TTY
] = (struct pollfd
) {
480 .fd
= ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
,
483 pollfd
[POLL_INOTIFY
] = (struct pollfd
) {
489 _cleanup_(erase_char
) char c
;
490 int sleep_for
= -1, k
;
496 y
= now(CLOCK_MONOTONIC
);
503 sleep_for
= (int) DIV_ROUND_UP(until
- y
, USEC_PER_MSEC
);
507 if (access(flag_file
, F_OK
) < 0) {
512 k
= poll(pollfd
, notify
>= 0 ? 2 : 1, sleep_for
);
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 /* We treat EOF, newline and NUL byte all as valid end markers */
549 if (n
== 0 || c
== '\n' || c
== 0)
552 if (c
== 4) { /* C-d also known as EOT */
554 (void) loop_write(ttyfd
, "(skipped)", 9, false);
559 if (c
== 21) { /* C-u */
561 if (!(flags
& ASK_PASSWORD_SILENT
))
562 (void) backspace_string(ttyfd
, passphrase
);
564 explicit_bzero_safe(passphrase
, sizeof(passphrase
));
567 } else if (IN_SET(c
, '\b', 127)) {
572 if (!(flags
& ASK_PASSWORD_SILENT
))
573 (void) backspace_chars(ttyfd
, 1);
575 /* Remove a full UTF-8 codepoint from the end. For that, figure out where the
581 z
= utf8_encoded_valid_unichar(passphrase
+ q
, (size_t) -1);
583 q
= (size_t) -1; /* Invalid UTF8! */
587 if (q
+ z
>= p
) /* This one brings us over the edge */
593 p
= codepoint
= q
== (size_t) -1 ? p
- 1 : q
;
594 explicit_bzero_safe(passphrase
+ p
, sizeof(passphrase
) - p
);
596 } else if (!dirty
&& !(flags
& ASK_PASSWORD_SILENT
)) {
598 flags
|= ASK_PASSWORD_SILENT
;
600 /* There are two ways to enter silent mode. Either by pressing backspace as
601 * first key (and only as first key), or ... */
604 (void) loop_write(ttyfd
, "(no echo) ", 10, false);
606 } else if (ttyfd
>= 0)
607 (void) loop_write(ttyfd
, "\a", 1, false);
609 } else if (c
== '\t' && !(flags
& ASK_PASSWORD_SILENT
)) {
611 (void) backspace_string(ttyfd
, passphrase
);
612 flags
|= ASK_PASSWORD_SILENT
;
614 /* ... or by pressing TAB at any time. */
617 (void) loop_write(ttyfd
, "(no echo) ", 10, false);
619 } else if (p
>= sizeof(passphrase
)-1) {
621 /* Reached the size limit */
623 (void) loop_write(ttyfd
, "\a", 1, false);
628 if (!(flags
& ASK_PASSWORD_SILENT
) && ttyfd
>= 0) {
629 /* Check if we got a complete UTF-8 character now. If so, let's output one '*'. */
630 n
= utf8_encoded_valid_unichar(passphrase
+ codepoint
, (size_t) -1);
632 if (flags
& ASK_PASSWORD_ECHO
)
633 (void) loop_write(ttyfd
, passphrase
+ codepoint
, n
, false);
635 (void) loop_write(ttyfd
, "*", 1, false);
644 x
= strndup(passphrase
, p
);
645 explicit_bzero_safe(passphrase
, sizeof(passphrase
));
651 r
= strv_consume(&l
, x
);
657 (void) add_to_keyring_and_log(keyname
, flags
, l
);
663 if (ttyfd
>= 0 && reset_tty
) {
664 (void) loop_write(ttyfd
, "\n", 1, false);
665 (void) tcsetattr(ttyfd
, TCSADRAIN
, &old_termios
);
671 static int create_socket(char **ret
) {
672 _cleanup_free_
char *path
= NULL
;
673 union sockaddr_union sa
= {};
674 _cleanup_close_
int fd
= -1;
679 fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
683 if (asprintf(&path
, "/run/systemd/ask-password/sck.%" PRIx64
, random_u64()) < 0)
686 salen
= sockaddr_un_set_path(&sa
.un
, path
);
690 RUN_WITH_UMASK(0177) {
691 if (bind(fd
, &sa
.sa
, salen
) < 0)
695 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSCRED
, true);
699 *ret
= TAKE_PTR(path
);
703 int ask_password_agent(
709 AskPasswordFlags flags
,
719 _cleanup_close_
int socket_fd
= -1, signal_fd
= -1, notify
= -1, fd
= -1;
720 char temp
[] = "/run/systemd/ask-password/tmp.XXXXXX";
721 char final
[sizeof(temp
)] = "";
722 _cleanup_free_
char *socket_name
= NULL
;
723 _cleanup_strv_free_erase_
char **l
= NULL
;
724 _cleanup_fclose_
FILE *f
= NULL
;
725 struct pollfd pollfd
[_FD_MAX
];
726 sigset_t mask
, oldmask
;
731 if (flags
& ASK_PASSWORD_NO_AGENT
)
734 assert_se(sigemptyset(&mask
) >= 0);
735 assert_se(sigset_add_many(&mask
, SIGINT
, SIGTERM
, -1) >= 0);
736 assert_se(sigprocmask(SIG_BLOCK
, &mask
, &oldmask
) >= 0);
738 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
740 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
) {
741 r
= ask_password_keyring(keyname
, flags
, ret
);
745 } else if (r
!= -ENOKEY
)
748 notify
= inotify_init1(IN_CLOEXEC
| IN_NONBLOCK
);
753 if (inotify_add_watch(notify
, "/run/systemd/ask-password", IN_ATTRIB
/* for mtime */) < 0) {
759 fd
= mkostemp_safe(temp
);
765 (void) fchmod(fd
, 0644);
775 signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
781 socket_fd
= create_socket(&socket_name
);
793 "NotAfter="USEC_FMT
"\n",
796 (flags
& ASK_PASSWORD_ACCEPT_CACHED
) ? 1 : 0,
797 (flags
& ASK_PASSWORD_ECHO
) ? 1 : 0,
801 fprintf(f
, "Message=%s\n", message
);
804 fprintf(f
, "Icon=%s\n", icon
);
807 fprintf(f
, "Id=%s\n", id
);
809 r
= fflush_and_check(f
);
813 memcpy(final
, temp
, sizeof(temp
));
815 final
[sizeof(final
)-11] = 'a';
816 final
[sizeof(final
)-10] = 's';
817 final
[sizeof(final
)-9] = 'k';
819 if (rename(temp
, final
) < 0) {
825 pollfd
[FD_SOCKET
].fd
= socket_fd
;
826 pollfd
[FD_SOCKET
].events
= POLLIN
;
827 pollfd
[FD_SIGNAL
].fd
= signal_fd
;
828 pollfd
[FD_SIGNAL
].events
= POLLIN
;
829 pollfd
[FD_INOTIFY
].fd
= notify
;
830 pollfd
[FD_INOTIFY
].events
= POLLIN
;
833 char passphrase
[LINE_MAX
+1];
834 struct msghdr msghdr
;
838 struct cmsghdr cmsghdr
;
839 uint8_t buf
[CMSG_SPACE(sizeof(struct ucred
))];
845 t
= now(CLOCK_MONOTONIC
);
847 if (until
> 0 && until
<= t
) {
852 k
= poll(pollfd
, notify
>= 0 ? _FD_MAX
: _FD_MAX
- 1, until
> 0 ? (int) ((until
-t
)/USEC_PER_MSEC
) : -1);
866 if (pollfd
[FD_SIGNAL
].revents
& POLLIN
) {
871 if (notify
>= 0 && pollfd
[FD_INOTIFY
].revents
!= 0) {
872 (void) flush_fd(notify
);
874 r
= ask_password_keyring(keyname
, flags
, ret
);
878 } else if (r
!= -ENOKEY
)
882 if (pollfd
[FD_SOCKET
].revents
== 0)
885 if (pollfd
[FD_SOCKET
].revents
!= POLLIN
) {
890 iovec
= IOVEC_MAKE(passphrase
, sizeof(passphrase
));
894 msghdr
.msg_iov
= &iovec
;
895 msghdr
.msg_iovlen
= 1;
896 msghdr
.msg_control
= &control
;
897 msghdr
.msg_controllen
= sizeof(control
);
899 n
= recvmsg(socket_fd
, &msghdr
, 0);
901 if (IN_SET(errno
, EAGAIN
, EINTR
))
908 cmsg_close_all(&msghdr
);
911 log_debug("Message too short");
915 if (msghdr
.msg_controllen
< CMSG_LEN(sizeof(struct ucred
)) ||
916 control
.cmsghdr
.cmsg_level
!= SOL_SOCKET
||
917 control
.cmsghdr
.cmsg_type
!= SCM_CREDENTIALS
||
918 control
.cmsghdr
.cmsg_len
!= CMSG_LEN(sizeof(struct ucred
))) {
919 log_debug("Received message without credentials. Ignoring.");
923 ucred
= (struct ucred
*) CMSG_DATA(&control
.cmsghdr
);
924 if (ucred
->uid
!= 0) {
925 log_debug("Got request from unprivileged user. Ignoring.");
929 if (passphrase
[0] == '+') {
930 /* An empty message refers to the empty password */
934 l
= strv_parse_nulstr(passphrase
+1, n
-1);
935 explicit_bzero_safe(passphrase
, n
);
941 if (strv_isempty(l
)) {
943 log_debug("Invalid packet");
950 if (passphrase
[0] == '-') {
955 log_debug("Invalid packet");
959 (void) add_to_keyring_and_log(keyname
, flags
, l
);
966 (void) unlink(socket_name
);
971 (void) unlink(final
);
973 assert_se(sigprocmask(SIG_SETMASK
, &oldmask
, NULL
) == 0);
977 int ask_password_auto(
983 AskPasswordFlags flags
,
990 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) &&
992 ((flags
& ASK_PASSWORD_NO_TTY
) || !isatty(STDIN_FILENO
)) &&
993 (flags
& ASK_PASSWORD_NO_AGENT
)) {
994 r
= ask_password_keyring(keyname
, flags
, ret
);
999 if (!(flags
& ASK_PASSWORD_NO_TTY
) && isatty(STDIN_FILENO
))
1000 return ask_password_tty(-1, message
, keyname
, until
, flags
, NULL
, ret
);
1002 if (!(flags
& ASK_PASSWORD_NO_AGENT
))
1003 return ask_password_agent(message
, icon
, id
, keyname
, until
, flags
, ret
);