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