1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010 Lennart Poettering
20 #include <sys/inotify.h>
21 #include <sys/signalfd.h>
22 #include <sys/socket.h>
30 #include "alloc-util.h"
31 #include "ask-password-api.h"
34 #include "format-util.h"
40 #include "process-util.h"
41 #include "random-util.h"
42 #include "signal-util.h"
43 #include "socket-util.h"
44 #include "string-util.h"
46 #include "terminal-util.h"
47 #include "time-util.h"
48 #include "umask-util.h"
52 #define KEYRING_TIMEOUT_USEC ((5 * USEC_PER_MINUTE) / 2)
54 static int lookup_key(const char *keyname
, key_serial_t
*ret
) {
60 serial
= request_key("user", keyname
, NULL
, 0);
62 return negative_errno();
68 static int retrieve_key(key_serial_t serial
, char ***ret
) {
69 _cleanup_free_
char *p
= NULL
;
80 n
= keyctl(KEYCTL_READ
, (unsigned long) serial
, (unsigned long) p
, (unsigned long) m
, 0);
92 l
= strv_parse_nulstr(p
, n
);
102 static int add_to_keyring(const char *keyname
, AskPasswordFlags flags
, char **passwords
) {
103 _cleanup_strv_free_erase_
char **l
= NULL
;
104 _cleanup_free_
char *p
= NULL
;
112 if (!(flags
& ASK_PASSWORD_PUSH_CACHE
))
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
);
132 explicit_bzero(p
, n
);
136 if (keyctl(KEYCTL_SET_TIMEOUT
,
137 (unsigned long) serial
,
138 (unsigned long) DIV_ROUND_UP(KEYRING_TIMEOUT_USEC
, USEC_PER_SEC
), 0, 0) < 0)
139 log_debug_errno(errno
, "Failed to adjust timeout: %m");
141 log_debug("Added key to keyring as %" PRIi32
".", serial
);
146 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 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 void backspace_chars(int ttyfd
, size_t p
) {
187 loop_write(ttyfd
, "\b \b", 3, false);
191 static void backspace_string(int ttyfd
, const char *str
) {
199 /* Backspaces through enough characters to entirely undo printing of the specified string. */
201 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 output. Most
204 * likely this happened because we are not in an UTF-8 locale, and in that case that
205 * is the correct thing to do. And even if it's not, terminals tend to stop
206 * backspacing at the leftmost column, hence backspacing too much should be mostly
209 backspace_chars(ttyfd
, m
);
212 int ask_password_tty(
217 AskPasswordFlags flags
,
218 const char *flag_file
,
227 bool reset_tty
= false, dirty
= false, use_color
= false;
228 _cleanup_close_
int cttyfd
= -1, notify
= -1;
229 struct termios old_termios
, new_termios
;
230 char passphrase
[LINE_MAX
+ 1] = {}, *x
;
231 struct pollfd pollfd
[_POLL_MAX
];
232 size_t p
= 0, codepoint
= 0;
237 if (flags
& ASK_PASSWORD_NO_TTY
)
241 message
= "Password:";
244 notify
= inotify_init1(IN_CLOEXEC
|IN_NONBLOCK
);
248 if (inotify_add_watch(notify
, flag_file
, IN_ATTRIB
/* for the link count */) < 0)
252 /* If the caller didn't specify a TTY, then use the controlling tty, if we can. */
254 ttyfd
= cttyfd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
257 if (tcgetattr(ttyfd
, &old_termios
) < 0)
260 if (flags
& ASK_PASSWORD_CONSOLE_COLOR
)
261 use_color
= dev_console_colors_enabled();
263 use_color
= colors_enabled();
266 (void) loop_write(ttyfd
, ANSI_HIGHLIGHT
, STRLEN(ANSI_HIGHLIGHT
), false);
268 (void) loop_write(ttyfd
, message
, strlen(message
), false);
269 (void) loop_write(ttyfd
, " ", 1, false);
272 (void) loop_write(ttyfd
, ANSI_NORMAL
, STRLEN(ANSI_NORMAL
), false);
274 new_termios
= old_termios
;
275 new_termios
.c_lflag
&= ~(ICANON
|ECHO
);
276 new_termios
.c_cc
[VMIN
] = 1;
277 new_termios
.c_cc
[VTIME
] = 0;
279 if (tcsetattr(ttyfd
, TCSADRAIN
, &new_termios
) < 0) {
287 pollfd
[POLL_TTY
] = (struct pollfd
) {
288 .fd
= ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
,
291 pollfd
[POLL_INOTIFY
] = (struct pollfd
) {
297 int sleep_for
= -1, k
;
304 y
= now(CLOCK_MONOTONIC
);
311 sleep_for
= (int) DIV_ROUND_UP(until
- y
, USEC_PER_MSEC
);
315 if (access(flag_file
, F_OK
) < 0) {
320 k
= poll(pollfd
, notify
>= 0 ? 2 : 1, sleep_for
);
332 if (notify
>= 0 && pollfd
[POLL_INOTIFY
].revents
!= 0)
333 (void) flush_fd(notify
);
335 if (pollfd
[POLL_TTY
].revents
== 0)
338 n
= read(ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
, &c
, 1);
340 if (IN_SET(errno
, EINTR
, EAGAIN
))
348 /* We treat EOF, newline and NUL byte all as valid end markers */
349 if (n
== 0 || c
== '\n' || c
== 0)
352 if (c
== 21) { /* C-u */
354 if (!(flags
& ASK_PASSWORD_SILENT
))
355 backspace_string(ttyfd
, passphrase
);
357 explicit_bzero(passphrase
, sizeof(passphrase
));
360 } else if (IN_SET(c
, '\b', 127)) {
365 if (!(flags
& ASK_PASSWORD_SILENT
))
366 backspace_chars(ttyfd
, 1);
368 /* Remove a full UTF-8 codepoint from the end. For that, figure out where the last one
374 z
= utf8_encoded_valid_unichar(passphrase
+ q
);
376 q
= (size_t) -1; /* Invalid UTF8! */
380 if (q
+ z
>= p
) /* This one brings us over the edge */
386 p
= codepoint
= q
== (size_t) -1 ? p
- 1 : q
;
387 explicit_bzero(passphrase
+ p
, sizeof(passphrase
) - p
);
389 } else if (!dirty
&& !(flags
& ASK_PASSWORD_SILENT
)) {
391 flags
|= ASK_PASSWORD_SILENT
;
393 /* There are two ways to enter silent mode. Either by pressing backspace as first key
394 * (and only as first key), or ... */
397 (void) loop_write(ttyfd
, "(no echo) ", 10, false);
399 } else if (ttyfd
>= 0)
400 (void) loop_write(ttyfd
, "\a", 1, false);
402 } else if (c
== '\t' && !(flags
& ASK_PASSWORD_SILENT
)) {
404 backspace_string(ttyfd
, passphrase
);
405 flags
|= ASK_PASSWORD_SILENT
;
407 /* ... or by pressing TAB at any time. */
410 (void) loop_write(ttyfd
, "(no echo) ", 10, false);
412 } else if (p
>= sizeof(passphrase
)-1) {
414 /* Reached the size limit */
416 (void) loop_write(ttyfd
, "\a", 1, false);
421 if (!(flags
& ASK_PASSWORD_SILENT
) && ttyfd
>= 0) {
422 /* Check if we got a complete UTF-8 character now. If so, let's output one '*'. */
423 n
= utf8_encoded_valid_unichar(passphrase
+ codepoint
);
426 (void) loop_write(ttyfd
, (flags
& ASK_PASSWORD_ECHO
) ? &c
: "*", 1, false);
433 /* Let's forget this char, just to not keep needlessly copies of key material around */
437 x
= strndup(passphrase
, p
);
438 explicit_bzero(passphrase
, sizeof(passphrase
));
445 (void) add_to_keyring_and_log(keyname
, flags
, STRV_MAKE(x
));
451 if (ttyfd
>= 0 && reset_tty
) {
452 (void) loop_write(ttyfd
, "\n", 1, false);
453 (void) tcsetattr(ttyfd
, TCSADRAIN
, &old_termios
);
459 static int create_socket(char **name
) {
460 union sockaddr_union sa
= {
461 .un
.sun_family
= AF_UNIX
,
463 _cleanup_close_
int fd
= -1;
464 static const int one
= 1;
470 fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
474 snprintf(sa
.un
.sun_path
, sizeof(sa
.un
.sun_path
)-1, "/run/systemd/ask-password/sck.%" PRIx64
, random_u64());
476 RUN_WITH_UMASK(0177) {
477 if (bind(fd
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
)) < 0)
481 if (setsockopt(fd
, SOL_SOCKET
, SO_PASSCRED
, &one
, sizeof(one
)) < 0)
484 c
= strdup(sa
.un
.sun_path
);
496 int ask_password_agent(
502 AskPasswordFlags flags
,
511 _cleanup_close_
int socket_fd
= -1, signal_fd
= -1, fd
= -1;
512 char temp
[] = "/run/systemd/ask-password/tmp.XXXXXX";
513 char final
[sizeof(temp
)] = "";
514 _cleanup_free_
char *socket_name
= NULL
;
515 _cleanup_strv_free_
char **l
= NULL
;
516 _cleanup_fclose_
FILE *f
= NULL
;
517 struct pollfd pollfd
[_FD_MAX
];
518 sigset_t mask
, oldmask
;
523 if (flags
& ASK_PASSWORD_NO_AGENT
)
526 assert_se(sigemptyset(&mask
) >= 0);
527 assert_se(sigset_add_many(&mask
, SIGINT
, SIGTERM
, -1) >= 0);
528 assert_se(sigprocmask(SIG_BLOCK
, &mask
, &oldmask
) >= 0);
530 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
532 fd
= mkostemp_safe(temp
);
538 (void) fchmod(fd
, 0644);
548 signal_fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
554 socket_fd
= create_socket(&socket_name
);
566 "NotAfter="USEC_FMT
"\n",
569 (flags
& ASK_PASSWORD_ACCEPT_CACHED
) ? 1 : 0,
570 (flags
& ASK_PASSWORD_ECHO
) ? 1 : 0,
574 fprintf(f
, "Message=%s\n", message
);
577 fprintf(f
, "Icon=%s\n", icon
);
580 fprintf(f
, "Id=%s\n", id
);
582 r
= fflush_and_check(f
);
586 memcpy(final
, temp
, sizeof(temp
));
588 final
[sizeof(final
)-11] = 'a';
589 final
[sizeof(final
)-10] = 's';
590 final
[sizeof(final
)-9] = 'k';
592 if (rename(temp
, final
) < 0) {
598 pollfd
[FD_SOCKET
].fd
= socket_fd
;
599 pollfd
[FD_SOCKET
].events
= POLLIN
;
600 pollfd
[FD_SIGNAL
].fd
= signal_fd
;
601 pollfd
[FD_SIGNAL
].events
= POLLIN
;
604 char passphrase
[LINE_MAX
+1];
605 struct msghdr msghdr
;
609 struct cmsghdr cmsghdr
;
610 uint8_t buf
[CMSG_SPACE(sizeof(struct ucred
))];
616 t
= now(CLOCK_MONOTONIC
);
618 if (until
> 0 && until
<= t
) {
623 k
= poll(pollfd
, _FD_MAX
, until
> 0 ? (int) ((until
-t
)/USEC_PER_MSEC
) : -1);
637 if (pollfd
[FD_SIGNAL
].revents
& POLLIN
) {
642 if (pollfd
[FD_SOCKET
].revents
!= POLLIN
) {
648 iovec
.iov_base
= passphrase
;
649 iovec
.iov_len
= sizeof(passphrase
);
653 msghdr
.msg_iov
= &iovec
;
654 msghdr
.msg_iovlen
= 1;
655 msghdr
.msg_control
= &control
;
656 msghdr
.msg_controllen
= sizeof(control
);
658 n
= recvmsg(socket_fd
, &msghdr
, 0);
660 if (IN_SET(errno
, EAGAIN
, EINTR
))
667 cmsg_close_all(&msghdr
);
670 log_debug("Message too short");
674 if (msghdr
.msg_controllen
< CMSG_LEN(sizeof(struct ucred
)) ||
675 control
.cmsghdr
.cmsg_level
!= SOL_SOCKET
||
676 control
.cmsghdr
.cmsg_type
!= SCM_CREDENTIALS
||
677 control
.cmsghdr
.cmsg_len
!= CMSG_LEN(sizeof(struct ucred
))) {
678 log_debug("Received message without credentials. Ignoring.");
682 ucred
= (struct ucred
*) CMSG_DATA(&control
.cmsghdr
);
683 if (ucred
->uid
!= 0) {
684 log_debug("Got request from unprivileged user. Ignoring.");
688 if (passphrase
[0] == '+') {
689 /* An empty message refers to the empty password */
691 l
= strv_new("", NULL
);
693 l
= strv_parse_nulstr(passphrase
+1, n
-1);
694 explicit_bzero(passphrase
, n
);
700 if (strv_isempty(l
)) {
702 log_debug("Invalid packet");
709 if (passphrase
[0] == '-') {
714 log_debug("Invalid packet");
718 (void) add_to_keyring_and_log(keyname
, flags
, l
);
725 (void) unlink(socket_name
);
730 (void) unlink(final
);
732 assert_se(sigprocmask(SIG_SETMASK
, &oldmask
, NULL
) == 0);
736 int ask_password_auto(
742 AskPasswordFlags flags
,
749 if ((flags
& ASK_PASSWORD_ACCEPT_CACHED
) && keyname
) {
750 r
= ask_password_keyring(keyname
, flags
, ret
);
755 if (!(flags
& ASK_PASSWORD_NO_TTY
) && isatty(STDIN_FILENO
)) {
756 char *s
= NULL
, **l
= NULL
;
758 r
= ask_password_tty(-1, message
, keyname
, until
, flags
, NULL
, &s
);
762 r
= strv_push(&l
, s
);
773 if (!(flags
& ASK_PASSWORD_NO_AGENT
))
774 return ask_password_agent(message
, icon
, id
, keyname
, until
, flags
, ret
);