5 * (c) 2012 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Yet Another Ident Daemon (YAID).
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.
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.
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.
27 /*----- Header files ------------------------------------------------------*/
31 /*----- Data structures ---------------------------------------------------*/
33 /* A write buffer is the gadget which keeps track of our output and writes
34 * portions of it out as and when connections are ready for it.
38 size_t o; /* Offset of remaining data */
39 size_t n; /* Length of remaining data */
40 sel_file wr; /* Write selector */
41 void (*func)(int /*err*/, void *); /* Function to call on completion */
42 void *p; /* Context for `func' */
43 unsigned char buf[WRBUFSZ]; /* Output buffer */
46 /* Structure for a listening socket. There's one of these for each address
47 * family we're looking after.
50 const struct addrops *ao; /* Address family operations */
51 sel_file f; /* Watch for incoming connections */
54 /* The main structure for a client. */
56 int fd; /* The connection to the client */
57 selbuf b; /* Accumulate lines of input */
58 struct query q; /* The clients query and our reply */
59 struct sel_timer t; /* Timeout for idle or doomed conn */
60 struct listen *l; /* Back to the listener (and ops) */
61 struct writebuf wb; /* Write buffer for our reply */
62 struct proxy *px; /* Proxy if conn goes via NAT */
65 /* A proxy connection. */
67 int fd; /* Connection; -1 if in progress */
68 struct client *c; /* Back to the client */
69 conn cn; /* Nonblocking connection */
70 selbuf b; /* Accumulate the response line */
71 struct writebuf wb; /* Write buffer for query */
72 char nat[ADDRLEN]; /* Server address, as text */
75 /*----- Static variables --------------------------------------------------*/
77 static sel_state sel; /* I/O multiplexer state */
79 static const struct policy default_policy = POLICY_INIT(A_NAME);
80 static policy_v policy = DA_INIT; /* Vector of global policy rules */
81 static fwatch polfw; /* Watch policy file for changes */
83 static unsigned char tokenbuf[4096]; /* Random-ish data for tokens */
84 static size_t tokenptr = sizeof(tokenbuf); /* Current read position */
85 static int randfd; /* File descriptor for random data */
87 /*----- Ident protocol parsing --------------------------------------------*/
89 /* Advance *PP over whitespace characters. */
90 static void skipws(const char **pp)
91 { while (isspace((unsigned char )**pp)) (*pp)++; }
93 /* Copy a token of no more than N bytes starting at *PP into Q, advancing *PP
96 static int idtoken(const char **pp, char *q, size_t n)
103 if (*p == ':' || *p <= 32 || *p >= 127) break;
113 /* Read an unsigned decimal number from *PP, and store it in *II. Check that
114 * it's between MIN and MAX, and advance *PP over it. Return zero for
115 * success, or nonzero if something goes wrong.
117 static int unum(const char **pp, unsigned *ii, unsigned min, unsigned max)
124 if (!isdigit((unsigned char)**pp)) return (-1);
125 e = errno; errno = 0;
126 i = strtoul(*pp, &q, 10);
127 if (errno) return (-1);
130 if (i < min || i > max) return (-1);
135 /*----- Asynchronous writing ----------------------------------------------*/
137 /* Callback for actually writing stuff from a `writebuf'. */
138 static void write_out(int fd, unsigned mode, void *p)
141 struct writebuf *wb = p;
143 /* Try to write something. */
144 if ((n = write(fd, wb->buf + wb->o, wb->n)) < 0) {
145 if (errno == EAGAIN || errno == EWOULDBLOCK) return;
148 wb->func(errno, wb->p);
153 /* If there's nothing left then restore the buffer to its empty state. */
161 /* Queue N bytes starting at P to be written. */
162 static int queue_write(struct writebuf *wb, const void *p, size_t n)
164 /* Maybe there's nothing to actually do. */
167 /* Make sure it'll fit. */
168 if (wb->n - wb->o + n > WRBUFSZ) return (-1);
170 /* If there's anything there already, then make sure it's at the start of
171 * the available space.
174 memmove(wb->buf, wb->buf + wb->o, wb->n);
178 /* If there's nothing currently there, then we're not requesting write
179 * notifications, so set that up, and force an initial wake-up.
182 sel_addfile(&wb->wr);
186 /* Copy the new material over. */
187 memcpy(wb->buf + wb->n, p, n);
194 /* Release resources allocated to WB. */
195 static void free_writebuf(struct writebuf *wb)
196 { if (wb->n) sel_rmfile(&wb->wr); }
198 /* Initialize a writebuf in *WB, writing to file descriptor FD. On
199 * completion, call FUNC, passing it P and an error indicator: either 0 for
200 * success or an `errno' value on failure.
202 static void init_writebuf(struct writebuf *wb,
203 int fd, void (*func)(int, void *), void *p)
205 sel_initfile(&sel, &wb->wr, fd, SEL_WRITE, write_out, wb);
211 /*----- General utilities -------------------------------------------------*/
213 /* Format and log MSG somewhere sensible, at the syslog(3) priority PRIO.
214 * Prefix it with a description of the query Q, if non-null.
216 void logmsg(const struct query *q, int prio, const char *msg, ...)
223 dputsock(&d, q->ao, &q->s[L]);
224 dstr_puts(&d, " <-> ");
225 dputsock(&d, q->ao, &q->s[R]);
228 dstr_vputf(&d, msg, &ap);
230 fprintf(stderr, "yaid: %s\n", d.buf);
234 /* Fix up a socket FD so that it won't bite us. Returns zero on success, or
237 static int fix_up_socket(int fd, const char *what)
241 if (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)) {
242 logmsg(0, LOG_ERR, "failed to set %s connection nonblocking: %s",
243 what, strerror(errno));
247 if (setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &yes, sizeof(yes))) {
249 "failed to disable `out-of-band' data on %s connection: %s",
250 what, strerror(errno));
257 /*----- Client output functions -------------------------------------------*/
259 static void disconnect_client(struct client *c);
261 /* Notification that output has been written. If successful, re-enable the
262 * input buffer and prepare for another query.
264 static void done_client_write(int err, void *p)
266 struct client *c = p;
269 selbuf_enable(&c->b);
271 logmsg(&c->q, LOG_ERR, "failed to send reply: %s", strerror(err));
272 disconnect_client(c);
276 /* Format the message FMT and queue it to be sent to the client. Client
277 * input will be disabled until the write completes.
279 static void write_to_client(struct client *c, const char *fmt, ...)
286 n = vsnprintf(buf, sizeof(buf), fmt, ap);
288 logmsg(&c->q, LOG_ERR, "failed to format output: %s", strerror(errno));
289 disconnect_client(c);
291 } else if (n > sizeof(buf)) {
292 logmsg(&c->q, LOG_ERR, "output too long for client send buffer");
293 disconnect_client(c);
297 selbuf_disable(&c->b);
298 if (queue_write(&c->wb, buf, n)) {
299 logmsg(&c->q, LOG_ERR, "write buffer overflow");
300 disconnect_client(c);
304 /* Format a reply to the client, with the form LPORT:RPORT:TY:TOK0[:TOK1].
305 * Typically, TY will be `ERROR' or `USERID'. In the former case, TOK0 will
306 * be the error token and TOK1 will be null; in the latter case, TOK0 will be
307 * the operating system and TOK1 the user name.
309 static void reply(struct client *c, const char *ty,
310 const char *tok0, const char *tok1)
312 write_to_client(c, "%u,%u:%s:%s%s%s\r\n",
313 c->q.s[L].port, c->q.s[R].port, ty,
314 tok0, tok1 ? ":" : "", tok1 ? tok1 : "");
317 /* Mapping from error codes to their protocol tokens. */
318 const char *const errtok[] = {
319 #define DEFTOK(err, tok) tok,
324 /* Report an error with code ERR to the client. */
325 static void reply_error(struct client *c, unsigned err)
327 assert(err < E_LIMIT);
328 reply(c, "ERROR", errtok[err], 0);
331 /*----- NAT proxy functions -----------------------------------------------*/
333 /* Cancel the proxy operation PX, closing the connection and releasing
334 * resources. This is used for both normal and unexpected closures.
336 static void cancel_proxy(struct proxy *px)
342 selbuf_destroy(&px->b);
343 free_writebuf(&px->wb);
345 selbuf_enable(&px->c->b);
350 /* Notification that a line (presumably a reply) has been received from the
351 * server. We should check it, log it, and propagate the answer back.
352 * Whatever happens, this proxy operation is now complete.
354 static void proxy_line(char *line, size_t sz, void *p)
356 struct proxy *px = p;
358 const char *q = line;
361 /* Trim trailing space. */
362 while (sz && isspace((unsigned char)line[sz - 1])) sz--;
364 /* Parse the port numbers. These should match the request. */
365 if (unum(&q, &lp, 1, 65535)) goto syntax;
366 skipws(&q); if (*q != ',') goto syntax; q++;
367 if (unum(&q, &rp, 1, 65535)) goto syntax;
368 skipws(&q); if (*q != ':') goto syntax; q++;
369 if (lp != px->c->q.u.nat.port || rp != px->c->q.s[R].port) goto syntax;
371 /* Find out what kind of reply this is. */
372 if (idtoken(&q, buf, sizeof(buf))) goto syntax;
373 skipws(&q); if (*q != ':') goto syntax; q++;
375 if (strcmp(buf, "ERROR") == 0) {
377 /* Report the error without interpreting it. It might be meaningful to
381 logmsg(&px->c->q, LOG_ERR, "proxy error from %s: %s", px->nat, q);
382 reply(px->c, "ERROR", q, 0);
384 } else if (strcmp(buf, "USERID") == 0) {
386 /* Parse out the operating system and user name, and pass them on. */
387 if (idtoken(&q, buf, sizeof(buf))) goto syntax;
388 skipws(&q); if (*q != ':') goto syntax; q++;
390 logmsg(&px->c->q, LOG_ERR, "user `%s'; proxy = %s, os = %s",
392 reply(px->c, "USERID", buf, q);
399 /* We didn't understand the message from the client. */
400 logmsg(&px->c->q, LOG_ERR, "failed to parse response from %s", px->nat);
401 reply_error(px->c, E_UNKNOWN);
403 /* All finished, no matter what. */
407 /* Notification that we have written the query to the server. Await a
408 * response if successful.
410 static void done_proxy_write(int err, void *p)
412 struct proxy *px = p;
415 logmsg(&px->c->q, LOG_ERR, "failed to proxy query to %s: %s",
416 px->nat, strerror(errno));
417 reply_error(px->c, E_UNKNOWN);
421 selbuf_enable(&px->b);
424 /* Notification that the connection to the server is either established or
425 * failed. In the former case, queue the right query.
427 static void proxy_connected(int fd, void *p)
429 struct proxy *px = p;
433 /* If the connection failed then report the problem and give up. */
435 logmsg(&px->c->q, LOG_ERR,
436 "failed to make %s proxy connection to %s: %s",
437 px->c->l->ao->name, px->nat, strerror(errno));
438 reply_error(px->c, E_UNKNOWN);
443 /* We're now ready to go, so set things up. */
445 selbuf_init(&px->b, &sel, fd, proxy_line, px);
446 selbuf_setsize(&px->b, 1024);
447 selbuf_disable(&px->b);
448 init_writebuf(&px->wb, fd, done_proxy_write, px);
450 /* Write the query. This buffer is large enough because we've already
451 * range-checked the remote the port number and the local one came from the
452 * kernel, which we trust not to do anything stupid.
454 n = sprintf(buf, "%u,%u\r\n", px->c->q.u.nat.port, px->c->q.s[R].port);
455 queue_write(&px->wb, buf, n);
458 /* Proxy the query through to a client machine for which we're providing NAT
461 static void proxy_query(struct client *c)
464 struct sockaddr_storage ss;
469 /* Allocate the context structure for the NAT. */
470 px = xmalloc(sizeof(*px));
472 /* We'll use the client host's address in lots of log messages, so we may
473 * as well format it once and use it over and over.
475 inet_ntop(c->q.ao->af, &c->q.u.nat.addr, px->nat, sizeof(px->nat));
477 /* Create the socket for the connection. */
478 if ((fd = socket(c->q.ao->af, SOCK_STREAM, 0)) < 0) {
479 logmsg(&c->q, LOG_ERR, "failed to make %s socket for proxy: %s",
480 c->l->ao->name, strerror(errno));
483 if (fix_up_socket(fd, "proxy")) goto err_1;
485 /* Set up the connection to the client host. The connection interface is a
486 * bit broken: if the connection completes immediately, then the callback
487 * function is called synchronously, and that might decide to shut
488 * everything down. So we must have fully initialized our context before
489 * calling `conn_init', and mustn't touch it again afterwards -- since the
490 * block may have been freed.
494 c->l->ao->socket_to_sockaddr(&s, &ss, &ssz);
495 selbuf_disable(&c->b);
496 c->px = px; px->c = c;
498 if (conn_init(&px->cn, &sel, fd, (struct sockaddr *)&ss, ssz,
499 proxy_connected, px)) {
500 logmsg(&c->q, LOG_ERR, "failed to make %s proxy connection to %s: %s",
501 c->l->ao->name, px->nat, strerror(errno));
505 /* All ready to go. */
508 /* Tidy up after various kinds of failures. */
510 selbuf_enable(&c->b);
515 reply_error(c, E_UNKNOWN);
518 /*----- Client connection functions ---------------------------------------*/
520 /* Disconnect a client, freeing up any associated resources. */
521 static void disconnect_client(struct client *c)
524 selbuf_destroy(&c->b);
526 free_writebuf(&c->wb);
527 if (c->px) cancel_proxy(c->px);
531 /* Time out a client because it's been idle for too long. */
532 static void timeout_client(struct timeval *tv, void *p)
534 struct client *c = p;
535 logmsg(&c->q, LOG_NOTICE, "timing out idle or stuck client");
536 sel_addtimer(&sel, &c->t, tv, timeout_client, 0);
537 disconnect_client(c);
540 /* Reset the client idle timer, as a result of activity. Set EXISTP if
541 * there is an existing timer which needs to be removed.
543 static void reset_client_timer(struct client *c, int existp)
547 gettimeofday(&tv, 0);
549 if (existp) sel_rmtimer(&c->t);
550 sel_addtimer(&sel, &c->t, &tv, timeout_client, c);
553 /* Write a pseudorandom token into the buffer at P, which must have space for
554 * at least TOKENSZ bytes.
556 #define TOKENRANDSZ 8
557 #define TOKENSZ ((4*TOKENRANDSZ + 5)/3)
558 static void user_token(char *p)
563 static const char tokmap[64] =
564 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-";
566 /* If there's not enough pseudorandom stuff lying around, then read more
569 if (tokenptr + TOKENRANDSZ >= sizeof(tokenbuf)) {
570 if (read(randfd, tokenbuf, sizeof(tokenbuf)) < sizeof(tokenbuf))
571 die(1, "unexpected short read or error from `/dev/urandom'");
575 /* Now encode the bytes using a slightly tweaked base-64 encoding. Read
576 * bytes into the accumulator and write out characters while there's
579 for (i = 0; i < TOKENRANDSZ; i++) {
580 a = (a << 8) | tokenbuf[tokenptr++]; b += 8;
583 *p++ = tokmap[(a >> b) & 0x3f];
587 /* If there's anything left in the accumulator then flush it out. */
589 *p++ = tokmap[(a << (6 - b)) & 0x3f];
591 /* Null-terminate the token. */
595 /* Notification that a line has been received from the client. Parse it,
596 * find out about the connection it's referring to, apply the relevant
597 * policy rules, and produce a response. This is where almost everything
598 * interesting happens.
600 static void client_line(char *line, size_t len, void *p)
602 struct client *c = p;
604 struct passwd *pw = 0;
605 const struct policy *pol;
607 struct policy upol = POLICY_INIT(A_LIMIT);
608 struct policy_file pf;
612 /* If the connection has closed, then tidy stuff away. */
613 c->q.s[L].port = c->q.s[R].port = 0;
615 disconnect_client(c);
619 /* Client activity, so update the timer. */
620 reset_client_timer(c, 1);
622 /* See if the policy file has changed since we last looked. If so, try to
623 * read the new version.
625 if (fwatch_update(&polfw, "yaid.policy")) {
626 logmsg(0, LOG_INFO, "reload master policy file `%s'", "yaid.policy");
627 load_policy_file("yaid.policy", &policy);
630 /* Read the local and remote port numbers into the query structure. */
632 if (unum(&q, &c->q.s[L].port, 1, 65535)) goto bad;
633 skipws(&q); if (*q != ',') goto bad; q++;
634 if (unum(&q, &c->q.s[R].port, 1, 65535)) goto bad;
635 skipws(&q); if (*q) goto bad;
637 /* Identify the connection. Act on the result. */
642 /* We found a user. Track down the user's password entry, because
643 * we'll want that later. Most of the processing for this case is
646 if ((pw = getpwuid(c->q.u.uid)) == 0) {
647 logmsg(&c->q, LOG_ERR, "no passwd entry for user %d", c->q.u.uid);
648 reply_error(c, E_NOUSER);
654 /* We've acted as a NAT for this connection. Proxy the query through
655 * to the actal client host.
661 /* We failed to identify the connection for some reason. We should
662 * already have logged an error, so there's not much to do here.
664 reply_error(c, c->q.u.error);
668 /* Something happened that we don't understand. */
672 /* Search the table of policy rules to find a match. */
673 for (i = 0; i < DA_LEN(&policy); i++) {
674 pol = &DA(&policy)[i];
675 if (!match_policy(pol, &c->q)) continue;
677 /* If this is something simple, then apply the resulting policy rule. */
678 if (pol->act.act != A_USER) goto match;
680 /* The global policy has decided to let the user have a say, so we must
681 * parse the user file.
684 dstr_putf(&d, "%s/.yaid.policy", pw->pw_dir);
685 if (open_policy_file(&pf, d.buf, "user policy file", &c->q))
687 while (!read_policy_file(&pf)) {
689 /* Give up after 100 lines. If the user's policy is that complicated,
690 * something's gone very wrong. Or there's too much commentary or
694 logmsg(&c->q, LOG_ERR, "%s:%d: user policy file too long",
699 /* If this isn't a match, go around for the next rule. */
700 if (!match_policy(&pf.p, &c->q)) continue;
702 /* Check that the user is allowed to request this action. If not, see
703 * if there's a more acceptable action later on.
705 if (!(pol->act.u.user & (1 << pf.p.act.act))) {
706 logmsg(&c->q, LOG_ERR,
707 "%s:%d: user action forbidden by global policy",
712 /* We've found a match, so grab it, close the file, and say we're
715 upol = pf.p; pol = &upol;
717 close_policy_file(&pf);
721 close_policy_file(&pf);
725 /* No match: apply the built-in default policy. */
726 pol = &default_policy;
729 switch (pol->act.act) {
732 /* Report the actual user's name. */
733 logmsg(&c->q, LOG_INFO, "user `%s' (%d)", pw->pw_name, c->q.u.uid);
734 reply(c, "USERID", "UNIX", pw->pw_name);
738 /* Report an arbitrary token which we can look up in our log file. */
740 logmsg(&c->q, LOG_INFO, "user `%s' (%d); token = %s",
741 pw->pw_name, c->q.u.uid, buf);
742 reply(c, "USERID", "OTHER", buf);
746 /* Deny that there's anyone there at all. */
747 logmsg(&c->q, LOG_INFO, "user `%s' (%d); denying",
748 pw->pw_name, c->q.u.uid);
752 /* Report the user as being hidden. */
753 logmsg(&c->q, LOG_INFO, "user `%s' (%d); hiding",
754 pw->pw_name, c->q.u.uid);
755 reply_error(c, E_HIDDEN);
759 /* Tell an egregious lie about who the user is. */
760 logmsg(&c->q, LOG_INFO, "user `%s' (%d); lie = `%s'",
761 pw->pw_name, c->q.u.uid, pol->act.u.lie);
762 reply(c, "USERID", "UNIX", pol->act.u.lie);
766 /* Something has gone very wrong. */
775 logmsg(&c->q, LOG_ERR, "failed to parse query from client");
776 disconnect_client(c);
779 /* Notification that a new client has connected. Prepare to read a query. */
780 static void accept_client(int fd, unsigned mode, void *p)
782 struct listen *l = p;
784 struct sockaddr_storage ssr, ssl;
785 size_t ssz = sizeof(ssr);
788 /* Accept the new connection. */
789 if ((sk = accept(fd, (struct sockaddr *)&ssr, &ssz)) < 0) {
790 if (errno != EAGAIN && errno == EWOULDBLOCK) {
791 logmsg(0, LOG_ERR, "failed to accept incoming %s connection: %s",
792 l->ao->name, strerror(errno));
796 if (fix_up_socket(sk, "incoming client")) { close(sk); return; }
798 /* Build a client block and fill it in. */
799 c = xmalloc(sizeof(*c));
803 /* Collect the local and remote addresses. */
804 l->ao->sockaddr_to_addr(&ssr, &c->q.s[R].addr);
806 if (getsockname(sk, (struct sockaddr *)&ssl, &ssz)) {
808 "failed to read local address for incoming %s connection: %s",
809 l->ao->name, strerror(errno));
814 l->ao->sockaddr_to_addr(&ssl, &c->q.s[L].addr);
815 c->q.s[L].port = c->q.s[R].port = 0;
817 /* Set stuff up for reading the query and sending responses. */
818 selbuf_init(&c->b, &sel, sk, client_line, c);
819 selbuf_setsize(&c->b, 1024);
820 reset_client_timer(c, 0);
823 init_writebuf(&c->wb, sk, done_client_write, c);
826 /*----- Main code ---------------------------------------------------------*/
828 /* Set up a listening socket for the address family described by AO,
831 static int make_listening_socket(const struct addrops *ao, int port)
836 struct sockaddr_storage ss;
840 /* Make the socket. */
841 if ((fd = socket(ao->af, SOCK_STREAM, 0)) < 0) {
842 if (errno == EAFNOSUPPORT) return (-1);
843 die(1, "failed to create %s listening socket: %s",
844 ao->name, strerror(errno));
847 /* Build the appropriate local address. */
850 ao->socket_to_sockaddr(&s, &ss, &ssz);
852 /* Perform any initialization specific to the address type. */
853 if (ao->init_listen_socket(fd)) {
854 die(1, "failed to initialize %s listening socket: %s",
855 ao->name, strerror(errno));
858 /* Bind to the address. */
859 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
860 if (bind(fd, (struct sockaddr *)&ss, ssz)) {
861 die(1, "failed to bind %s listening socket: %s",
862 ao->name, strerror(errno));
865 /* Avoid unpleasant race conditions. */
866 if (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)) {
867 die(1, "failed to set %s listening socket nonblocking: %s",
868 ao->name, strerror(errno));
871 /* Prepare to listen. */
873 die(1, "failed to listen for %s: %s", ao->name, strerror(errno));
875 /* Make a record of all of this. */
876 l = xmalloc(sizeof(*l));
878 sel_initfile(&sel, &l->f, fd, SEL_READ, accept_client, l);
885 int main(int argc, char *argv[])
888 const struct addrops *ao;
893 fwatch_init(&polfw, "yaid.policy");
895 if (load_policy_file("yaid.policy", &policy))
898 for (i = 0; i < DA_LEN(&policy); i++)
899 print_policy(&DA(&policy)[i]);
902 if ((randfd = open("/dev/urandom", O_RDONLY)) < 0) {
903 die(1, "failed to open `/dev/urandom' for reading: %s",
908 for (ao = addroptab; ao->name; ao++)
909 if (!make_listening_socket(ao, port)) any = 1;
911 die(1, "no IP protocols supported");
914 if (sel_select(&sel)) die(1, "select failed: %s", strerror(errno));
919 /*----- That's all, folks -------------------------------------------------*/