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