chiark / gitweb /
virtualization: beef virtualization code
[elogind.git] / src / tty-ask-password-agent.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
22 #include <stdbool.h>
23 #include <errno.h>
24 #include <string.h>
25 #include <sys/socket.h>
26 #include <sys/un.h>
27 #include <stddef.h>
28 #include <sys/poll.h>
29 #include <sys/inotify.h>
30 #include <unistd.h>
31 #include <getopt.h>
32 #include <sys/signalfd.h>
33 #include <fcntl.h>
34
35 #include "util.h"
36 #include "conf-parser.h"
37 #include "utmp-wtmp.h"
38 #include "socket-util.h"
39 #include "ask-password-api.h"
40
41 static enum {
42         ACTION_LIST,
43         ACTION_QUERY,
44         ACTION_WATCH,
45         ACTION_WALL
46 } arg_action = ACTION_QUERY;
47
48 static bool arg_plymouth = false;
49 static bool arg_console = false;
50
51 static int ask_password_plymouth(const char *message, usec_t until, const char *flag_file, char **_passphrase) {
52         int fd = -1, notify = -1;
53         union sockaddr_union sa;
54         char *packet = NULL;
55         ssize_t k;
56         int r, n;
57         struct pollfd pollfd[2];
58         char buffer[LINE_MAX];
59         size_t p = 0;
60         enum {
61                 POLL_SOCKET,
62                 POLL_INOTIFY
63         };
64
65         if (flag_file) {
66                 if ((notify = inotify_init1(IN_CLOEXEC|IN_NONBLOCK)) < 0) {
67                         r = -errno;
68                         goto finish;
69                 }
70
71                 if (inotify_add_watch(notify, flag_file, IN_ATTRIB /* for the link count */) < 0) {
72                         r = -errno;
73                         goto finish;
74                 }
75         }
76
77         if ((fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
78                 r = -errno;
79                 goto finish;
80         }
81
82         zero(sa);
83         sa.sa.sa_family = AF_UNIX;
84         strncpy(sa.un.sun_path+1, "/org/freedesktop/plymouthd", sizeof(sa.un.sun_path)-1);
85         if (connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1)) < 0) {
86                 log_error("FAILED TO CONNECT: %m");
87                 r = -errno;
88                 goto finish;
89         }
90
91         if (asprintf(&packet, "*\002%c%s%n", (int) (strlen(message) + 1), message, &n) < 0) {
92                 r = -ENOMEM;
93                 goto finish;
94         }
95
96         if ((k = loop_write(fd, packet, n+1, true)) != n+1) {
97                 r = k < 0 ? (int) k : -EIO;
98                 goto finish;
99         }
100
101         zero(pollfd);
102         pollfd[POLL_SOCKET].fd = fd;
103         pollfd[POLL_SOCKET].events = POLLIN;
104         pollfd[POLL_INOTIFY].fd = notify;
105         pollfd[POLL_INOTIFY].events = POLLIN;
106
107         for (;;) {
108                 int sleep_for = -1, j;
109
110                 if (until > 0) {
111                         usec_t y;
112
113                         y = now(CLOCK_MONOTONIC);
114
115                         if (y > until) {
116                                 r = -ETIMEDOUT;
117                                 goto finish;
118                         }
119
120                         sleep_for = (int) ((until - y) / USEC_PER_MSEC);
121                 }
122
123                 if (flag_file)
124                         if (access(flag_file, F_OK) < 0) {
125                                 r = -errno;
126                                 goto finish;
127                         }
128
129                 if ((j = poll(pollfd, notify > 0 ? 2 : 1, sleep_for)) < 0) {
130
131                         if (errno == EINTR)
132                                 continue;
133
134                         r = -errno;
135                         goto finish;
136                 } else if (j == 0) {
137                         r = -ETIMEDOUT;
138                         goto finish;
139                 }
140
141                 if (notify > 0 && pollfd[POLL_INOTIFY].revents != 0)
142                         flush_fd(notify);
143
144                 if (pollfd[POLL_SOCKET].revents == 0)
145                         continue;
146
147                 if ((k = read(fd, buffer + p, sizeof(buffer) - p)) <= 0) {
148                         r = k < 0 ? -errno : -EIO;
149                         goto finish;
150                 }
151
152                 p += k;
153
154                 if (p < 1)
155                         continue;
156
157                 if (buffer[0] == 5) {
158                         /* No password, because UI not shown */
159                         r = -ENOENT;
160                         goto finish;
161
162                 } else if (buffer[0] == 2) {
163                         uint32_t size;
164                         char *s;
165
166                         /* One answer */
167                         if (p < 5)
168                                 continue;
169
170                         memcpy(&size, buffer+1, sizeof(size));
171                         if (size+5 > sizeof(buffer)) {
172                                 r = -EIO;
173                                 goto finish;
174                         }
175
176                         if (p-5 < size)
177                                 continue;
178
179                         if (!(s = strndup(buffer + 5, size))) {
180                                 r = -ENOMEM;
181                                 goto finish;
182                         }
183
184                         *_passphrase = s;
185                         break;
186                 } else {
187                         /* Unknown packet */
188                         r = -EIO;
189                         goto finish;
190                 }
191         }
192
193         r = 0;
194
195 finish:
196         if (notify >= 0)
197                 close_nointr_nofail(notify);
198
199         if (fd >= 0)
200                 close_nointr_nofail(fd);
201
202         free(packet);
203
204         return r;
205 }
206
207 static int parse_password(const char *filename, char **wall) {
208         char *socket_name = NULL, *message = NULL, *packet = NULL;
209         uint64_t not_after = 0;
210         unsigned pid = 0;
211         int socket_fd = -1;
212
213         const ConfigItem items[] = {
214                 { "Socket",   config_parse_string,   &socket_name, "Ask" },
215                 { "NotAfter", config_parse_uint64,   &not_after,   "Ask" },
216                 { "Message",  config_parse_string,   &message,     "Ask" },
217                 { "PID",      config_parse_unsigned, &pid,         "Ask" },
218                 { NULL, NULL, NULL, NULL }
219         };
220
221         FILE *f;
222         int r;
223         usec_t n;
224
225         assert(filename);
226
227         if (!(f = fopen(filename, "re"))) {
228
229                 if (errno == ENOENT)
230                         return 0;
231
232                 log_error("open(%s): %m", filename);
233                 return -errno;
234         }
235
236         if ((r = config_parse(filename, f, NULL, items, true, NULL)) < 0) {
237                 log_error("Failed to parse password file %s: %s", filename, strerror(-r));
238                 goto finish;
239         }
240
241         if (!socket_name || not_after <= 0) {
242                 log_error("Invalid password file %s", filename);
243                 r = -EBADMSG;
244                 goto finish;
245         }
246
247         n = now(CLOCK_MONOTONIC);
248         if (n > not_after) {
249                 r = 0;
250                 goto finish;
251         }
252
253         if (arg_action == ACTION_LIST)
254                 printf("'%s' (PID %u)\n", message, pid);
255         else if (arg_action == ACTION_WALL) {
256                 char *_wall;
257
258                 if (asprintf(&_wall,
259                              "%s%sPassword entry required for \'%s\' (PID %u).\r\n"
260                              "Please enter password with the systemd-tty-ask-password-agent tool!",
261                              *wall ? *wall : "",
262                              *wall ? "\r\n\r\n" : "",
263                              message,
264                              pid) < 0) {
265                         log_error("Out of memory");
266                         r = -ENOMEM;
267                         goto finish;
268                 }
269
270                 free(*wall);
271                 *wall = _wall;
272         } else {
273                 union {
274                         struct sockaddr sa;
275                         struct sockaddr_un un;
276                 } sa;
277                 char *password;
278
279                 assert(arg_action == ACTION_QUERY ||
280                        arg_action == ACTION_WATCH);
281
282                 if (access(socket_name, W_OK) < 0) {
283
284                         if (arg_action == ACTION_QUERY)
285                                 log_info("Not querying '%s' (PID %u), lacking privileges.", message, pid);
286
287                         r = 0;
288                         goto finish;
289                 }
290
291                 if (arg_plymouth)
292                         r = ask_password_plymouth(message, not_after, filename, &password);
293                 else {
294                         int tty_fd = -1;
295
296                         if (arg_console)
297                                 if ((tty_fd = acquire_terminal("/dev/console", false, false, false)) < 0) {
298                                         r = tty_fd;
299                                         goto finish;
300                                 }
301
302                         r = ask_password_tty(message, not_after, filename, &password);
303
304                         if (arg_console) {
305                                 close_nointr_nofail(tty_fd);
306                                 release_terminal();
307                         }
308                 }
309
310                 if (r < 0) {
311                         log_error("Failed to query password: %s", strerror(-r));
312                         goto finish;
313                 }
314
315                 asprintf(&packet, "+%s", password);
316                 free(password);
317
318                 if (!packet) {
319                         log_error("Out of memory");
320                         r = -ENOMEM;
321                         goto finish;
322                 }
323
324                 if ((socket_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0) {
325                         log_error("socket(): %m");
326                         r = -errno;
327                         goto finish;
328                 }
329
330                 zero(sa);
331                 sa.un.sun_family = AF_UNIX;
332                 strncpy(sa.un.sun_path, socket_name, sizeof(sa.un.sun_path));
333
334                 if (sendto(socket_fd, packet, strlen(packet), MSG_NOSIGNAL, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(socket_name)) < 0) {
335                         log_error("Failed to send: %m");
336                         r = -errno;
337                         goto finish;
338                 }
339         }
340
341 finish:
342         fclose(f);
343
344         if (socket_fd >= 0)
345                 close_nointr_nofail(socket_fd);
346
347         free(packet);
348         free(socket_name);
349         free(message);
350
351         return r;
352 }
353
354 static int wall_tty_block(void) {
355         char *p;
356         int fd, r;
357         dev_t devnr;
358
359         if ((r = get_ctty_devnr(&devnr)) < 0)
360                 return -r;
361
362         if (asprintf(&p, "/dev/.systemd/ask-password-block/%u:%u", major(devnr), minor(devnr)) < 0)
363                 return -ENOMEM;
364
365         mkdir_parents(p, 0700);
366         mkfifo(p, 0600);
367
368         fd = open(p, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
369         free(p);
370
371         if (fd < 0)
372                 return -errno;
373
374         return fd;
375 }
376
377 static bool wall_tty_match(const char *path) {
378         int fd, k;
379         char *p;
380         struct stat st;
381
382         if (path_is_absolute(path))
383                 k = lstat(path, &st);
384         else {
385                 if (asprintf(&p, "/dev/%s", path) < 0)
386                         return true;
387
388                 k = lstat(p, &st);
389                 free(p);
390         }
391
392         if (k < 0)
393                 return true;
394
395         if (!S_ISCHR(st.st_mode))
396                 return true;
397
398         /* We use named pipes to ensure that wall messages suggesting
399          * password entry are not printed over password prompts
400          * already shown. We use the fact here that opening a pipe in
401          * non-blocking mode for write-only will succeed only if
402          * there's some writer behind it. Using pipes has the
403          * advantage that the block will automatically go away if the
404          * process dies. */
405
406         if (asprintf(&p, "/dev/.systemd/ask-password-block/%u:%u", major(st.st_rdev), minor(st.st_rdev)) < 0)
407                 return true;
408
409         fd = open(p, O_WRONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
410         free(p);
411
412         if (fd < 0)
413                 return true;
414
415         /* What, we managed to open the pipe? Then this tty is filtered. */
416         close_nointr_nofail(fd);
417         return false;
418 }
419
420 static int show_passwords(void) {
421         DIR *d;
422         struct dirent *de;
423         int r = 0;
424
425         if (!(d = opendir("/dev/.systemd/ask-password"))) {
426                 if (errno == ENOENT)
427                         return 0;
428
429                 log_error("opendir(): %m");
430                 return -errno;
431         }
432
433         while ((de = readdir(d))) {
434                 char *p;
435                 int q;
436                 char *wall;
437
438                 if (de->d_type != DT_REG)
439                         continue;
440
441                 if (ignore_file(de->d_name))
442                         continue;
443
444                 if (!startswith(de->d_name, "ask."))
445                         continue;
446
447                 if (!(p = strappend("/dev/.systemd/ask-password/", de->d_name))) {
448                         log_error("Out of memory");
449                         r = -ENOMEM;
450                         goto finish;
451                 }
452
453                 wall = NULL;
454                 if ((q = parse_password(p, &wall)) < 0)
455                         r = q;
456
457                 free(p);
458
459                 if (wall) {
460                         utmp_wall(wall, wall_tty_match);
461                         free(wall);
462                 }
463         }
464
465 finish:
466         if (d)
467                 closedir(d);
468
469         return r;
470 }
471
472 static int watch_passwords(void) {
473         enum {
474                 FD_INOTIFY,
475                 FD_SIGNAL,
476                 _FD_MAX
477         };
478
479         int notify = -1, signal_fd = -1, tty_block_fd = -1;
480         struct pollfd pollfd[_FD_MAX];
481         sigset_t mask;
482         int r;
483
484         tty_block_fd = wall_tty_block();
485
486         mkdir_p("/dev/.systemd/ask-password", 0755);
487
488         if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
489                 r = -errno;
490                 goto finish;
491         }
492
493         if (inotify_add_watch(notify, "/dev/.systemd/ask-password", IN_CLOSE_WRITE|IN_MOVED_TO) < 0) {
494                 r = -errno;
495                 goto finish;
496         }
497
498         assert_se(sigemptyset(&mask) == 0);
499         sigset_add_many(&mask, SIGINT, SIGTERM, -1);
500         assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
501
502         if ((signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
503                 log_error("signalfd(): %m");
504                 r = -errno;
505                 goto finish;
506         }
507
508         zero(pollfd);
509         pollfd[FD_INOTIFY].fd = notify;
510         pollfd[FD_INOTIFY].events = POLLIN;
511         pollfd[FD_SIGNAL].fd = signal_fd;
512         pollfd[FD_SIGNAL].events = POLLIN;
513
514         for (;;) {
515                 if ((r = show_passwords()) < 0)
516                         log_error("Failed to show password: %s", strerror(-r));
517
518                 if (poll(pollfd, _FD_MAX, -1) < 0) {
519
520                         if (errno == EINTR)
521                                 continue;
522
523                         r = -errno;
524                         goto finish;
525                 }
526
527                 if (pollfd[FD_INOTIFY].revents != 0)
528                         flush_fd(notify);
529
530                 if (pollfd[FD_SIGNAL].revents != 0)
531                         break;
532         }
533
534         r = 0;
535
536 finish:
537         if (notify >= 0)
538                 close_nointr_nofail(notify);
539
540         if (signal_fd >= 0)
541                 close_nointr_nofail(signal_fd);
542
543         if (tty_block_fd >= 0)
544                 close_nointr_nofail(tty_block_fd);
545
546         return r;
547 }
548
549 static int help(void) {
550
551         printf("%s [OPTIONS...]\n\n"
552                "Process system password requests.\n\n"
553                "  -h --help     Show this help\n"
554                "     --list     Show pending password requests\n"
555                "     --query    Process pending password requests\n"
556                "     --watch    Continously process password requests\n"
557                "     --wall     Continously forward password requests to wall\n"
558                "     --plymouth Ask question with Plymouth instead of on TTY\n"
559                "     --console  Ask question on /dev/console instead of current TTY\n",
560                program_invocation_short_name);
561
562         return 0;
563 }
564
565 static int parse_argv(int argc, char *argv[]) {
566
567         enum {
568                 ARG_LIST = 0x100,
569                 ARG_QUERY,
570                 ARG_WATCH,
571                 ARG_WALL,
572                 ARG_PLYMOUTH,
573                 ARG_CONSOLE
574         };
575
576         static const struct option options[] = {
577                 { "help",     no_argument, NULL, 'h'          },
578                 { "list",     no_argument, NULL, ARG_LIST     },
579                 { "query",    no_argument, NULL, ARG_QUERY    },
580                 { "watch",    no_argument, NULL, ARG_WATCH    },
581                 { "wall",     no_argument, NULL, ARG_WALL     },
582                 { "plymouth", no_argument, NULL, ARG_PLYMOUTH },
583                 { "console",  no_argument, NULL, ARG_CONSOLE  },
584                 { NULL,    0,           NULL, 0               }
585         };
586
587         int c;
588
589         assert(argc >= 0);
590         assert(argv);
591
592         while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
593
594                 switch (c) {
595
596                 case 'h':
597                         help();
598                         return 0;
599
600                 case ARG_LIST:
601                         arg_action = ACTION_LIST;
602                         break;
603
604                 case ARG_QUERY:
605                         arg_action = ACTION_QUERY;
606                         break;
607
608                 case ARG_WATCH:
609                         arg_action = ACTION_WATCH;
610                         break;
611
612                 case ARG_WALL:
613                         arg_action = ACTION_WALL;
614                         break;
615
616                 case ARG_PLYMOUTH:
617                         arg_plymouth = true;
618                         break;
619
620                 case ARG_CONSOLE:
621                         arg_console = true;
622                         break;
623
624                 case '?':
625                         return -EINVAL;
626
627                 default:
628                         log_error("Unknown option code %c", c);
629                         return -EINVAL;
630                 }
631         }
632
633         if (optind != argc) {
634                 help();
635                 return -EINVAL;
636         }
637
638         return 1;
639 }
640
641 int main(int argc, char *argv[]) {
642         int r;
643
644         log_parse_environment();
645         log_open();
646
647         if ((r = parse_argv(argc, argv)) <= 0)
648                 goto finish;
649
650         if (arg_console) {
651                 setsid();
652                 release_terminal();
653         }
654
655         if (arg_action == ACTION_WATCH ||
656             arg_action == ACTION_WALL)
657                 r = watch_passwords();
658         else
659                 r = show_passwords();
660
661         if (r < 0)
662                 log_error("Error: %s", strerror(-r));
663
664 finish:
665         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
666 }