chiark / gitweb /
systemctl: shutdown agent explicitly so that it can reset the tty properly
[elogind.git] / src / ask-password-api.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 <termios.h>
23 #include <unistd.h>
24 #include <sys/poll.h>
25 #include <sys/inotify.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <sys/socket.h>
29 #include <string.h>
30 #include <sys/un.h>
31 #include <stddef.h>
32 #include <sys/signalfd.h>
33
34 #include "util.h"
35 #include "strv.h"
36
37 #include "ask-password-api.h"
38
39 int ask_password_tty(
40                 const char *message,
41                 usec_t until,
42                 const char *flag_file,
43                 char **_passphrase) {
44
45         struct termios old_termios, new_termios;
46         char passphrase[LINE_MAX];
47         size_t p = 0;
48         int r, ttyfd = -1, notify = -1;
49         struct pollfd pollfd[2];
50         bool reset_tty = false;
51         enum {
52                 POLL_TTY,
53                 POLL_INOTIFY
54         };
55
56         assert(message);
57         assert(_passphrase);
58
59         if (flag_file) {
60                 if ((notify = inotify_init1(IN_CLOEXEC|IN_NONBLOCK)) < 0) {
61                         r = -errno;
62                         goto finish;
63                 }
64
65                 if (inotify_add_watch(notify, flag_file, IN_ATTRIB /* for the link count */) < 0) {
66                         r = -errno;
67                         goto finish;
68                 }
69         }
70
71         if ((ttyfd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC)) >= 0) {
72
73                 if (tcgetattr(ttyfd, &old_termios) < 0) {
74                         r = -errno;
75                         goto finish;
76                 }
77
78                 loop_write(ttyfd, "\x1B[1m", 4, false);
79                 loop_write(ttyfd, message, strlen(message), false);
80                 loop_write(ttyfd, " ", 1, false);
81                 loop_write(ttyfd, "\x1B[0m", 4, false);
82
83                 new_termios = old_termios;
84                 new_termios.c_lflag &= ~(ICANON|ECHO);
85                 new_termios.c_cc[VMIN] = 1;
86                 new_termios.c_cc[VTIME] = 0;
87
88                 if (tcsetattr(ttyfd, TCSADRAIN, &new_termios) < 0) {
89                         r = -errno;
90                         goto finish;
91                 }
92
93                 reset_tty = true;
94         }
95
96         zero(pollfd);
97
98         pollfd[POLL_TTY].fd = ttyfd >= 0 ? ttyfd : STDIN_FILENO;
99         pollfd[POLL_TTY].events = POLLIN;
100         pollfd[POLL_INOTIFY].fd = notify;
101         pollfd[POLL_INOTIFY].events = POLLIN;
102
103         for (;;) {
104                 char c;
105                 int sleep_for = -1, k;
106                 ssize_t n;
107
108                 if (until > 0) {
109                         usec_t y;
110
111                         y = now(CLOCK_MONOTONIC);
112
113                         if (y > until) {
114                                 r = -ETIME;
115                                 goto finish;
116                         }
117
118                         sleep_for = (int) ((until - y) / USEC_PER_MSEC);
119                 }
120
121                 if (flag_file)
122                         if (access(flag_file, F_OK) < 0) {
123                                 r = -errno;
124                                 goto finish;
125                         }
126
127                 if ((k = poll(pollfd, notify > 0 ? 2 : 1, sleep_for)) < 0) {
128
129                         if (errno == EINTR)
130                                 continue;
131
132                         r = -errno;
133                         goto finish;
134                 } else if (k == 0) {
135                         r = -ETIME;
136                         goto finish;
137                 }
138
139                 if (notify > 0 && pollfd[POLL_INOTIFY].revents != 0)
140                         flush_fd(notify);
141
142                 if (pollfd[POLL_TTY].revents == 0)
143                         continue;
144
145                 if ((n = read(ttyfd >= 0 ? ttyfd : STDIN_FILENO, &c, 1)) < 0) {
146
147                         if (errno == EINTR || errno == EAGAIN)
148                                 continue;
149
150                         r = -errno;
151                         goto finish;
152
153                 } else if (n == 0)
154                         break;
155
156                 if (c == '\n')
157                         break;
158                 else if (c == 21) {
159
160                         while (p > 0) {
161                                 p--;
162
163                                 if (ttyfd >= 0)
164                                         loop_write(ttyfd, "\b \b", 3, false);
165                         }
166
167                 } else if (c == '\b' || c == 127) {
168                         if (p > 0) {
169                                 p--;
170
171                                 if (ttyfd >= 0)
172                                         loop_write(ttyfd, "\b \b", 3, false);
173                         }
174                 } else {
175                         passphrase[p++] = c;
176
177                         if (ttyfd >= 0)
178                                 loop_write(ttyfd, "*", 1, false);
179                 }
180         }
181
182         if (ttyfd >= 0)
183
184         passphrase[p] = 0;
185
186         if (!(*_passphrase = strdup(passphrase))) {
187                 r = -ENOMEM;
188                 goto finish;
189         }
190
191         r = 0;
192
193 finish:
194         if (notify >= 0)
195                 close_nointr_nofail(notify);
196
197         if (ttyfd >= 0) {
198
199                 if (reset_tty) {
200                         loop_write(ttyfd, "\n", 1, false);
201                         tcsetattr(ttyfd, TCSADRAIN, &old_termios);
202                 }
203
204                 close_nointr_nofail(ttyfd);
205         }
206
207         return r;
208 }
209
210 static int create_socket(char **name) {
211         int fd;
212         union {
213                 struct sockaddr sa;
214                 struct sockaddr_un un;
215         } sa;
216         int one = 1, r;
217         char *c;
218
219         assert(name);
220
221         if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
222                 log_error("socket() failed: %m");
223                 return -errno;
224         }
225
226         zero(sa);
227         sa.un.sun_family = AF_UNIX;
228         snprintf(sa.un.sun_path, sizeof(sa.un.sun_path)-1, "/dev/.systemd/ask-password/sck.%llu", random_ull());
229
230         if (bind(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(sa.un.sun_path)) < 0) {
231                 r = -errno;
232                 log_error("bind() failed: %m");
233                 goto fail;
234         }
235
236         if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0) {
237                 r = -errno;
238                 log_error("SO_PASSCRED failed: %m");
239                 goto fail;
240         }
241
242         if (!(c = strdup(sa.un.sun_path))) {
243                 r = -ENOMEM;
244                 log_error("Out of memory");
245                 goto fail;
246         }
247
248         *name = c;
249         return fd;
250
251 fail:
252         close_nointr_nofail(fd);
253
254         return r;
255 }
256
257 int ask_password_agent(
258                 const char *message,
259                 const char *icon,
260                 usec_t until,
261                 bool accept_cached,
262                 char ***_passphrases) {
263
264         enum {
265                 FD_SOCKET,
266                 FD_SIGNAL,
267                 _FD_MAX
268         };
269
270         char temp[] = "/dev/.systemd/ask-password/tmp.XXXXXX";
271         char final[sizeof(temp)] = "";
272         int fd = -1, r;
273         FILE *f = NULL;
274         char *socket_name = NULL;
275         int socket_fd = -1, signal_fd = -1;
276         sigset_t mask;
277         struct pollfd pollfd[_FD_MAX];
278
279         assert(_passphrases);
280
281         mkdir_p("/dev/.systemd/ask-password", 0755);
282
283         if ((fd = mkostemp(temp, O_CLOEXEC|O_CREAT|O_WRONLY)) < 0) {
284                 log_error("Failed to create password file: %m");
285                 r = -errno;
286                 goto finish;
287         }
288
289         fchmod(fd, 0644);
290
291         if (!(f = fdopen(fd, "w"))) {
292                 log_error("Failed to allocate FILE: %m");
293                 r = -errno;
294                 goto finish;
295         }
296
297         fd = -1;
298
299         assert_se(sigemptyset(&mask) == 0);
300         sigset_add_many(&mask, SIGINT, SIGTERM, -1);
301         assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
302
303         if ((signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
304                 log_error("signalfd(): %m");
305                 r = -errno;
306                 goto finish;
307         }
308
309         if ((socket_fd = create_socket(&socket_name)) < 0) {
310                 r = socket_fd;
311                 goto finish;
312         }
313
314         fprintf(f,
315                 "[Ask]\n"
316                 "PID=%lu\n"
317                 "Socket=%s\n"
318                 "AcceptCached=%i\n"
319                 "NotAfter=%llu\n",
320                 (unsigned long) getpid(),
321                 socket_name,
322                 accept_cached ? 1 : 0,
323                 (unsigned long long) until);
324
325         if (message)
326                 fprintf(f, "Message=%s\n", message);
327
328         if (icon)
329                 fprintf(f, "Icon=%s\n", icon);
330
331         fflush(f);
332
333         if (ferror(f)) {
334                 log_error("Failed to write query file: %m");
335                 r = -errno;
336                 goto finish;
337         }
338
339         memcpy(final, temp, sizeof(temp));
340
341         final[sizeof(final)-11] = 'a';
342         final[sizeof(final)-10] = 's';
343         final[sizeof(final)-9] = 'k';
344
345         if (rename(temp, final) < 0) {
346                 log_error("Failed to rename query file: %m");
347                 r = -errno;
348                 goto finish;
349         }
350
351         zero(pollfd);
352         pollfd[FD_SOCKET].fd = socket_fd;
353         pollfd[FD_SOCKET].events = POLLIN;
354         pollfd[FD_SIGNAL].fd = signal_fd;
355         pollfd[FD_SIGNAL].events = POLLIN;
356
357         for (;;) {
358                 char passphrase[LINE_MAX+1];
359                 struct msghdr msghdr;
360                 struct iovec iovec;
361                 struct ucred *ucred;
362                 union {
363                         struct cmsghdr cmsghdr;
364                         uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
365                 } control;
366                 ssize_t n;
367                 int k;
368                 usec_t t;
369
370                 t = now(CLOCK_MONOTONIC);
371
372                 if (until <= t) {
373                         log_notice("Timed out");
374                         r = -ETIME;
375                         goto finish;
376                 }
377
378                 if ((k = poll(pollfd, _FD_MAX, (until-t)/USEC_PER_MSEC)) < 0) {
379
380                         if (errno == EINTR)
381                                 continue;
382
383                         log_error("poll() failed: %m");
384                         r = -errno;
385                         goto finish;
386                 }
387
388                 if (k <= 0) {
389                         log_notice("Timed out");
390                         r = -ETIME;
391                         goto finish;
392                 }
393
394                 if (pollfd[FD_SIGNAL].revents & POLLIN) {
395                         r = -EINTR;
396                         goto finish;
397                 }
398
399                 if (pollfd[FD_SOCKET].revents != POLLIN) {
400                         log_error("Unexpected poll() event.");
401                         r = -EIO;
402                         goto finish;
403                 }
404
405                 zero(iovec);
406                 iovec.iov_base = passphrase;
407                 iovec.iov_len = sizeof(passphrase);
408
409                 zero(control);
410                 zero(msghdr);
411                 msghdr.msg_iov = &iovec;
412                 msghdr.msg_iovlen = 1;
413                 msghdr.msg_control = &control;
414                 msghdr.msg_controllen = sizeof(control);
415
416                 if ((n = recvmsg(socket_fd, &msghdr, 0)) < 0) {
417
418                         if (errno == EAGAIN ||
419                             errno == EINTR)
420                                 continue;
421
422                         log_error("recvmsg() failed: %m");
423                         r = -errno;
424                         goto finish;
425                 }
426
427                 if (n <= 0) {
428                         log_error("Message too short");
429                         continue;
430                 }
431
432                 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
433                     control.cmsghdr.cmsg_level != SOL_SOCKET ||
434                     control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
435                     control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
436                         log_warning("Received message without credentials. Ignoring.");
437                         continue;
438                 }
439
440                 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
441                 if (ucred->uid != 0) {
442                         log_warning("Got request from unprivileged user. Ignoring.");
443                         continue;
444                 }
445
446                 if (passphrase[0] == '+') {
447                         char **l;
448
449                         if (!(l = strv_parse_nulstr(passphrase+1, n-1))) {
450                                 r = -ENOMEM;
451                                 goto finish;
452                         }
453
454                         if (strv_length(l) <= 0) {
455                                 strv_free(l);
456                                 log_error("Invalid packet");
457                                 continue;
458                         }
459
460                         *_passphrases = l;
461
462                 } else if (passphrase[0] == '-') {
463                         r = -ECANCELED;
464                         goto finish;
465                 } else {
466                         log_error("Invalid packet");
467                         continue;
468                 }
469
470                 break;
471         }
472
473         r = 0;
474
475 finish:
476         if (fd >= 0)
477                 close_nointr_nofail(fd);
478
479         if (socket_name) {
480                 unlink(socket_name);
481                 free(socket_name);
482         }
483
484         if (socket_fd >= 0)
485                 close_nointr_nofail(socket_fd);
486
487         if (signal_fd >= 0)
488                 close_nointr_nofail(signal_fd);
489
490         if (f)
491                 fclose(f);
492
493         unlink(temp);
494
495         if (final[0])
496                 unlink(final);
497
498         return r;
499 }
500
501 int ask_password_auto(const char *message, const char *icon, usec_t until, bool accept_cached, char ***_passphrases) {
502         assert(message);
503         assert(_passphrases);
504
505         if (isatty(STDIN_FILENO)) {
506                 int r;
507                 char *s = NULL, **l = NULL;
508
509                 if ((r = ask_password_tty(message, until, NULL, &s)) < 0)
510                         return r;
511
512                 l = strv_new(s, NULL);
513                 free(s);
514
515                 if (!l)
516                         return -ENOMEM;
517
518                 *_passphrases = l;
519                 return r;
520
521         } else
522                 return ask_password_agent(message, icon, until, accept_cached, _passphrases);
523 }