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