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