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"
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 "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 _cleanup_free_
char *p
= NULL
;
75 n
= keyctl(KEYCTL_READ
, (unsigned long) serial
, (unsigned long) p
, (unsigned long) m
, 0);
87 l
= strv_parse_nulstr(p
, n
);
97 static int add_to_keyring(const char *keyname
, AskPasswordFlags flags
, char **passwords
) {
98 _cleanup_strv_free_erase_
char **l
= NULL
;
99 _cleanup_free_
char *p
= NULL
;
107 if (!(flags
& ASK_PASSWORD_PUSH_CACHE
))
110 r
= lookup_key(keyname
, &serial
);
112 r
= retrieve_key(serial
, &l
);
115 } else if (r
!= -ENOKEY
)
118 r
= strv_extend_strv(&l
, passwords
, true);
122 r
= strv_make_nulstr(l
, &p
, &n
);
126 serial
= add_key("user", keyname
, p
, n
, KEY_SPEC_USER_KEYRING
);
127 explicit_bzero(p
, n
);
131 if (keyctl(KEYCTL_SET_TIMEOUT
,
132 (unsigned long) serial
,
133 (unsigned long) DIV_ROUND_UP(KEYRING_TIMEOUT_USEC
, USEC_PER_SEC
), 0, 0) < 0)
134 log_debug_errno(errno
, "Failed to adjust timeout: %m");
136 log_debug("Added key to keyring as %" PRIi32
".", serial
);
141 static int add_to_keyring_and_log(const char *keyname
, AskPasswordFlags flags
, char **passwords
) {
147 r
= add_to_keyring(keyname
, flags
, passwords
);
149 return log_debug_errno(r
, "Failed to add password to keyring: %m");
154 int ask_password_keyring(const char *keyname
, AskPasswordFlags flags
, char ***ret
) {
162 if (!(flags
& ASK_PASSWORD_ACCEPT_CACHED
))
165 r
= lookup_key(keyname
, &serial
);
166 if (r
== -ENOSYS
) /* when retrieving the distinction doesn't matter */
171 return retrieve_key(serial
, ret
);
174 static void backspace_chars(int ttyfd
, size_t p
) {
182 loop_write(ttyfd
, "\b \b", 3, false);
186 static void backspace_string(int ttyfd
, const char *str
) {
194 /* Backspaces through enough characters to entirely undo printing of the specified string. */
196 m
= utf8_n_codepoints(str
);
197 if (m
== (size_t) -1)
198 m
= strlen(str
); /* Not a valid UTF-8 string? If so, let's backspace the number of bytes output. Most
199 * likely this happened because we are not in an UTF-8 locale, and in that case that
200 * is the correct thing to do. And even if it's not, terminals tend to stop
201 * backspacing at the leftmost column, hence backspacing too much should be mostly
204 backspace_chars(ttyfd
, m
);
207 int ask_password_tty(
212 AskPasswordFlags flags
,
213 const char *flag_file
,
222 bool reset_tty
= false, dirty
= false, use_color
= false;
223 _cleanup_close_
int cttyfd
= -1, notify
= -1;
224 struct termios old_termios
, new_termios
;
225 char passphrase
[LINE_MAX
+ 1] = {}, *x
;
226 struct pollfd pollfd
[_POLL_MAX
];
227 size_t p
= 0, codepoint
= 0;
232 if (flags
& ASK_PASSWORD_NO_TTY
)
236 message
= "Password:";
239 notify
= inotify_init1(IN_CLOEXEC
|IN_NONBLOCK
);
243 if (inotify_add_watch(notify
, flag_file
, IN_ATTRIB
/* for the link count */) < 0)
247 /* If the caller didn't specify a TTY, then use the controlling tty, if we can. */
249 ttyfd
= cttyfd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
252 if (tcgetattr(ttyfd
, &old_termios
) < 0)
255 if (flags
& ASK_PASSWORD_CONSOLE_COLOR
)
256 use_color
= dev_console_colors_enabled();
258 use_color
= colors_enabled();
261 (void) loop_write(ttyfd
, ANSI_HIGHLIGHT
, STRLEN(ANSI_HIGHLIGHT
), false);
263 (void) loop_write(ttyfd
, message
, strlen(message
), false);
264 (void) loop_write(ttyfd
, " ", 1, false);
267 (void) loop_write(ttyfd
, ANSI_NORMAL
, STRLEN(ANSI_NORMAL
), false);
269 new_termios
= old_termios
;
270 new_termios
.c_lflag
&= ~(ICANON
|ECHO
);
271 new_termios
.c_cc
[VMIN
] = 1;
272 new_termios
.c_cc
[VTIME
] = 0;
274 if (tcsetattr(ttyfd
, TCSADRAIN
, &new_termios
) < 0) {
282 pollfd
[POLL_TTY
] = (struct pollfd
) {
283 .fd
= ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
,
286 pollfd
[POLL_INOTIFY
] = (struct pollfd
) {
292 int sleep_for
= -1, k
;
299 y
= now(CLOCK_MONOTONIC
);
306 sleep_for
= (int) DIV_ROUND_UP(until
- y
, USEC_PER_MSEC
);
310 if (access(flag_file
, F_OK
) < 0) {
315 k
= poll(pollfd
, notify
>= 0 ? 2 : 1, sleep_for
);
327 if (notify
>= 0 && pollfd
[POLL_INOTIFY
].revents
!= 0)
328 (void) flush_fd(notify
);
330 if (pollfd
[POLL_TTY
].revents
== 0)
333 n
= read(ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
, &c
, 1);
335 if (IN_SET(errno
, EINTR
, EAGAIN
))
343 /* We treat EOF, newline and NUL byte all as valid end markers */
344 if (n
== 0 || c
== '\n' || c
== 0)
347 if (c
== 21) { /* C-u */
349 if (!(flags
& ASK_PASSWORD_SILENT
))
350 backspace_string(ttyfd
, passphrase
);
352 explicit_bzero(passphrase
, sizeof(passphrase
));
355 } else if (IN_SET(c
, '\b', 127)) {
360 if (!(flags
& ASK_PASSWORD_SILENT
))
361 backspace_chars(ttyfd
, 1);
363 /* Remove a full UTF-8 codepoint from the end. For that, figure out where the last one
369 z
= utf8_encoded_valid_unichar(passphrase
+ q
);
371 q
= (size_t) -1; /* Invalid UTF8! */
375 if (q
+ z
>= p
) /* This one brings us over the edge */
381 p
= codepoint
= q
== (size_t) -1 ? p
- 1 : q
;
382 explicit_bzero(passphrase
+ p
, sizeof(passphrase
) - p
);
384 } else if (!dirty
&& !(flags
& ASK_PASSWORD_SILENT
)) {
386 flags
|= ASK_PASSWORD_SILENT
;
388 /* There are two ways to enter silent mode. Either by pressing backspace as first key
389 * (and only as first key), or ... */
392 (void) loop_write(ttyfd
, "(no echo) ", 10, false);
394 } else if (ttyfd
>= 0)
395 (void) loop_write(ttyfd
, "\a", 1, false);
397 } else if (c
== '\t' && !(flags
& ASK_PASSWORD_SILENT
)) {
399 backspace_string(ttyfd
, passphrase
);
400 flags
|= ASK_PASSWORD_SILENT
;
402 /* ... or by pressing TAB at any time. */
405 (void) loop_write(ttyfd
, "(no echo) ", 10, false);
407 } else if (p
>= sizeof(passphrase
)-1) {
409 /* Reached the size limit */
411 (void) loop_write(ttyfd
, "\a", 1, false);
416 if (!(flags
& ASK_PASSWORD_SILENT
) && ttyfd
>= 0) {
417 /* Check if we got a complete UTF-8 character now. If so, let's output one '*'. */
418 n
= utf8_encoded_valid_unichar(passphrase
+ codepoint
);
421 (void) loop_write(ttyfd
, (flags
& ASK_PASSWORD_ECHO
) ? &c
: "*", 1, false);
428 /* Let's forget this char, just to not keep needlessly copies of key material around */
432 x
= strndup(passphrase
, p
);
433 explicit_bzero(passphrase
, sizeof(passphrase
));
440 (void) add_to_keyring_and_log(keyname
, flags
, STRV_MAKE(x
));
446 if (ttyfd
>= 0 && reset_tty
) {
447 (void) loop_write(ttyfd
, "\n", 1, false);
448 (void) tcsetattr(ttyfd
, TCSADRAIN
, &old_termios
);
454 static int create_socket(char **name
) {
455 union sockaddr_union sa
= {
456 .un
.sun_family
= AF_UNIX
,
458 _cleanup_close_
int fd
= -1;
459 static const int one
= 1;
465 fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
469 snprintf(sa
.un
.sun_path
, sizeof(sa
.un
.sun_path
)-1, "/run/systemd/ask-password/sck.%" PRIx64
, random_u64());
471 RUN_WITH_UMASK(0177) {
472 if (bind(fd
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
)) < 0)
476 if (setsockopt(fd
, SOL_SOCKET
, SO_PASSCRED
, &one
, sizeof(one
)) < 0)
479 c
= strdup(sa
.un
.sun_path
);
491 int ask_password_agent(
497 AskPasswordFlags flags
,
506 _cleanup_close_
int socket_fd
= -1, signal_fd
= -1, fd
= -1;
507 char temp
[] = "/run/systemd/ask-password/tmp.XXXXXX";
508 char final
[sizeof(temp
)] = "";
509 _cleanup_free_
char *socket_name
= NULL
;
510 _cleanup_strv_free_
char **l
= NULL
;
511 _cleanup_fclose_
FILE *f
= NULL
;
512 struct pollfd pollfd
[_FD_MAX
];
513 sigset_t mask
, oldmask
;
518 if (flags
& ASK_PASSWORD_NO_AGENT
)
521 assert_se(sigemptyset(&mask
) >= 0);
522 assert_se(sigset_add_many(&mask
, SIGINT
, SIGTERM
, -1) >= 0);
523 assert_se(sigprocmask(SIG_BLOCK
, &mask
, &oldmask
) >= 0);
525 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
527 fd
= mkostemp_safe(temp
);
533 (void) fchmod(fd
, 0644);
543 signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
549 socket_fd
= create_socket(&socket_name
);
561 "NotAfter="USEC_FMT
"\n",
564 (flags
& ASK_PASSWORD_ACCEPT_CACHED
) ? 1 : 0,
565 (flags
& ASK_PASSWORD_ECHO
) ? 1 : 0,
569 fprintf(f
, "Message=%s\n", message
);
572 fprintf(f
, "Icon=%s\n", icon
);
575 fprintf(f
, "Id=%s\n", id
);
577 r
= fflush_and_check(f
);
581 memcpy(final
, temp
, sizeof(temp
));
583 final
[sizeof(final
)-11] = 'a';
584 final
[sizeof(final
)-10] = 's';
585 final
[sizeof(final
)-9] = 'k';
587 if (rename(temp
, final
) < 0) {
593 pollfd
[FD_SOCKET
].fd
= socket_fd
;
594 pollfd
[FD_SOCKET
].events
= POLLIN
;
595 pollfd
[FD_SIGNAL
].fd
= signal_fd
;
596 pollfd
[FD_SIGNAL
].events
= POLLIN
;
599 char passphrase
[LINE_MAX
+1];
600 struct msghdr msghdr
;
604 struct cmsghdr cmsghdr
;
605 uint8_t buf
[CMSG_SPACE(sizeof(struct ucred
))];
611 t
= now(CLOCK_MONOTONIC
);
613 if (until
> 0 && until
<= t
) {
618 k
= poll(pollfd
, _FD_MAX
, until
> 0 ? (int) ((until
-t
)/USEC_PER_MSEC
) : -1);
632 if (pollfd
[FD_SIGNAL
].revents
& POLLIN
) {
637 if (pollfd
[FD_SOCKET
].revents
!= POLLIN
) {
643 iovec
.iov_base
= passphrase
;
644 iovec
.iov_len
= sizeof(passphrase
);
648 msghdr
.msg_iov
= &iovec
;
649 msghdr
.msg_iovlen
= 1;
650 msghdr
.msg_control
= &control
;
651 msghdr
.msg_controllen
= sizeof(control
);
653 n
= recvmsg(socket_fd
, &msghdr
, 0);
655 if (IN_SET(errno
, EAGAIN
, EINTR
))
662 cmsg_close_all(&msghdr
);
665 log_debug("Message too short");
669 if (msghdr
.msg_controllen
< CMSG_LEN(sizeof(struct ucred
)) ||
670 control
.cmsghdr
.cmsg_level
!= SOL_SOCKET
||
671 control
.cmsghdr
.cmsg_type
!= SCM_CREDENTIALS
||
672 control
.cmsghdr
.cmsg_len
!= CMSG_LEN(sizeof(struct ucred
))) {
673 log_debug("Received message without credentials. Ignoring.");
677 ucred
= (struct ucred
*) CMSG_DATA(&control
.cmsghdr
);
678 if (ucred
->uid
!= 0) {
679 log_debug("Got request from unprivileged user. Ignoring.");
683 if (passphrase
[0] == '+') {
684 /* An empty message refers to the empty password */
686 l
= strv_new("", NULL
);
688 l
= strv_parse_nulstr(passphrase
+1, n
-1);
689 explicit_bzero(passphrase
, n
);
695 if (strv_isempty(l
)) {
697 log_debug("Invalid packet");
704 if (passphrase
[0] == '-') {
709 log_debug("Invalid packet");
713 (void) add_to_keyring_and_log(keyname
, flags
, l
);
720 (void) unlink(socket_name
);
725 (void) unlink(final
);
727 assert_se(sigprocmask(SIG_SETMASK
, &oldmask
, NULL
) == 0);
731 int ask_password_auto(
737 AskPasswordFlags flags
,
744 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
) {
745 r
= ask_password_keyring(keyname
, flags
, ret
);
750 if (!(flags
& ASK_PASSWORD_NO_TTY
) && isatty(STDIN_FILENO
)) {
751 char *s
= NULL
, **l
= NULL
;
753 r
= ask_password_tty(-1, message
, keyname
, until
, flags
, NULL
, &s
);
757 r
= strv_push(&l
, s
);
768 if (!(flags
& ASK_PASSWORD_NO_AGENT
))
769 return ask_password_agent(message
, icon
, id
, keyname
, until
, flags
, ret
);