chiark / gitweb /
ask-password: add basic tty agent
[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, sizeof(sa.un.sun_path)-1, "/dev/.systemd/ask-password/sck.%llu", random_ull());
66
67         if (bind(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(sa.un.sun_path)) < 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))) {
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=SEC Timeout in sec\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         mkdir_p("/dev/.systemd/ask-password", 0755);
180
181         if ((fd = mkostemp(temp, O_CLOEXEC|O_CREAT|O_WRONLY)) < 0) {
182                 log_error("Failed to create password file: %m");
183                 r = -errno;
184                 goto finish;
185         }
186
187         fchmod(fd, 0644);
188
189         if (!(f = fdopen(fd, "w"))) {
190                 log_error("Failed to allocate FILE: %m");
191                 r = -errno;
192                 goto finish;
193         }
194
195         fd = -1;
196
197         assert_se(sigemptyset(&mask) == 0);
198         sigset_add_many(&mask, SIGINT, SIGTERM, -1);
199         assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
200
201         if ((signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
202                 log_error("signalfd(): %m");
203                 r = -errno;
204                 goto finish;
205         }
206
207         if ((socket_fd = create_socket(&socket_name)) < 0) {
208                 r = socket_fd;
209                 goto finish;
210         }
211
212         not_after = now(CLOCK_MONOTONIC) + arg_timeout;
213
214         fprintf(f,
215                 "[Ask]\n"
216                 "PID=%lu\n"
217                 "Socket=%s\n"
218                 "NotAfter=%llu\n",
219                 (unsigned long) getpid(),
220                 socket_name,
221                 (unsigned long long) not_after);
222
223         if (arg_message)
224                 fprintf(f, "Message=%s\n", arg_message);
225
226         if (arg_icon)
227                 fprintf(f, "Icon=%s\n", arg_icon);
228
229         fflush(f);
230
231         if (ferror(f)) {
232                 log_error("Failed to write query file: %m");
233                 r = -errno;
234                 goto finish;
235         }
236
237         memcpy(final, temp, sizeof(temp));
238
239         final[sizeof(final)-11] = 'a';
240         final[sizeof(final)-10] = 's';
241         final[sizeof(final)-9] = 'k';
242
243         if (rename(temp, final) < 0) {
244                 log_error("Failed to rename query file: %m");
245                 r = -errno;
246                 goto finish;
247         }
248
249         for (;;) {
250                 enum {
251                         FD_SOCKET,
252                         FD_SIGNAL,
253                         _FD_MAX
254                 };
255
256                 char passphrase[LINE_MAX+1];
257                 struct msghdr msghdr;
258                 struct iovec iovec;
259                 struct ucred *ucred;
260                 union {
261                         struct cmsghdr cmsghdr;
262                         uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
263                 } control;
264                 ssize_t n;
265                 struct pollfd pollfd[_FD_MAX];
266                 int k;
267
268                 zero(pollfd);
269                 pollfd[FD_SOCKET].fd = socket_fd;
270                 pollfd[FD_SOCKET].events = POLLIN;
271                 pollfd[FD_SIGNAL].fd = signal_fd;
272                 pollfd[FD_SIGNAL].events = POLLIN;
273
274                 if ((k = poll(pollfd, 2, arg_timeout/USEC_PER_MSEC)) < 0) {
275
276                         if (errno == EINTR)
277                                 continue;
278
279                         log_error("poll() failed: %m");
280                         r = -errno;
281                         goto finish;
282                 }
283
284                 if (k <= 0) {
285                         log_notice("Timed out");
286                         r = -ETIME;
287                         goto finish;
288                 }
289
290                 if (pollfd[FD_SIGNAL].revents & POLLIN)
291                         break;
292
293                 if (pollfd[FD_SOCKET].revents != POLLIN) {
294                         log_error("Unexpected poll() event.");
295                         r = -EIO;
296                         goto finish;
297                 }
298
299                 zero(iovec);
300                 iovec.iov_base = passphrase;
301                 iovec.iov_len = sizeof(passphrase)-1;
302
303                 zero(control);
304                 zero(msghdr);
305                 msghdr.msg_iov = &iovec;
306                 msghdr.msg_iovlen = 1;
307                 msghdr.msg_control = &control;
308                 msghdr.msg_controllen = sizeof(control);
309
310                 if ((n = recvmsg(socket_fd, &msghdr, 0)) < 0) {
311
312                         if (errno == EAGAIN ||
313                             errno == EINTR)
314                                 continue;
315
316                         log_error("recvmsg() failed: %m");
317                         r = -errno;
318                         goto finish;
319                 }
320
321                 if (n <= 0) {
322                         log_error("Message too short");
323                         continue;
324                 }
325
326                 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
327                     control.cmsghdr.cmsg_level != SOL_SOCKET ||
328                     control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
329                     control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
330                         log_warning("Received message without credentials. Ignoring.");
331                         continue;
332                 }
333
334                 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
335                 if (ucred->uid != 0) {
336                         log_warning("Got request from unprivileged user. Ignoring.");
337                         continue;
338                 }
339
340                 if (passphrase[0] == '+') {
341                         passphrase[n] = 0;
342                         fputs(passphrase+1, stdout);
343                         fflush(stdout);
344                 } else if (passphrase[0] == '-') {
345                         r = -ECANCELED;
346                         goto finish;
347                 } else {
348                         log_error("Invalid packet");
349                         continue;
350                 }
351
352                 break;
353         }
354
355         r = 0;
356
357 finish:
358         if (fd >= 0)
359                 close_nointr_nofail(fd);
360
361         if (socket_name) {
362                 unlink(socket_name);
363                 free(socket_name);
364         }
365
366         if (socket_fd >= 0)
367                 close_nointr_nofail(socket_fd);
368
369         if (f)
370                 fclose(f);
371
372         unlink(temp);
373
374         if (final[0])
375                 unlink(final);
376
377         return r;
378 }
379
380 int main(int argc, char *argv[]) {
381         int r;
382
383         log_parse_environment();
384         log_open();
385
386         if ((r = parse_argv(argc, argv)) <= 0)
387                 goto finish;
388
389         if (arg_use_tty && isatty(STDIN_FILENO)) {
390                 char *password = NULL;
391
392                 if ((r = ask_password_tty(arg_message, now(CLOCK_MONOTONIC) + arg_timeout, NULL, &password)) >= 0) {
393                         fputs(password, stdout);
394                         fflush(stdout);
395                         free(password);
396                 }
397
398         } else
399                 r = ask_agent();
400
401 finish:
402         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
403 }