yaid.c: Don't fail if either IPv4 or IPv6 is unavailable.
[yaid] / yaid.c
1 /* -*-c-*-
2 *
3 * Main daemon
4 *
5 * (c) 2012 Straylight/Edgeware
6 */
7
8 /*----- Licensing notice --------------------------------------------------*
9 *
10 * This file is part of Yet Another Ident Daemon (YAID).
11 *
12 * YAID is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
16 *
17 * YAID is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with YAID; if not, write to the Free Software Foundation,
24 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25 */
26
27 /*----- Header files ------------------------------------------------------*/
28
29 #include "yaid.h"
30
31 /*----- Data structures ---------------------------------------------------*/
32
33 struct listen {
34 int af;
35 const char *proto;
36 sel_file f;
37 };
38
39 #define WRBUFSZ 1024
40 struct writebuf {
41 size_t o, n;
42 sel_file wr;
43 void (*func)(int, void *);
44 void *p;
45 unsigned char buf[WRBUFSZ];
46 };
47
48 struct proxy {
49 struct client *c;
50 int fd;
51 conn cn;
52 selbuf b;
53 struct writebuf wb;
54 char nat[ADDRLEN];
55 };
56
57 struct client {
58 selbuf b;
59 int fd;
60 struct query q;
61 struct listen *l;
62 struct writebuf wb;
63 struct proxy *px;
64 };
65
66 /*----- Static variables --------------------------------------------------*/
67
68 static sel_state sel;
69
70 static policy_v policy = DA_INIT;
71 static fwatch polfw;
72
73 static unsigned char tokenbuf[4096];
74 static size_t tokenptr = sizeof(tokenbuf);
75 static int randfd;
76
77 /*----- Main code ---------------------------------------------------------*/
78
79 static void socket_to_sockaddr(int af, const struct socket *s,
80 struct sockaddr *sa, size_t *ssz)
81 {
82 sa->sa_family = af;
83 switch (af) {
84 case AF_INET: {
85 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
86 sin->sin_addr = s->addr.ipv4;
87 sin->sin_port = htons(s->port);
88 *ssz = sizeof(*sin);
89 } break;
90 case AF_INET6: {
91 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
92 sin6->sin6_addr = s->addr.ipv6;
93 sin6->sin6_port = htons(s->port);
94 sin6->sin6_flowinfo = 0;
95 sin6->sin6_scope_id = 0;
96 *ssz = sizeof(*sin6);
97 } break;
98 default: abort();
99 }
100 }
101
102 static void sockaddr_to_addr(const struct sockaddr *sa, union addr *a)
103 {
104 switch (sa->sa_family) {
105 case AF_INET: a->ipv4 = ((struct sockaddr_in *)sa)->sin_addr; break;
106 case AF_INET6: a->ipv6 = ((struct sockaddr_in6 *)sa)->sin6_addr; break;
107 default: abort();
108 }
109 }
110
111 static void dputsock(dstr *d, int af, const struct socket *s)
112 {
113 char buf[ADDRLEN];
114
115 inet_ntop(af, &s->addr, buf, sizeof(buf));
116 if (!s->port || af != AF_INET6) dstr_puts(d, buf);
117 else { dstr_putc(d, '['); dstr_puts(d, buf); dstr_putc(d, ']'); }
118 if (s->port) dstr_putf(d, ":%d", s->port);
119 }
120
121 void logmsg(const struct query *q, int prio, const char *msg, ...)
122 {
123 va_list ap;
124 dstr d = DSTR_INIT;
125
126 va_start(ap, msg);
127 if (q) {
128 dputsock(&d, q->af, &q->s[L]);
129 dstr_puts(&d, " <-> ");
130 dputsock(&d, q->af, &q->s[R]);
131 dstr_puts(&d, ": ");
132 }
133 dstr_vputf(&d, msg, &ap);
134 va_end(ap);
135 fprintf(stderr, "yaid: %s\n", d.buf);
136 dstr_destroy(&d);
137 }
138
139 static void write_out(int fd, unsigned mode, void *p)
140 {
141 ssize_t n;
142 struct writebuf *wb = p;
143
144 if ((n = write(fd, wb->buf + wb->o, wb->n)) < 0) {
145 if (errno == EAGAIN || errno == EWOULDBLOCK) return;
146 wb->n = 0;
147 sel_rmfile(&wb->wr);
148 wb->func(errno, wb->p);
149 }
150 wb->o += n;
151 wb->n -= n;
152 if (!wb->n) {
153 wb->o = 0;
154 sel_rmfile(&wb->wr);
155 wb->func(0, wb->p);
156 }
157 }
158
159 static int queue_write(struct writebuf *wb, const void *p, size_t n)
160 {
161 if (!n) return (0);
162 if (wb->n - wb->o + n > WRBUFSZ) return (-1);
163 if (wb->o) {
164 memmove(wb->buf, wb->buf + wb->o, wb->n);
165 wb->o = 0;
166 }
167 memcpy(wb->buf + wb->n, p, n);
168 if (!wb->n) {
169 sel_addfile(&wb->wr);
170 sel_force(&wb->wr);
171 }
172 wb->n += n;
173 return (0);
174 }
175
176 static void free_writebuf(struct writebuf *wb)
177 { if (wb->n) sel_rmfile(&wb->wr); }
178
179 static void init_writebuf(struct writebuf *wb,
180 int fd, void (*func)(int, void *), void *p)
181 {
182 sel_initfile(&sel, &wb->wr, fd, SEL_WRITE, write_out, wb);
183 wb->func = func;
184 wb->p = p;
185 wb->n = wb->o = 0;
186 }
187
188 static void cancel_proxy(struct proxy *px)
189 {
190 if (px->fd == -1)
191 conn_kill(&px->cn);
192 else {
193 close(px->fd);
194 selbuf_destroy(&px->b);
195 free_writebuf(&px->wb);
196 }
197 selbuf_enable(&px->c->b);
198 px->c->px = 0;
199 xfree(px);
200 }
201
202 static void disconnect_client(struct client *c)
203 {
204 close(c->fd);
205 selbuf_destroy(&c->b);
206 free_writebuf(&c->wb);
207 if (c->px) cancel_proxy(c->px);
208 xfree(c);
209 }
210
211 static void done_client_write(int err, void *p)
212 {
213 struct client *c = p;
214
215 if (!err)
216 selbuf_enable(&c->b);
217 else {
218 logmsg(&c->q, LOG_ERR, "failed to send reply: %s", strerror(err));
219 disconnect_client(c);
220 }
221 }
222
223 static void write_to_client(struct client *c, const char *fmt, ...)
224 {
225 va_list ap;
226 char buf[WRBUFSZ];
227 ssize_t n;
228
229 va_start(ap, fmt);
230 n = vsnprintf(buf, sizeof(buf), fmt, ap);
231 if (n < 0) {
232 logmsg(&c->q, LOG_ERR, "failed to format output: %s", strerror(errno));
233 disconnect_client(c);
234 return;
235 } else if (n > sizeof(buf)) {
236 logmsg(&c->q, LOG_ERR, "output too long for client send buffer");
237 disconnect_client(c);
238 return;
239 }
240
241 selbuf_disable(&c->b);
242 if (queue_write(&c->wb, buf, n)) {
243 logmsg(&c->q, LOG_ERR, "write buffer overflow");
244 disconnect_client(c);
245 }
246 }
247
248 static void reply(struct client *c, const char *ty, const char *msg)
249 {
250 write_to_client(c, "%u,%u:%s:%s\r\n",
251 c->q.s[L].port, c->q.s[R].port, ty, msg);
252 }
253
254 static void reply_error(struct client *c, unsigned err)
255 {
256 assert(err < E_LIMIT);
257 reply(c, "ERROR", errtok[err]);
258 }
259
260 static void skipws(const char **pp)
261 { while (isspace((unsigned char )**pp)) (*pp)++; }
262
263 static int idtoken(const char **pp, char *q, size_t n)
264 {
265 const char *p = *pp;
266
267 skipws(&p);
268 n--;
269 for (;;) {
270 if (*p == ':' || *p <= 32 || *p >= 127) break;
271 if (!n) return (-1);
272 *q++ = *p++;
273 n--;
274 }
275 *q++ = 0;
276 *pp = p;
277 return (0);
278 }
279
280 static int unum(const char **pp, unsigned *ii, unsigned min, unsigned max)
281 {
282 char *q;
283 unsigned long i;
284 int e;
285
286 skipws(pp);
287 if (!isdigit((unsigned char)**pp)) return (-1);
288 e = errno; errno = 0;
289 i = strtoul(*pp, &q, 10);
290 if (errno) return (-1);
291 *pp = q;
292 errno = e;
293 if (i < min || i > max) return (-1);
294 *ii = i;
295 return (0);
296 }
297
298 static void proxy_line(char *line, size_t sz, void *p)
299 {
300 struct proxy *px = p;
301 char buf[1024];
302 const char *q = line;
303 unsigned lp, rp;
304
305 while (sz && isspace((unsigned char)line[sz - 1])) sz--;
306 printf("received proxy line from %s: %s\n", px->nat, line);
307
308 if (unum(&q, &lp, 1, 65535)) goto syntax;
309 skipws(&q); if (*q != ',') goto syntax; q++;
310 if (unum(&q, &rp, 1, 65535)) goto syntax;
311 skipws(&q); if (*q != ':') goto syntax; q++;
312 if (lp != px->c->q.u.nat.port || rp != px->c->q.s[R].port) goto syntax;
313 if (idtoken(&q, buf, sizeof(buf))) goto syntax;
314 skipws(&q); if (*q != ':') goto syntax; q++;
315 if (strcmp(buf, "ERROR") == 0) {
316 skipws(&q);
317 logmsg(&px->c->q, LOG_ERR, "proxy error from %s: %s", px->nat, q);
318 reply(px->c, "ERROR", q);
319 } else if (strcmp(buf, "USERID") == 0) {
320 if (idtoken(&q, buf, sizeof(buf))) goto syntax;
321 skipws(&q); if (*q != ':') goto syntax; q++;
322 skipws(&q);
323 logmsg(&px->c->q, LOG_ERR, "user `%s'; proxy = %s, os = %s",
324 q, px->nat, buf);
325 write_to_client(px->c, "%u,%u:USERID:%s:%s\r\n",
326 px->c->q.s[L].port, px->c->q.s[R].port, buf, q);
327 } else
328 goto syntax;
329 goto done;
330
331 syntax:
332 logmsg(&px->c->q, LOG_ERR, "failed to parse response from %s", px->nat);
333 reply_error(px->c, E_UNKNOWN);
334 done:
335 cancel_proxy(px);
336 }
337
338 static void done_proxy_write(int err, void *p)
339 {
340 struct proxy *px = p;
341
342 if (err) {
343 logmsg(&px->c->q, LOG_ERR, "failed to proxy query to %s: %s",
344 px->nat, strerror(errno));
345 reply_error(px->c, E_UNKNOWN);
346 cancel_proxy(px);
347 return;
348 }
349 selbuf_enable(&px->b);
350 }
351
352 static void proxy_connected(int fd, void *p)
353 {
354 struct proxy *px = p;
355 char buf[16];
356 int n;
357
358 if (fd < 0) {
359 logmsg(&px->c->q, LOG_ERR,
360 "failed to make %s proxy connection to %s: %s",
361 px->c->l->proto, px->nat, strerror(errno));
362 reply_error(px->c, E_UNKNOWN);
363 cancel_proxy(px);
364 return;
365 }
366
367 px->fd = fd;
368 selbuf_init(&px->b, &sel, fd, proxy_line, px);
369 selbuf_setsize(&px->b, 1024);
370 selbuf_disable(&px->b);
371 init_writebuf(&px->wb, fd, done_proxy_write, px);
372
373 n = sprintf(buf, "%u,%u\r\n", px->c->q.u.nat.port, px->c->q.s[R].port);
374 queue_write(&px->wb, buf, n);
375 }
376
377 static void proxy_query(struct client *c)
378 {
379 struct socket s;
380 struct sockaddr_storage ss;
381 size_t ssz;
382 struct proxy *px;
383 int o;
384 int fd;
385
386 px = xmalloc(sizeof(*px));
387 inet_ntop(c->q.af, &c->q.u.nat.addr, px->nat, sizeof(px->nat));
388
389 if ((fd = socket(c->q.af, SOCK_STREAM, 0)) < 0) {
390 logmsg(&c->q, LOG_ERR, "failed to make %s socket for proxy: %s",
391 c->l->proto, strerror(errno));
392 goto err_0;
393 }
394
395 if ((o = fcntl(fd, F_GETFL)) < 0 ||
396 fcntl(fd, F_SETFL, o | O_NONBLOCK)) {
397 logmsg(&c->q, LOG_ERR, "failed to set %s proxy socket nonblocking: %s",
398 c->l->proto, strerror(errno));
399 goto err_1;
400 }
401
402 s = c->q.u.nat;
403 s.port = 113;
404 socket_to_sockaddr(c->q.af, &s, (struct sockaddr *)&ss, &ssz);
405 selbuf_disable(&c->b);
406 if (conn_init(&px->cn, &sel, fd, (struct sockaddr *)&ss, ssz,
407 proxy_connected, px)) {
408 logmsg(&c->q, LOG_ERR, "failed to make %s proxy connection to %s: %s",
409 c->l->proto, px->nat, strerror(errno));
410 goto err_2;
411 }
412
413 c->px = px; px->c = c;
414 px->fd = -1;
415 return;
416
417 err_2:
418 selbuf_enable(&c->b);
419 err_1:
420 close(px->fd);
421 err_0:
422 xfree(px);
423 reply_error(c, E_UNKNOWN);
424 }
425
426 static const struct policy default_policy = POLICY_INIT(A_NAME);
427
428 static void user_token(char *p)
429 {
430 static const char tokmap[64] =
431 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-";
432 unsigned a = 0;
433 unsigned b = 0;
434 int i;
435 #define TOKENSZ 8
436
437 if (tokenptr + TOKENSZ >= sizeof(tokenbuf)) {
438 if (read(randfd, tokenbuf, sizeof(tokenbuf)) < sizeof(tokenbuf))
439 die(1, "unexpected short read or error from `/dev/urandom'");
440 tokenptr = 0;
441 }
442
443 for (i = 0; i < TOKENSZ; i++) {
444 a = (a << 8) | tokenbuf[tokenptr++]; b += 8;
445 while (b >= 6) {
446 b -= 6;
447 *p++ = tokmap[(a >> b) & 0x3f];
448 }
449 }
450 if (b)
451 *p++ = tokmap[(a << (6 - b)) & 0x3f];
452 *p++ = 0;
453 }
454
455 static void client_line(char *line, size_t len, void *p)
456 {
457 struct client *c = p;
458 const char *q;
459 struct passwd *pw = 0;
460 const struct policy *pol;
461 dstr d = DSTR_INIT;
462 struct policy upol = POLICY_INIT(A_LIMIT);
463 struct policy_file pf;
464 char buf[16];
465 int i;
466
467 c->q.s[L].port = c->q.s[R].port = 0;
468 if (!line) {
469 disconnect_client(c);
470 return;
471 }
472
473 if (fwatch_update(&polfw, "yaid.policy")) {
474 logmsg(0, LOG_INFO, "reload master policy file `%s'", "yaid.policy");
475 load_policy_file("yaid.policy", &policy);
476 }
477
478 q = line;
479 if (unum(&q, &c->q.s[L].port, 1, 65535)) goto bad;
480 skipws(&q); if (*q != ',') goto bad; q++;
481 if (unum(&q, &c->q.s[R].port, 1, 65535)) goto bad;
482 skipws(&q); if (*q) goto bad;
483
484 identify(&c->q);
485 switch (c->q.resp) {
486 case R_UID:
487 if ((pw = getpwuid(c->q.u.uid)) == 0) {
488 logmsg(&c->q, LOG_ERR, "no passwd entry for user %d", c->q.u.uid);
489 reply_error(c, E_NOUSER);
490 return;
491 }
492 break;
493 case R_NAT:
494 proxy_query(c);
495 return;
496 case R_ERROR:
497 /* Should already be logged. */
498 reply_error(c, c->q.u.error);
499 return;
500 default:
501 abort();
502 }
503
504 for (i = 0; i < DA_LEN(&policy); i++) {
505 pol = &DA(&policy)[i];
506 if (!match_policy(pol, &c->q)) continue;
507 if (pol->act.act != A_USER)
508 goto match;
509 DRESET(&d);
510 dstr_putf(&d, "%s/.yaid.policy", pw->pw_dir);
511 if (open_policy_file(&pf, d.buf, "user policy file", &c->q))
512 continue;
513 while (!read_policy_file(&pf)) {
514 if (pf.lno > 100) {
515 logmsg(&c->q, LOG_ERR, "%s:%d: user policy file too long",
516 pf.name, pf.lno);
517 break;
518 }
519 if (!match_policy(&pf.p, &c->q)) continue;
520 if (!(pol->act.u.user & (1 << pf.p.act.act))) {
521 logmsg(&c->q, LOG_ERR,
522 "%s:%d: user action forbidden by global policy",
523 pf.name, pf.lno);
524 continue;
525 }
526 upol = pf.p; pol = &upol;
527 init_policy(&pf.p);
528 close_policy_file(&pf);
529 goto match;
530 }
531 close_policy_file(&pf);
532 }
533 pol = &default_policy;
534
535 match:
536 DDESTROY(&d);
537 switch (pol->act.act) {
538 case A_NAME:
539 logmsg(&c->q, LOG_INFO, "user `%s' (%d)", pw->pw_name, c->q.u.uid);
540 reply(c, "USERID:UNIX", pw->pw_name);
541 break;
542 case A_TOKEN:
543 user_token(buf);
544 logmsg(&c->q, LOG_INFO, "user `%s' (%d); token = %s",
545 pw->pw_name, c->q.u.uid, buf);
546 reply(c, "USERID:OTHER", buf);
547 break;
548 case A_DENY:
549 logmsg(&c->q, LOG_INFO, "user `%s' (%d); denying",
550 pw->pw_name, c->q.u.uid);
551 break;
552 case A_HIDE:
553 logmsg(&c->q, LOG_INFO, "user `%s' (%d); hiding",
554 pw->pw_name, c->q.u.uid);
555 reply_error(c, E_HIDDEN);
556 break;
557 case A_LIE:
558 logmsg(&c->q, LOG_INFO, "user `%s' (%d); lie = `%s'",
559 pw->pw_name, c->q.u.uid, pol->act.u.lie);
560 reply(c, "USERID:UNIX", pol->act.u.lie);
561 break;
562 default:
563 abort();
564 }
565
566 free_policy(&upol);
567 return;
568
569 bad:
570 logmsg(&c->q, LOG_ERR, "failed to parse query from client");
571 disconnect_client(c);
572 }
573
574 static void accept_client(int fd, unsigned mode, void *p)
575 {
576 struct listen *l = p;
577 struct client *c;
578 struct sockaddr_storage ssr, ssl;
579 size_t ssz = sizeof(ssr);
580 int sk;
581
582 if ((sk = accept(fd, (struct sockaddr *)&ssr, &ssz)) < 0) {
583 if (errno != EAGAIN && errno == EWOULDBLOCK) {
584 logmsg(0, LOG_ERR, "failed to accept incoming %s connection: %s",
585 l->proto, strerror(errno));
586 }
587 return;
588 }
589
590 c = xmalloc(sizeof(*c));
591 c->l = l;
592 c->q.af = l->af;
593 sockaddr_to_addr((struct sockaddr *)&ssr, &c->q.s[R].addr);
594 ssz = sizeof(ssl);
595 if (getsockname(sk, (struct sockaddr *)&ssl, &ssz)) {
596 logmsg(0, LOG_ERR,
597 "failed to read local address for incoming %s connection: %s",
598 l->proto, strerror(errno));
599 close(sk);
600 xfree(c);
601 return;
602 }
603 sockaddr_to_addr((struct sockaddr *)&ssl, &c->q.s[L].addr);
604 c->q.s[L].port = c->q.s[R].port = 0;
605
606 /* logmsg(&c->q, LOG_INFO, "accepted %s connection", l->proto); */
607
608 selbuf_init(&c->b, &sel, sk, client_line, c);
609 selbuf_setsize(&c->b, 1024);
610 c->fd = sk;
611 c->px = 0;
612 init_writebuf(&c->wb, sk, done_client_write, c);
613 }
614
615 static int make_listening_socket(int af, int port, const char *proto)
616 {
617 int fd;
618 int o;
619 struct sockaddr_storage ss;
620 struct listen *l;
621 size_t ssz;
622
623 if ((fd = socket(af, SOCK_STREAM, 0)) < 0) {
624 if (errno == EAFNOSUPPORT) return (-1);
625 die(1, "failed to create %s listening socket: %s",
626 proto, strerror(errno));
627 }
628 o = 1; setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &o, sizeof(o));
629 ss.ss_family = af;
630 switch (af) {
631 case AF_INET: {
632 struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
633 sin->sin_addr.s_addr = INADDR_ANY;
634 sin->sin_port = htons(port);
635 ssz = sizeof(*sin);
636 } break;
637 case AF_INET6: {
638 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
639 o = 1; setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &o, sizeof(o));
640 sin6->sin6_family = AF_INET6;
641 sin6->sin6_addr = in6addr_any;
642 sin6->sin6_scope_id = 0;
643 sin6->sin6_flowinfo = 0;
644 ssz = sizeof(*sin6);
645 } break;
646 default:
647 abort();
648 }
649 if (bind(fd, (struct sockaddr *)&ss, ssz))
650 die(1, "failed to bind %s listening socket: %s", proto, strerror(errno));
651 if ((o = fcntl(fd, F_GETFL)) < 0 ||
652 fcntl(fd, F_SETFL, o | O_NONBLOCK)) {
653 die(1, "failed to set %s listening socket nonblocking: %s",
654 proto, strerror(errno));
655 }
656 if (listen(fd, 5))
657 die(1, "failed to listen for %s: %s", proto, strerror(errno));
658
659 l = xmalloc(sizeof(*l));
660 l->af = af;
661 l->proto = proto;
662 sel_initfile(&sel, &l->f, fd, SEL_READ, accept_client, l);
663 sel_addfile(&l->f);
664
665 return (0);
666 }
667
668 int main(int argc, char *argv[])
669 {
670 int port = 113;
671 char buf[ADDRLEN];
672 union addr a;
673
674 ego(argv[0]);
675
676 fwatch_init(&polfw, "yaid.policy");
677 if (load_policy_file("yaid.policy", &policy))
678 exit(1);
679 { int i;
680 for (i = 0; i < DA_LEN(&policy); i++)
681 print_policy(&DA(&policy)[i]);
682 }
683
684 if ((randfd = open("/dev/urandom", O_RDONLY)) < 0) {
685 die(1, "failed to open `/dev/urandom' for reading: %s",
686 strerror(errno));
687 }
688
689 if (get_default_gw(AF_INET, &a))
690 printf("ipv4 gw = %s\n", inet_ntop(AF_INET, &a, buf, sizeof(buf)));
691 if (get_default_gw(AF_INET6, &a))
692 printf("ipv6 gw = %s\n", inet_ntop(AF_INET6, &a, buf, sizeof(buf)));
693
694 sel_init(&sel);
695 if (make_listening_socket(AF_INET, port, "IPv4") &&
696 make_listening_socket(AF_INET6, port, "IPv6"))
697 die(1, "no IP protocols supported");
698
699 for (;;)
700 if (sel_select(&sel)) die(1, "select failed: %s", strerror(errno));
701
702 return (0);
703 }
704
705 /*----- That's all, folks -------------------------------------------------*/