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