chiark / gitweb /
udev: systemd-tag all ttys
[elogind.git] / src / ask-password-api.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21 #include <stdbool.h>
22 #include <termios.h>
23 #include <unistd.h>
24 #include <sys/poll.h>
25 #include <sys/inotify.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <sys/socket.h>
29 #include <string.h>
30 #include <sys/un.h>
31 #include <stddef.h>
32 #include <sys/signalfd.h>
33
34 #include "util.h"
35 #include "strv.h"
36
37 #include "ask-password-api.h"
38
39 static void backspace_chars(int ttyfd, size_t p) {
40
41         if (ttyfd < 0)
42                 return;
43
44         while (p > 0) {
45                 p--;
46
47                 loop_write(ttyfd, "\b \b", 3, false);
48         }
49 }
50
51 int ask_password_tty(
52                 const char *message,
53                 usec_t until,
54                 const char *flag_file,
55                 char **_passphrase) {
56
57         struct termios old_termios, new_termios;
58         char passphrase[LINE_MAX];
59         size_t p = 0;
60         int r, ttyfd = -1, notify = -1;
61         struct pollfd pollfd[2];
62         bool reset_tty = false;
63         bool silent_mode = false;
64         enum {
65                 POLL_TTY,
66                 POLL_INOTIFY
67         };
68
69         assert(message);
70         assert(_passphrase);
71
72         if (flag_file) {
73                 if ((notify = inotify_init1(IN_CLOEXEC|IN_NONBLOCK)) < 0) {
74                         r = -errno;
75                         goto finish;
76                 }
77
78                 if (inotify_add_watch(notify, flag_file, IN_ATTRIB /* for the link count */) < 0) {
79                         r = -errno;
80                         goto finish;
81                 }
82         }
83
84         if ((ttyfd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC)) >= 0) {
85
86                 if (tcgetattr(ttyfd, &old_termios) < 0) {
87                         r = -errno;
88                         goto finish;
89                 }
90
91                 loop_write(ttyfd, "\x1B[1m", 4, false);
92                 loop_write(ttyfd, message, strlen(message), false);
93                 loop_write(ttyfd, " ", 1, false);
94                 loop_write(ttyfd, "\x1B[0m", 4, false);
95
96                 new_termios = old_termios;
97                 new_termios.c_lflag &= ~(ICANON|ECHO);
98                 new_termios.c_cc[VMIN] = 1;
99                 new_termios.c_cc[VTIME] = 0;
100
101                 if (tcsetattr(ttyfd, TCSADRAIN, &new_termios) < 0) {
102                         r = -errno;
103                         goto finish;
104                 }
105
106                 reset_tty = true;
107         }
108
109         zero(pollfd);
110
111         pollfd[POLL_TTY].fd = ttyfd >= 0 ? ttyfd : STDIN_FILENO;
112         pollfd[POLL_TTY].events = POLLIN;
113         pollfd[POLL_INOTIFY].fd = notify;
114         pollfd[POLL_INOTIFY].events = POLLIN;
115
116         for (;;) {
117                 char c;
118                 int sleep_for = -1, k;
119                 ssize_t n;
120
121                 if (until > 0) {
122                         usec_t y;
123
124                         y = now(CLOCK_MONOTONIC);
125
126                         if (y > until) {
127                                 r = -ETIME;
128                                 goto finish;
129                         }
130
131                         sleep_for = (int) ((until - y) / USEC_PER_MSEC);
132                 }
133
134                 if (flag_file)
135                         if (access(flag_file, F_OK) < 0) {
136                                 r = -errno;
137                                 goto finish;
138                         }
139
140                 if ((k = poll(pollfd, notify > 0 ? 2 : 1, sleep_for)) < 0) {
141
142                         if (errno == EINTR)
143                                 continue;
144
145                         r = -errno;
146                         goto finish;
147                 } else if (k == 0) {
148                         r = -ETIME;
149                         goto finish;
150                 }
151
152                 if (notify > 0 && pollfd[POLL_INOTIFY].revents != 0)
153                         flush_fd(notify);
154
155                 if (pollfd[POLL_TTY].revents == 0)
156                         continue;
157
158                 if ((n = read(ttyfd >= 0 ? ttyfd : STDIN_FILENO, &c, 1)) < 0) {
159
160                         if (errno == EINTR || errno == EAGAIN)
161                                 continue;
162
163                         r = -errno;
164                         goto finish;
165
166                 } else if (n == 0)
167                         break;
168
169                 if (c == '\n')
170                         break;
171                 else if (c == 21) { /* C-u */
172
173                         if (!silent_mode)
174                                 backspace_chars(ttyfd, p);
175                         p = 0;
176
177                 } else if (c == '\b' || c == 127) {
178
179                         if (p > 0) {
180
181                                 if (!silent_mode)
182                                         backspace_chars(ttyfd, 1);
183
184                                 p--;
185                         } else if (ttyfd >= 0)
186                                 loop_write(ttyfd, "\a", 1, false);
187
188                 } else if (c == '\t' && !silent_mode) {
189
190                         backspace_chars(ttyfd, p);
191                         silent_mode = true;
192
193                         if (ttyfd >= 0)
194                                 loop_write(ttyfd, "(no echo) ", 10, false);
195                 } else {
196                         passphrase[p++] = c;
197
198                         if (!silent_mode && ttyfd >= 0)
199                                 loop_write(ttyfd, "*", 1, false);
200                 }
201         }
202
203         passphrase[p] = 0;
204
205         if (!(*_passphrase = strdup(passphrase))) {
206                 r = -ENOMEM;
207                 goto finish;
208         }
209
210         r = 0;
211
212 finish:
213         if (notify >= 0)
214                 close_nointr_nofail(notify);
215
216         if (ttyfd >= 0) {
217
218                 if (reset_tty) {
219                         loop_write(ttyfd, "\n", 1, false);
220                         tcsetattr(ttyfd, TCSADRAIN, &old_termios);
221                 }
222
223                 close_nointr_nofail(ttyfd);
224         }
225
226         return r;
227 }
228
229 static int create_socket(char **name) {
230         int fd;
231         union {
232                 struct sockaddr sa;
233                 struct sockaddr_un un;
234         } sa;
235         int one = 1, r;
236         char *c;
237
238         assert(name);
239
240         if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
241                 log_error("socket() failed: %m");
242                 return -errno;
243         }
244
245         zero(sa);
246         sa.un.sun_family = AF_UNIX;
247         snprintf(sa.un.sun_path, sizeof(sa.un.sun_path)-1, "/run/systemd/ask-password/sck.%llu", random_ull());
248
249         if (bind(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(sa.un.sun_path)) < 0) {
250                 r = -errno;
251                 log_error("bind() failed: %m");
252                 goto fail;
253         }
254
255         if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0) {
256                 r = -errno;
257                 log_error("SO_PASSCRED failed: %m");
258                 goto fail;
259         }
260
261         if (!(c = strdup(sa.un.sun_path))) {
262                 r = -ENOMEM;
263                 log_error("Out of memory");
264                 goto fail;
265         }
266
267         *name = c;
268         return fd;
269
270 fail:
271         close_nointr_nofail(fd);
272
273         return r;
274 }
275
276 int ask_password_agent(
277                 const char *message,
278                 const char *icon,
279                 usec_t until,
280                 bool accept_cached,
281                 char ***_passphrases) {
282
283         enum {
284                 FD_SOCKET,
285                 FD_SIGNAL,
286                 _FD_MAX
287         };
288
289         char temp[] = "/run/systemd/ask-password/tmp.XXXXXX";
290         char final[sizeof(temp)] = "";
291         int fd = -1, r;
292         FILE *f = NULL;
293         char *socket_name = NULL;
294         int socket_fd = -1, signal_fd = -1;
295         sigset_t mask, oldmask;
296         struct pollfd pollfd[_FD_MAX];
297
298         assert(_passphrases);
299
300         assert_se(sigemptyset(&mask) == 0);
301         sigset_add_many(&mask, SIGINT, SIGTERM, -1);
302         assert_se(sigprocmask(SIG_BLOCK, &mask, &oldmask) == 0);
303
304         mkdir_p("/run/systemd/ask-password", 0755);
305
306         if ((fd = mkostemp(temp, O_CLOEXEC|O_CREAT|O_WRONLY)) < 0) {
307                 log_error("Failed to create password file: %m");
308                 r = -errno;
309                 goto finish;
310         }
311
312         fchmod(fd, 0644);
313
314         if (!(f = fdopen(fd, "w"))) {
315                 log_error("Failed to allocate FILE: %m");
316                 r = -errno;
317                 goto finish;
318         }
319
320         fd = -1;
321
322         if ((signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
323                 log_error("signalfd(): %m");
324                 r = -errno;
325                 goto finish;
326         }
327
328         if ((socket_fd = create_socket(&socket_name)) < 0) {
329                 r = socket_fd;
330                 goto finish;
331         }
332
333         fprintf(f,
334                 "[Ask]\n"
335                 "PID=%lu\n"
336                 "Socket=%s\n"
337                 "AcceptCached=%i\n"
338                 "NotAfter=%llu\n",
339                 (unsigned long) getpid(),
340                 socket_name,
341                 accept_cached ? 1 : 0,
342                 (unsigned long long) until);
343
344         if (message)
345                 fprintf(f, "Message=%s\n", message);
346
347         if (icon)
348                 fprintf(f, "Icon=%s\n", icon);
349
350         fflush(f);
351
352         if (ferror(f)) {
353                 log_error("Failed to write query file: %m");
354                 r = -errno;
355                 goto finish;
356         }
357
358         memcpy(final, temp, sizeof(temp));
359
360         final[sizeof(final)-11] = 'a';
361         final[sizeof(final)-10] = 's';
362         final[sizeof(final)-9] = 'k';
363
364         if (rename(temp, final) < 0) {
365                 log_error("Failed to rename query file: %m");
366                 r = -errno;
367                 goto finish;
368         }
369
370         zero(pollfd);
371         pollfd[FD_SOCKET].fd = socket_fd;
372         pollfd[FD_SOCKET].events = POLLIN;
373         pollfd[FD_SIGNAL].fd = signal_fd;
374         pollfd[FD_SIGNAL].events = POLLIN;
375
376         for (;;) {
377                 char passphrase[LINE_MAX+1];
378                 struct msghdr msghdr;
379                 struct iovec iovec;
380                 struct ucred *ucred;
381                 union {
382                         struct cmsghdr cmsghdr;
383                         uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
384                 } control;
385                 ssize_t n;
386                 int k;
387                 usec_t t;
388
389                 t = now(CLOCK_MONOTONIC);
390
391                 if (until <= t) {
392                         log_notice("Timed out");
393                         r = -ETIME;
394                         goto finish;
395                 }
396
397                 if ((k = poll(pollfd, _FD_MAX, (until-t)/USEC_PER_MSEC)) < 0) {
398
399                         if (errno == EINTR)
400                                 continue;
401
402                         log_error("poll() failed: %m");
403                         r = -errno;
404                         goto finish;
405                 }
406
407                 if (k <= 0) {
408                         log_notice("Timed out");
409                         r = -ETIME;
410                         goto finish;
411                 }
412
413                 if (pollfd[FD_SIGNAL].revents & POLLIN) {
414                         r = -EINTR;
415                         goto finish;
416                 }
417
418                 if (pollfd[FD_SOCKET].revents != POLLIN) {
419                         log_error("Unexpected poll() event.");
420                         r = -EIO;
421                         goto finish;
422                 }
423
424                 zero(iovec);
425                 iovec.iov_base = passphrase;
426                 iovec.iov_len = sizeof(passphrase);
427
428                 zero(control);
429                 zero(msghdr);
430                 msghdr.msg_iov = &iovec;
431                 msghdr.msg_iovlen = 1;
432                 msghdr.msg_control = &control;
433                 msghdr.msg_controllen = sizeof(control);
434
435                 if ((n = recvmsg(socket_fd, &msghdr, 0)) < 0) {
436
437                         if (errno == EAGAIN ||
438                             errno == EINTR)
439                                 continue;
440
441                         log_error("recvmsg() failed: %m");
442                         r = -errno;
443                         goto finish;
444                 }
445
446                 if (n <= 0) {
447                         log_error("Message too short");
448                         continue;
449                 }
450
451                 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
452                     control.cmsghdr.cmsg_level != SOL_SOCKET ||
453                     control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
454                     control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
455                         log_warning("Received message without credentials. Ignoring.");
456                         continue;
457                 }
458
459                 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
460                 if (ucred->uid != 0) {
461                         log_warning("Got request from unprivileged user. Ignoring.");
462                         continue;
463                 }
464
465                 if (passphrase[0] == '+') {
466                         char **l;
467
468                         if (!(l = strv_parse_nulstr(passphrase+1, n-1))) {
469                                 r = -ENOMEM;
470                                 goto finish;
471                         }
472
473                         if (strv_length(l) <= 0) {
474                                 strv_free(l);
475                                 log_error("Invalid packet");
476                                 continue;
477                         }
478
479                         *_passphrases = l;
480
481                 } else if (passphrase[0] == '-') {
482                         r = -ECANCELED;
483                         goto finish;
484                 } else {
485                         log_error("Invalid packet");
486                         continue;
487                 }
488
489                 break;
490         }
491
492         r = 0;
493
494 finish:
495         if (fd >= 0)
496                 close_nointr_nofail(fd);
497
498         if (socket_name) {
499                 unlink(socket_name);
500                 free(socket_name);
501         }
502
503         if (socket_fd >= 0)
504                 close_nointr_nofail(socket_fd);
505
506         if (signal_fd >= 0)
507                 close_nointr_nofail(signal_fd);
508
509         if (f)
510                 fclose(f);
511
512         unlink(temp);
513
514         if (final[0])
515                 unlink(final);
516
517         assert_se(sigprocmask(SIG_SETMASK, &oldmask, NULL) == 0);
518
519         return r;
520 }
521
522 int ask_password_auto(const char *message, const char *icon, usec_t until, bool accept_cached, char ***_passphrases) {
523         assert(message);
524         assert(_passphrases);
525
526         if (isatty(STDIN_FILENO)) {
527                 int r;
528                 char *s = NULL, **l = NULL;
529
530                 if ((r = ask_password_tty(message, until, NULL, &s)) < 0)
531                         return r;
532
533                 l = strv_new(s, NULL);
534                 free(s);
535
536                 if (!l)
537                         return -ENOMEM;
538
539                 *_passphrases = l;
540                 return r;
541
542         } else
543                 return ask_password_agent(message, icon, until, accept_cached, _passphrases);
544 }