1 /* SPDX-License-Identifier: LGPL-2.1+ */
15 #include <sys/inotify.h>
16 #include <sys/signalfd.h>
17 #include <sys/socket.h>
25 #include "alloc-util.h"
26 #include "ask-password-api.h"
29 #include "format-util.h"
34 #include "memory-util.h"
37 #include "process-util.h"
38 #include "random-util.h"
39 #include "signal-util.h"
40 #include "socket-util.h"
41 #include "string-util.h"
43 #include "terminal-util.h"
44 #include "time-util.h"
45 #include "tmpfile-util.h"
46 #include "umask-util.h"
49 #define KEYRING_TIMEOUT_USEC ((5 * USEC_PER_MINUTE) / 2)
51 static int lookup_key(const char *keyname
, key_serial_t
*ret
) {
57 serial
= request_key("user", keyname
, NULL
, 0);
59 return negative_errno();
65 static int retrieve_key(key_serial_t serial
, char ***ret
) {
66 _cleanup_free_
char *p
= NULL
;
77 n
= keyctl(KEYCTL_READ
, (unsigned long) serial
, (unsigned long) p
, (unsigned long) m
, 0);
83 explicit_bzero_safe(p
, n
);
85 if (m
> LONG_MAX
/ 2) /* overflow check */
88 if ((long) (size_t) m
!= m
) /* make sure that this still fits if converted to size_t */
94 l
= strv_parse_nulstr(p
, n
);
98 explicit_bzero_safe(p
, n
);
104 static int add_to_keyring(const char *keyname
, AskPasswordFlags flags
, char **passwords
) {
105 _cleanup_strv_free_erase_
char **l
= NULL
;
106 _cleanup_free_
char *p
= NULL
;
114 if (!(flags
& ASK_PASSWORD_PUSH_CACHE
))
117 r
= lookup_key(keyname
, &serial
);
119 r
= retrieve_key(serial
, &l
);
122 } else if (r
!= -ENOKEY
)
125 r
= strv_extend_strv(&l
, passwords
, true);
129 r
= strv_make_nulstr(l
, &p
, &n
);
133 serial
= add_key("user", keyname
, p
, n
, KEY_SPEC_USER_KEYRING
);
134 explicit_bzero_safe(p
, n
);
138 if (keyctl(KEYCTL_SET_TIMEOUT
,
139 (unsigned long) serial
,
140 (unsigned long) DIV_ROUND_UP(KEYRING_TIMEOUT_USEC
, USEC_PER_SEC
), 0, 0) < 0)
141 log_debug_errno(errno
, "Failed to adjust timeout: %m");
143 /* Tell everyone to check the keyring */
144 (void) touch("/run/systemd/ask-password");
146 log_debug("Added key to keyring as %" PRIi32
".", serial
);
151 static int add_to_keyring_and_log(const char *keyname
, AskPasswordFlags flags
, char **passwords
) {
157 r
= add_to_keyring(keyname
, flags
, passwords
);
159 return log_debug_errno(r
, "Failed to add password to keyring: %m");
164 static int ask_password_keyring(const char *keyname
, AskPasswordFlags flags
, char ***ret
) {
172 if (!(flags
& ASK_PASSWORD_ACCEPT_CACHED
))
175 r
= lookup_key(keyname
, &serial
);
176 if (r
== -ENOSYS
) /* when retrieving the distinction doesn't matter */
181 return retrieve_key(serial
, ret
);
184 static void backspace_chars(int ttyfd
, size_t p
) {
192 loop_write(ttyfd
, "\b \b", 3, false);
196 static void backspace_string(int ttyfd
, const char *str
) {
204 /* Backspaces through enough characters to entirely undo printing of the specified string. */
206 m
= utf8_n_codepoints(str
);
207 if (m
== (size_t) -1)
208 m
= strlen(str
); /* Not a valid UTF-8 string? If so, let's backspace the number of bytes output. Most
209 * likely this happened because we are not in an UTF-8 locale, and in that case that
210 * is the correct thing to do. And even if it's not, terminals tend to stop
211 * backspacing at the leftmost column, hence backspacing too much should be mostly
214 backspace_chars(ttyfd
, m
);
217 int ask_password_tty(
222 AskPasswordFlags flags
,
223 const char *flag_file
,
232 bool reset_tty
= false, dirty
= false, use_color
= false;
233 _cleanup_close_
int cttyfd
= -1, notify
= -1;
234 struct termios old_termios
, new_termios
;
235 char passphrase
[LINE_MAX
+ 1] = {}, *x
;
236 _cleanup_strv_free_erase_
char **l
= NULL
;
237 struct pollfd pollfd
[_POLL_MAX
];
238 size_t p
= 0, codepoint
= 0;
243 if (flags
& ASK_PASSWORD_NO_TTY
)
247 message
= "Password:";
249 if (flag_file
|| ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
)) {
250 notify
= inotify_init1(IN_CLOEXEC
|IN_NONBLOCK
);
255 if (inotify_add_watch(notify
, flag_file
, IN_ATTRIB
/* for the link count */) < 0)
258 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
) {
259 r
= ask_password_keyring(keyname
, flags
, ret
);
262 else if (r
!= -ENOKEY
)
265 if (inotify_add_watch(notify
, "/run/systemd/ask-password", IN_ATTRIB
/* for mtime */) < 0)
269 /* If the caller didn't specify a TTY, then use the controlling tty, if we can. */
271 ttyfd
= cttyfd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
274 if (tcgetattr(ttyfd
, &old_termios
) < 0)
277 if (flags
& ASK_PASSWORD_CONSOLE_COLOR
)
278 use_color
= dev_console_colors_enabled();
280 use_color
= colors_enabled();
283 (void) loop_write(ttyfd
, ANSI_HIGHLIGHT
, STRLEN(ANSI_HIGHLIGHT
), false);
285 (void) loop_write(ttyfd
, message
, strlen(message
), false);
286 (void) loop_write(ttyfd
, " ", 1, false);
289 (void) loop_write(ttyfd
, ANSI_NORMAL
, STRLEN(ANSI_NORMAL
), false);
291 new_termios
= old_termios
;
292 new_termios
.c_lflag
&= ~(ICANON
|ECHO
);
293 new_termios
.c_cc
[VMIN
] = 1;
294 new_termios
.c_cc
[VTIME
] = 0;
296 if (tcsetattr(ttyfd
, TCSADRAIN
, &new_termios
) < 0) {
304 pollfd
[POLL_TTY
] = (struct pollfd
) {
305 .fd
= ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
,
308 pollfd
[POLL_INOTIFY
] = (struct pollfd
) {
314 _cleanup_(erase_char
) char c
;
315 int sleep_for
= -1, k
;
321 y
= now(CLOCK_MONOTONIC
);
328 sleep_for
= (int) DIV_ROUND_UP(until
- y
, USEC_PER_MSEC
);
332 if (access(flag_file
, F_OK
) < 0) {
337 k
= poll(pollfd
, notify
>= 0 ? 2 : 1, sleep_for
);
349 if (notify
>= 0 && pollfd
[POLL_INOTIFY
].revents
!= 0 && keyname
) {
350 (void) flush_fd(notify
);
352 r
= ask_password_keyring(keyname
, flags
, ret
);
356 } else if (r
!= -ENOKEY
)
360 if (pollfd
[POLL_TTY
].revents
== 0)
363 n
= read(ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
, &c
, 1);
365 if (IN_SET(errno
, EINTR
, EAGAIN
))
373 /* We treat EOF, newline and NUL byte all as valid end markers */
374 if (n
== 0 || c
== '\n' || c
== 0)
377 if (c
== 21) { /* C-u */
379 if (!(flags
& ASK_PASSWORD_SILENT
))
380 backspace_string(ttyfd
, passphrase
);
382 explicit_bzero_safe(passphrase
, sizeof(passphrase
));
385 } else if (IN_SET(c
, '\b', 127)) {
390 if (!(flags
& ASK_PASSWORD_SILENT
))
391 backspace_chars(ttyfd
, 1);
393 /* Remove a full UTF-8 codepoint from the end. For that, figure out where the
399 z
= utf8_encoded_valid_unichar(passphrase
+ q
, (size_t) -1);
401 q
= (size_t) -1; /* Invalid UTF8! */
405 if (q
+ z
>= p
) /* This one brings us over the edge */
411 p
= codepoint
= q
== (size_t) -1 ? p
- 1 : q
;
412 explicit_bzero_safe(passphrase
+ p
, sizeof(passphrase
) - p
);
414 } else if (!dirty
&& !(flags
& ASK_PASSWORD_SILENT
)) {
416 flags
|= ASK_PASSWORD_SILENT
;
418 /* There are two ways to enter silent mode. Either by pressing backspace as
419 * first key (and only as first key), or ... */
422 (void) loop_write(ttyfd
, "(no echo) ", 10, false);
424 } else if (ttyfd
>= 0)
425 (void) loop_write(ttyfd
, "\a", 1, false);
427 } else if (c
== '\t' && !(flags
& ASK_PASSWORD_SILENT
)) {
429 backspace_string(ttyfd
, passphrase
);
430 flags
|= ASK_PASSWORD_SILENT
;
432 /* ... or by pressing TAB at any time. */
435 (void) loop_write(ttyfd
, "(no echo) ", 10, false);
437 } else if (p
>= sizeof(passphrase
)-1) {
439 /* Reached the size limit */
441 (void) loop_write(ttyfd
, "\a", 1, false);
446 if (!(flags
& ASK_PASSWORD_SILENT
) && ttyfd
>= 0) {
447 /* Check if we got a complete UTF-8 character now. If so, let's output one '*'. */
448 n
= utf8_encoded_valid_unichar(passphrase
+ codepoint
, (size_t) -1);
450 if (flags
& ASK_PASSWORD_ECHO
)
451 (void) loop_write(ttyfd
, passphrase
+ codepoint
, n
, false);
453 (void) loop_write(ttyfd
, "*", 1, false);
462 x
= strndup(passphrase
, p
);
463 explicit_bzero_safe(passphrase
, sizeof(passphrase
));
469 r
= strv_consume(&l
, x
);
474 (void) add_to_keyring_and_log(keyname
, flags
, l
);
480 if (ttyfd
>= 0 && reset_tty
) {
481 (void) loop_write(ttyfd
, "\n", 1, false);
482 (void) tcsetattr(ttyfd
, TCSADRAIN
, &old_termios
);
488 static int create_socket(char **ret
) {
489 _cleanup_free_
char *path
= NULL
;
490 union sockaddr_union sa
= {};
491 _cleanup_close_
int fd
= -1;
496 fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
500 if (asprintf(&path
, "/run/systemd/ask-password/sck.%" PRIx64
, random_u64()) < 0)
503 salen
= sockaddr_un_set_path(&sa
.un
, path
);
507 RUN_WITH_UMASK(0177) {
508 if (bind(fd
, &sa
.sa
, salen
) < 0)
512 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSCRED
, true);
516 *ret
= TAKE_PTR(path
);
520 int ask_password_agent(
526 AskPasswordFlags flags
,
536 _cleanup_close_
int socket_fd
= -1, signal_fd
= -1, notify
= -1, fd
= -1;
537 char temp
[] = "/run/systemd/ask-password/tmp.XXXXXX";
538 char final
[sizeof(temp
)] = "";
539 _cleanup_free_
char *socket_name
= NULL
;
540 _cleanup_strv_free_erase_
char **l
= NULL
;
541 _cleanup_fclose_
FILE *f
= NULL
;
542 struct pollfd pollfd
[_FD_MAX
];
543 sigset_t mask
, oldmask
;
548 if (flags
& ASK_PASSWORD_NO_AGENT
)
551 assert_se(sigemptyset(&mask
) >= 0);
552 assert_se(sigset_add_many(&mask
, SIGINT
, SIGTERM
, -1) >= 0);
553 assert_se(sigprocmask(SIG_BLOCK
, &mask
, &oldmask
) >= 0);
555 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
557 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
) {
558 r
= ask_password_keyring(keyname
, flags
, ret
);
562 } else if (r
!= -ENOKEY
)
565 notify
= inotify_init1(IN_CLOEXEC
| IN_NONBLOCK
);
570 if (inotify_add_watch(notify
, "/run/systemd/ask-password", IN_ATTRIB
/* for mtime */) < 0) {
576 fd
= mkostemp_safe(temp
);
582 (void) fchmod(fd
, 0644);
592 signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
598 socket_fd
= create_socket(&socket_name
);
610 "NotAfter="USEC_FMT
"\n",
613 (flags
& ASK_PASSWORD_ACCEPT_CACHED
) ? 1 : 0,
614 (flags
& ASK_PASSWORD_ECHO
) ? 1 : 0,
618 fprintf(f
, "Message=%s\n", message
);
621 fprintf(f
, "Icon=%s\n", icon
);
624 fprintf(f
, "Id=%s\n", id
);
626 r
= fflush_and_check(f
);
630 memcpy(final
, temp
, sizeof(temp
));
632 final
[sizeof(final
)-11] = 'a';
633 final
[sizeof(final
)-10] = 's';
634 final
[sizeof(final
)-9] = 'k';
636 if (rename(temp
, final
) < 0) {
642 pollfd
[FD_SOCKET
].fd
= socket_fd
;
643 pollfd
[FD_SOCKET
].events
= POLLIN
;
644 pollfd
[FD_SIGNAL
].fd
= signal_fd
;
645 pollfd
[FD_SIGNAL
].events
= POLLIN
;
646 pollfd
[FD_INOTIFY
].fd
= notify
;
647 pollfd
[FD_INOTIFY
].events
= POLLIN
;
650 char passphrase
[LINE_MAX
+1];
651 struct msghdr msghdr
;
655 struct cmsghdr cmsghdr
;
656 uint8_t buf
[CMSG_SPACE(sizeof(struct ucred
))];
662 t
= now(CLOCK_MONOTONIC
);
664 if (until
> 0 && until
<= t
) {
669 k
= poll(pollfd
, notify
>= 0 ? _FD_MAX
: _FD_MAX
- 1, until
> 0 ? (int) ((until
-t
)/USEC_PER_MSEC
) : -1);
683 if (pollfd
[FD_SIGNAL
].revents
& POLLIN
) {
688 if (notify
>= 0 && pollfd
[FD_INOTIFY
].revents
!= 0) {
689 (void) flush_fd(notify
);
691 r
= ask_password_keyring(keyname
, flags
, ret
);
695 } else if (r
!= -ENOKEY
)
699 if (pollfd
[FD_SOCKET
].revents
== 0)
702 if (pollfd
[FD_SOCKET
].revents
!= POLLIN
) {
707 iovec
= IOVEC_MAKE(passphrase
, sizeof(passphrase
));
711 msghdr
.msg_iov
= &iovec
;
712 msghdr
.msg_iovlen
= 1;
713 msghdr
.msg_control
= &control
;
714 msghdr
.msg_controllen
= sizeof(control
);
716 n
= recvmsg(socket_fd
, &msghdr
, 0);
718 if (IN_SET(errno
, EAGAIN
, EINTR
))
725 cmsg_close_all(&msghdr
);
728 log_debug("Message too short");
732 if (msghdr
.msg_controllen
< CMSG_LEN(sizeof(struct ucred
)) ||
733 control
.cmsghdr
.cmsg_level
!= SOL_SOCKET
||
734 control
.cmsghdr
.cmsg_type
!= SCM_CREDENTIALS
||
735 control
.cmsghdr
.cmsg_len
!= CMSG_LEN(sizeof(struct ucred
))) {
736 log_debug("Received message without credentials. Ignoring.");
740 ucred
= (struct ucred
*) CMSG_DATA(&control
.cmsghdr
);
741 if (ucred
->uid
!= 0) {
742 log_debug("Got request from unprivileged user. Ignoring.");
746 if (passphrase
[0] == '+') {
747 /* An empty message refers to the empty password */
751 l
= strv_parse_nulstr(passphrase
+1, n
-1);
752 explicit_bzero_safe(passphrase
, n
);
758 if (strv_isempty(l
)) {
760 log_debug("Invalid packet");
767 if (passphrase
[0] == '-') {
772 log_debug("Invalid packet");
776 (void) add_to_keyring_and_log(keyname
, flags
, l
);
783 (void) unlink(socket_name
);
788 (void) unlink(final
);
790 assert_se(sigprocmask(SIG_SETMASK
, &oldmask
, NULL
) == 0);
794 int ask_password_auto(
800 AskPasswordFlags flags
,
807 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) &&
809 ((flags
& ASK_PASSWORD_NO_TTY
) || !isatty(STDIN_FILENO
)) &&
810 (flags
& ASK_PASSWORD_NO_AGENT
)) {
811 r
= ask_password_keyring(keyname
, flags
, ret
);
816 if (!(flags
& ASK_PASSWORD_NO_TTY
) && isatty(STDIN_FILENO
))
817 return ask_password_tty(-1, message
, keyname
, until
, flags
, NULL
, ret
);
819 if (!(flags
& ASK_PASSWORD_NO_AGENT
))
820 return ask_password_agent(message
, icon
, id
, keyname
, until
, flags
, ret
);