chiark / gitweb /
mount: require fsck
[elogind.git] / src / ask-password.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 <sys/socket.h>
23 #include <sys/poll.h>
24 #include <sys/types.h>
25 #include <assert.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <unistd.h>
29 #include <fcntl.h>
30 #include <sys/un.h>
31 #include <sys/stat.h>
32 #include <sys/signalfd.h>
33 #include <getopt.h>
34 #include <termios.h>
35 #include <limits.h>
36 #include <stddef.h>
37
38 #include "log.h"
39 #include "macro.h"
40 #include "util.h"
41
42 static const char *arg_icon = NULL;
43 static const char *arg_message = NULL;
44 static bool arg_use_tty = true;
45 static usec_t arg_timeout = 60 * USEC_PER_SEC;
46
47 static int create_socket(char **name) {
48         int fd;
49         union {
50                 struct sockaddr sa;
51                 struct sockaddr_un un;
52         } sa;
53         int one = 1, r;
54         char *c;
55
56         assert(name);
57
58         if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
59                 log_error("socket() failed: %m");
60                 return -errno;
61         }
62
63         zero(sa);
64         sa.un.sun_family = AF_UNIX;
65         snprintf(sa.un.sun_path+1, sizeof(sa.un.sun_path)-1, "/org/freedesktop/systemd1/ask-password/%llu", random_ull());
66
67         if (bind(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1)) < 0) {
68                 r = -errno;
69                 log_error("bind() failed: %m");
70                 goto fail;
71         }
72
73         if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0) {
74                 r = -errno;
75                 log_error("SO_PASSCRED failed: %m");
76                 goto fail;
77         }
78
79         if (!(c = strdup(sa.un.sun_path+1))) {
80                 r = -ENOMEM;
81                 log_error("Out of memory");
82                 goto fail;
83         }
84
85         *name = c;
86         return fd;
87
88 fail:
89         close_nointr_nofail(fd);
90
91         return r;
92 }
93
94 static int help(void) {
95
96         printf("%s [OPTIONS...] MESSAGE\n\n"
97                "Query the user for a system passphrase, via the TTY or an UI agent.\n\n"
98                "  -h --help         Show this help\n"
99                "     --icon=NAME    Icon name\n"
100                "     --timeout=USEC Timeout in usec\n"
101                "     --no-tty       Ask question via agent even on TTY\n",
102                program_invocation_short_name);
103
104         return 0;
105 }
106
107 static int parse_argv(int argc, char *argv[]) {
108
109         enum {
110                 ARG_ICON = 0x100,
111                 ARG_TIMEOUT,
112                 ARG_NO_TTY
113         };
114
115         static const struct option options[] = {
116                 { "help",      no_argument,       NULL, 'h'         },
117                 { "icon",      required_argument, NULL, ARG_ICON    },
118                 { "timeout",   required_argument, NULL, ARG_TIMEOUT },
119                 { "no-tty",    no_argument,       NULL, ARG_NO_TTY  },
120                 { NULL,        0,                 NULL, 0           }
121         };
122
123         int c;
124
125         assert(argc >= 0);
126         assert(argv);
127
128         while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
129
130                 switch (c) {
131
132                 case 'h':
133                         help();
134                         return 0;
135
136                 case ARG_ICON:
137                         arg_icon = optarg;
138                         break;
139
140                 case ARG_TIMEOUT:
141                         if (parse_usec(optarg, &arg_timeout) < 0 || arg_timeout <= 0) {
142                                 log_error("Failed to parse --timeout parameter %s", optarg);
143                                 return -EINVAL;
144                         }
145                         break;
146
147                 case ARG_NO_TTY:
148                         arg_use_tty = false;
149                         break;
150
151                 case '?':
152                         return -EINVAL;
153
154                 default:
155                         log_error("Unknown option code %c", c);
156                         return -EINVAL;
157                 }
158         }
159
160         if (optind != argc-1) {
161                 help();
162                 return -EINVAL;
163         }
164
165         arg_message = argv[optind];
166         return 1;
167 }
168
169 static int ask_agent(void) {
170         char temp[] = "/dev/.systemd/ask-password/tmp.XXXXXX";
171         char final[sizeof(temp)] = "";
172         int fd = -1, r;
173         FILE *f = NULL;
174         char *socket_name = NULL;
175         int socket_fd = -1, signal_fd;
176         sigset_t mask;
177         usec_t not_after;
178
179         if ((fd = mkostemp(temp, O_CLOEXEC|O_CREAT|O_WRONLY)) < 0) {
180                 log_error("Failed to create password file: %m");
181                 r = -errno;
182                 goto finish;
183         }
184
185         fchmod(fd, 0644);
186
187         if (!(f = fdopen(fd, "w"))) {
188                 log_error("Failed to allocate FILE: %m");
189                 r = -errno;
190                 goto finish;
191         }
192
193         fd = -1;
194
195         assert_se(sigemptyset(&mask) == 0);
196         sigset_add_many(&mask, SIGINT, SIGTERM, -1);
197         assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
198
199         if ((signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
200                 log_error("signalfd(): %m");
201                 r = -errno;
202                 goto finish;
203         }
204
205         if ((socket_fd = create_socket(&socket_name)) < 0) {
206                 r = socket_fd;
207                 goto finish;
208         }
209
210         not_after = now(CLOCK_MONOTONIC) + arg_timeout;
211
212         fprintf(f,
213                 "[Ask]\n"
214                 "Socket=%s\n"
215                 "NotAfter=%llu\n",
216                 socket_name,
217                 (unsigned long long) not_after);
218
219         if (arg_message)
220                 fprintf(f, "Message=%s\n", arg_message);
221
222         if (arg_icon)
223                 fprintf(f, "Icon=%s\n", arg_icon);
224
225         fflush(f);
226
227         if (ferror(f)) {
228                 log_error("Failed to write query file: %m");
229                 r = -errno;
230                 goto finish;
231         }
232
233         memcpy(final, temp, sizeof(temp));
234
235         final[sizeof(final)-11] = 'a';
236         final[sizeof(final)-10] = 's';
237         final[sizeof(final)-9] = 'k';
238
239         if (rename(temp, final) < 0) {
240                 log_error("Failed to rename query file: %m");
241                 r = -errno;
242                 goto finish;
243         }
244
245         for (;;) {
246                 enum {
247                         FD_SOCKET,
248                         FD_SIGNAL,
249                         _FD_MAX
250                 };
251
252                 char passphrase[LINE_MAX+1];
253                 struct msghdr msghdr;
254                 struct iovec iovec;
255                 struct ucred *ucred;
256                 union {
257                         struct cmsghdr cmsghdr;
258                         uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
259                 } control;
260                 ssize_t n;
261                 struct pollfd pollfd[_FD_MAX];
262                 int k;
263
264                 zero(pollfd);
265                 pollfd[FD_SOCKET].fd = socket_fd;
266                 pollfd[FD_SOCKET].events = POLLIN;
267                 pollfd[FD_SIGNAL].fd = signal_fd;
268                 pollfd[FD_SIGNAL].events = POLLIN;
269
270                 if ((k = poll(pollfd, 2, arg_timeout/USEC_PER_MSEC)) < 0) {
271
272                         if (errno == EINTR)
273                                 continue;
274
275                         log_error("poll() failed: %m");
276                         r = -errno;
277                         goto finish;
278                 }
279
280                 if (k <= 0) {
281                         log_notice("Timed out");
282                         r = -ETIME;
283                         goto finish;
284                 }
285
286                 if (pollfd[FD_SIGNAL].revents & POLLIN)
287                         break;
288
289                 if (pollfd[FD_SOCKET].revents != POLLIN) {
290                         log_error("Unexpected poll() event.");
291                         r = -EIO;
292                         goto finish;
293                 }
294
295                 zero(iovec);
296                 iovec.iov_base = passphrase;
297                 iovec.iov_len = sizeof(passphrase)-1;
298
299                 zero(control);
300                 zero(msghdr);
301                 msghdr.msg_iov = &iovec;
302                 msghdr.msg_iovlen = 1;
303                 msghdr.msg_control = &control;
304                 msghdr.msg_controllen = sizeof(control);
305
306                 if ((n = recvmsg(socket_fd, &msghdr, 0)) < 0) {
307
308                         if (errno == EAGAIN ||
309                             errno == EINTR)
310                                 continue;
311
312                         log_error("recvmsg() failed: %m");
313                         r = -errno;
314                         goto finish;
315                 }
316
317                 if (n <= 0) {
318                         log_error("Message too short");
319                         continue;
320                 }
321
322                 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
323                     control.cmsghdr.cmsg_level != SOL_SOCKET ||
324                     control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
325                     control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
326                         log_warning("Received message without credentials. Ignoring.");
327                         continue;
328                 }
329
330                 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
331                 if (ucred->uid != 0) {
332                         log_warning("Got request from unprivileged user. Ignoring.");
333                         continue;
334                 }
335
336                 if (passphrase[0] == '+') {
337                         passphrase[n] = 0;
338                         fputs(passphrase+1, stdout);
339                         fflush(stdout);
340                 } else if (passphrase[0] == '-') {
341                         r = -ECANCELED;
342                         goto finish;
343                 } else {
344                         log_error("Invalid packet");
345                         continue;
346                 }
347
348                 break;
349         }
350
351         r = 0;
352
353 finish:
354         if (fd >= 0)
355                 close_nointr_nofail(fd);
356
357         if (socket_fd >= 0)
358                 close_nointr_nofail(socket_fd);
359
360         if (f)
361                 fclose(f);
362
363         unlink(temp);
364
365         if (final[0])
366                 unlink(final);
367
368         return r;
369 }
370
371 static int ask_tty(void) {
372         struct termios old_termios, new_termios;
373         char passphrase[LINE_MAX];
374         FILE *ttyf;
375
376         if (!(ttyf = fopen("/dev/tty", "w"))) {
377                 log_error("Failed to open /dev/tty: %m");
378                 return -errno;
379         }
380
381         fputs("\x1B[1m", ttyf);
382         fprintf(ttyf, "%s: ", arg_message);
383         fputs("\x1B[0m", ttyf);
384         fflush(ttyf);
385
386         if (tcgetattr(STDIN_FILENO, &old_termios) >= 0) {
387
388                 new_termios = old_termios;
389
390                 new_termios.c_lflag &= ~(ICANON|ECHO);
391                 new_termios.c_cc[VMIN] = 1;
392                 new_termios.c_cc[VTIME] = 0;
393
394                 if (tcsetattr(STDIN_FILENO, TCSADRAIN, &new_termios) >= 0) {
395                         size_t p = 0;
396                         int r = 0;
397
398                         for (;;) {
399                                 size_t k;
400                                 char c;
401
402                                 k = fread(&c, 1, 1, stdin);
403
404                                 if (k <= 0) {
405                                         r = -EIO;
406                                         break;
407                                 }
408
409                                 if (c == '\n')
410                                         break;
411                                 else if (c == '\b' || c == 127) {
412                                         if (p > 0) {
413                                                 p--;
414                                                 fputs("\b \b", ttyf);
415                                         }
416                                 } else {
417                                         passphrase[p++] = c;
418                                         fputc('*', ttyf);
419                                 }
420
421                                 fflush(ttyf);
422                         }
423
424                         fputc('\n', ttyf);
425                         fclose(ttyf);
426                         tcsetattr(STDIN_FILENO, TCSADRAIN, &old_termios);
427
428                         if (r < 0)
429                                 return -EIO;
430
431                         passphrase[p] = 0;
432
433                         fputs(passphrase, stdout);
434                         fflush(stdout);
435                         return 0;
436                 }
437
438         }
439
440         fclose(ttyf);
441
442         if (!fgets(passphrase, sizeof(passphrase), stdin)) {
443                 log_error("Failed to read password.");
444                 return -EIO;
445         }
446
447         truncate_nl(passphrase);
448         fputs(passphrase, stdout);
449         fflush(stdout);
450
451         return 0;
452 }
453
454 int main(int argc, char *argv[]) {
455         int r;
456
457         log_parse_environment();
458         log_open();
459
460         if ((r = parse_argv(argc, argv)) <= 0)
461                 goto finish;
462
463         if (arg_use_tty && isatty(STDIN_FILENO))
464                 r = ask_tty();
465         else
466                 r = ask_agent();
467
468 finish:
469         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
470 }