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 listen *l; /* Back to the listener (and ops) */
60 struct writebuf wb; /* Write buffer for our reply */
61 struct proxy *px; /* Proxy if conn goes via NAT */
64 /* A proxy connection. */
66 int fd; /* Connection; -1 if in progress */
67 struct client *c; /* Back to the client */
68 conn cn; /* Nonblocking connection */
69 selbuf b; /* Accumulate the response line */
70 struct writebuf wb; /* Write buffer for query */
71 char nat[ADDRLEN]; /* Server address, as text */
74 /*----- Static variables --------------------------------------------------*/
76 static sel_state sel; /* I/O multiplexer state */
78 static const struct policy default_policy = POLICY_INIT(A_NAME);
79 static policy_v policy = DA_INIT; /* Vector of global policy rules */
80 static fwatch polfw; /* Watch policy file for changes */
82 static unsigned char tokenbuf[4096]; /* Random-ish data for tokens */
83 static size_t tokenptr = sizeof(tokenbuf); /* Current read position */
84 static int randfd; /* File descriptor for random data */
86 /*----- Ident protocol parsing --------------------------------------------*/
88 /* Advance *PP over whitespace characters. */
89 static void skipws(const char **pp)
90 { while (isspace((unsigned char )**pp)) (*pp)++; }
92 /* Copy a token of no more than N bytes starting at *PP into Q, advancing *PP
95 static int idtoken(const char **pp, char *q, size_t n)
102 if (*p == ':' || *p <= 32 || *p >= 127) break;
112 /* Read an unsigned decimal number from *PP, and store it in *II. Check that
113 * it's between MIN and MAX, and advance *PP over it. Return zero for
114 * success, or nonzero if something goes wrong.
116 static int unum(const char **pp, unsigned *ii, unsigned min, unsigned max)
123 if (!isdigit((unsigned char)**pp)) return (-1);
124 e = errno; errno = 0;
125 i = strtoul(*pp, &q, 10);
126 if (errno) return (-1);
129 if (i < min || i > max) return (-1);
134 /*----- Asynchronous writing ----------------------------------------------*/
136 /* Callback for actually writing stuff from a `writebuf'. */
137 static void write_out(int fd, unsigned mode, void *p)
140 struct writebuf *wb = p;
142 /* Try to write something. */
143 if ((n = write(fd, wb->buf + wb->o, wb->n)) < 0) {
144 if (errno == EAGAIN || errno == EWOULDBLOCK) return;
147 wb->func(errno, wb->p);
152 /* If there's nothing left then restore the buffer to its empty state. */
160 /* Queue N bytes starting at P to be written. */
161 static int queue_write(struct writebuf *wb, const void *p, size_t n)
163 /* Maybe there's nothing to actually do. */
166 /* Make sure it'll fit. */
167 if (wb->n - wb->o + n > WRBUFSZ) return (-1);
169 /* If there's anything there already, then make sure it's at the start of
170 * the available space.
173 memmove(wb->buf, wb->buf + wb->o, wb->n);
177 /* If there's nothing currently there, then we're not requesting write
178 * notifications, so set that up, and force an initial wake-up.
181 sel_addfile(&wb->wr);
185 /* Copy the new material over. */
186 memcpy(wb->buf + wb->n, p, n);
193 /* Release resources allocated to WB. */
194 static void free_writebuf(struct writebuf *wb)
195 { if (wb->n) sel_rmfile(&wb->wr); }
197 /* Initialize a writebuf in *WB, writing to file descriptor FD. On
198 * completion, call FUNC, passing it P and an error indicator: either 0 for
199 * success or an `errno' value on failure.
201 static void init_writebuf(struct writebuf *wb,
202 int fd, void (*func)(int, void *), void *p)
204 sel_initfile(&sel, &wb->wr, fd, SEL_WRITE, write_out, wb);
210 /*----- General utilities -------------------------------------------------*/
212 /* Format and log MSG somewhere sensible, at the syslog(3) priority PRIO.
213 * Prefix it with a description of the query Q, if non-null.
215 void logmsg(const struct query *q, int prio, const char *msg, ...)
222 dputsock(&d, q->ao, &q->s[L]);
223 dstr_puts(&d, " <-> ");
224 dputsock(&d, q->ao, &q->s[R]);
227 dstr_vputf(&d, msg, &ap);
229 fprintf(stderr, "yaid: %s\n", d.buf);
233 /* Fix up a socket FD so that it won't bite us. Returns zero on success, or
236 static int fix_up_socket(int fd, const char *what)
240 if (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)) {
241 logmsg(0, LOG_ERR, "failed to set %s connection nonblocking: %s",
242 what, strerror(errno));
246 if (setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &yes, sizeof(yes))) {
248 "failed to disable `out-of-band' data on %s connection: %s",
249 what, strerror(errno));
256 /*----- Client output functions -------------------------------------------*/
258 static void disconnect_client(struct client *c);
260 /* Notification that output has been written. If successful, re-enable the
261 * input buffer and prepare for another query.
263 static void done_client_write(int err, void *p)
265 struct client *c = p;
268 selbuf_enable(&c->b);
270 logmsg(&c->q, LOG_ERR, "failed to send reply: %s", strerror(err));
271 disconnect_client(c);
275 /* Format the message FMT and queue it to be sent to the client. Client
276 * input will be disabled until the write completes.
278 static void write_to_client(struct client *c, const char *fmt, ...)
285 n = vsnprintf(buf, sizeof(buf), fmt, ap);
287 logmsg(&c->q, LOG_ERR, "failed to format output: %s", strerror(errno));
288 disconnect_client(c);
290 } else if (n > sizeof(buf)) {
291 logmsg(&c->q, LOG_ERR, "output too long for client send buffer");
292 disconnect_client(c);
296 selbuf_disable(&c->b);
297 if (queue_write(&c->wb, buf, n)) {
298 logmsg(&c->q, LOG_ERR, "write buffer overflow");
299 disconnect_client(c);
303 /* Format a reply to the client, with the form LPORT:RPORT:TY:TOK0[:TOK1].
304 * Typically, TY will be `ERROR' or `USERID'. In the former case, TOK0 will
305 * be the error token and TOK1 will be null; in the latter case, TOK0 will be
306 * the operating system and TOK1 the user name.
308 static void reply(struct client *c, const char *ty,
309 const char *tok0, const char *tok1)
311 write_to_client(c, "%u,%u:%s:%s%s%s\r\n",
312 c->q.s[L].port, c->q.s[R].port, ty,
313 tok0, tok1 ? ":" : "", tok1 ? tok1 : "");
316 /* Mapping from error codes to their protocol tokens. */
317 const char *const errtok[] = {
318 #define DEFTOK(err, tok) tok,
323 /* Report an error with code ERR to the client. */
324 static void reply_error(struct client *c, unsigned err)
326 assert(err < E_LIMIT);
327 reply(c, "ERROR", errtok[err], 0);
330 /*----- NAT proxy functions -----------------------------------------------*/
332 /* Cancel the proxy operation PX, closing the connection and releasing
333 * resources. This is used for both normal and unexpected closures.
335 static void cancel_proxy(struct proxy *px)
341 selbuf_destroy(&px->b);
342 free_writebuf(&px->wb);
344 selbuf_enable(&px->c->b);
349 /* Notification that a line (presumably a reply) has been received from the
350 * server. We should check it, log it, and propagate the answer back.
351 * Whatever happens, this proxy operation is now complete.
353 static void proxy_line(char *line, size_t sz, void *p)
355 struct proxy *px = p;
357 const char *q = line;
360 /* Trim trailing space. */
361 while (sz && isspace((unsigned char)line[sz - 1])) sz--;
363 /* Parse the port numbers. These should match the request. */
364 if (unum(&q, &lp, 1, 65535)) goto syntax;
365 skipws(&q); if (*q != ',') goto syntax; q++;
366 if (unum(&q, &rp, 1, 65535)) goto syntax;
367 skipws(&q); if (*q != ':') goto syntax; q++;
368 if (lp != px->c->q.u.nat.port || rp != px->c->q.s[R].port) goto syntax;
370 /* Find out what kind of reply this is. */
371 if (idtoken(&q, buf, sizeof(buf))) goto syntax;
372 skipws(&q); if (*q != ':') goto syntax; q++;
374 if (strcmp(buf, "ERROR") == 0) {
376 /* Report the error without interpreting it. It might be meaningful to
380 logmsg(&px->c->q, LOG_ERR, "proxy error from %s: %s", px->nat, q);
381 reply(px->c, "ERROR", q, 0);
383 } else if (strcmp(buf, "USERID") == 0) {
385 /* Parse out the operating system and user name, and pass them on. */
386 if (idtoken(&q, buf, sizeof(buf))) goto syntax;
387 skipws(&q); if (*q != ':') goto syntax; q++;
389 logmsg(&px->c->q, LOG_ERR, "user `%s'; proxy = %s, os = %s",
391 reply(px->c, "USERID", buf, q);
398 /* We didn't understand the message from the client. */
399 logmsg(&px->c->q, LOG_ERR, "failed to parse response from %s", px->nat);
400 reply_error(px->c, E_UNKNOWN);
402 /* All finished, no matter what. */
406 /* Notification that we have written the query to the server. Await a
407 * response if successful.
409 static void done_proxy_write(int err, void *p)
411 struct proxy *px = p;
414 logmsg(&px->c->q, LOG_ERR, "failed to proxy query to %s: %s",
415 px->nat, strerror(errno));
416 reply_error(px->c, E_UNKNOWN);
420 selbuf_enable(&px->b);
423 /* Notification that the connection to the server is either established or
424 * failed. In the former case, queue the right query.
426 static void proxy_connected(int fd, void *p)
428 struct proxy *px = p;
432 /* If the connection failed then report the problem and give up. */
434 logmsg(&px->c->q, LOG_ERR,
435 "failed to make %s proxy connection to %s: %s",
436 px->c->l->ao->name, px->nat, strerror(errno));
437 reply_error(px->c, E_UNKNOWN);
442 /* We're now ready to go, so set things up. */
444 selbuf_init(&px->b, &sel, fd, proxy_line, px);
445 selbuf_setsize(&px->b, 1024);
446 selbuf_disable(&px->b);
447 init_writebuf(&px->wb, fd, done_proxy_write, px);
449 /* Write the query. This buffer is large enough because we've already
450 * range-checked the remote the port number and the local one came from the
451 * kernel, which we trust not to do anything stupid.
453 n = sprintf(buf, "%u,%u\r\n", px->c->q.u.nat.port, px->c->q.s[R].port);
454 queue_write(&px->wb, buf, n);
457 /* Proxy the query through to a client machine for which we're providing NAT
460 static void proxy_query(struct client *c)
463 struct sockaddr_storage ss;
468 /* Allocate the context structure for the NAT. */
469 px = xmalloc(sizeof(*px));
471 /* We'll use the client host's address in lots of log messages, so we may
472 * as well format it once and use it over and over.
474 inet_ntop(c->q.ao->af, &c->q.u.nat.addr, px->nat, sizeof(px->nat));
476 /* Create the socket for the connection. */
477 if ((fd = socket(c->q.ao->af, SOCK_STREAM, 0)) < 0) {
478 logmsg(&c->q, LOG_ERR, "failed to make %s socket for proxy: %s",
479 c->l->ao->name, strerror(errno));
482 if (fix_up_socket(fd, "proxy")) goto err_1;
484 /* Set up the connection to the client host. The connection interface is a
485 * bit broken: if the connection completes immediately, then the callback
486 * function is called synchronously, and that might decide to shut
487 * everything down. So we must have fully initialized our context before
488 * calling `conn_init', and mustn't touch it again afterwards -- since the
489 * block may have been freed.
493 c->l->ao->socket_to_sockaddr(&s, &ss, &ssz);
494 selbuf_disable(&c->b);
495 c->px = px; px->c = c;
497 if (conn_init(&px->cn, &sel, fd, (struct sockaddr *)&ss, ssz,
498 proxy_connected, px)) {
499 logmsg(&c->q, LOG_ERR, "failed to make %s proxy connection to %s: %s",
500 c->l->ao->name, px->nat, strerror(errno));
504 /* All ready to go. */
507 /* Tidy up after various kinds of failures. */
509 selbuf_enable(&c->b);
514 reply_error(c, E_UNKNOWN);
517 /*----- Client connection functions ---------------------------------------*/
519 /* Disconnect a client, freeing up any associated resources. */
520 static void disconnect_client(struct client *c)
523 selbuf_destroy(&c->b);
524 free_writebuf(&c->wb);
525 if (c->px) cancel_proxy(c->px);
529 /* Write a pseudorandom token into the buffer at P, which must have space for
530 * at least TOKENSZ bytes.
532 #define TOKENRANDSZ 8
533 #define TOKENSZ ((4*TOKENRANDSZ + 5)/3)
534 static void user_token(char *p)
539 static const char tokmap[64] =
540 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-";
542 /* If there's not enough pseudorandom stuff lying around, then read more
545 if (tokenptr + TOKENRANDSZ >= sizeof(tokenbuf)) {
546 if (read(randfd, tokenbuf, sizeof(tokenbuf)) < sizeof(tokenbuf))
547 die(1, "unexpected short read or error from `/dev/urandom'");
551 /* Now encode the bytes using a slightly tweaked base-64 encoding. Read
552 * bytes into the accumulator and write out characters while there's
555 for (i = 0; i < TOKENRANDSZ; i++) {
556 a = (a << 8) | tokenbuf[tokenptr++]; b += 8;
559 *p++ = tokmap[(a >> b) & 0x3f];
563 /* If there's anything left in the accumulator then flush it out. */
565 *p++ = tokmap[(a << (6 - b)) & 0x3f];
567 /* Null-terminate the token. */
571 /* Notification that a line has been received from the client. Parse it,
572 * find out about the connection it's referring to, apply the relevant
573 * policy rules, and produce a response. This is where almost everything
574 * interesting happens.
576 static void client_line(char *line, size_t len, void *p)
578 struct client *c = p;
580 struct passwd *pw = 0;
581 const struct policy *pol;
583 struct policy upol = POLICY_INIT(A_LIMIT);
584 struct policy_file pf;
588 /* If the connection has closed, then tidy stuff away. */
589 c->q.s[L].port = c->q.s[R].port = 0;
591 disconnect_client(c);
595 /* See if the policy file has changed since we last looked. If so, try to
596 * read the new version.
598 if (fwatch_update(&polfw, "yaid.policy")) {
599 logmsg(0, LOG_INFO, "reload master policy file `%s'", "yaid.policy");
600 load_policy_file("yaid.policy", &policy);
603 /* Read the local and remote port numbers into the query structure. */
605 if (unum(&q, &c->q.s[L].port, 1, 65535)) goto bad;
606 skipws(&q); if (*q != ',') goto bad; q++;
607 if (unum(&q, &c->q.s[R].port, 1, 65535)) goto bad;
608 skipws(&q); if (*q) goto bad;
610 /* Identify the connection. Act on the result. */
615 /* We found a user. Track down the user's password entry, because
616 * we'll want that later. Most of the processing for this case is
619 if ((pw = getpwuid(c->q.u.uid)) == 0) {
620 logmsg(&c->q, LOG_ERR, "no passwd entry for user %d", c->q.u.uid);
621 reply_error(c, E_NOUSER);
627 /* We've acted as a NAT for this connection. Proxy the query through
628 * to the actal client host.
634 /* We failed to identify the connection for some reason. We should
635 * already have logged an error, so there's not much to do here.
637 reply_error(c, c->q.u.error);
641 /* Something happened that we don't understand. */
645 /* Search the table of policy rules to find a match. */
646 for (i = 0; i < DA_LEN(&policy); i++) {
647 pol = &DA(&policy)[i];
648 if (!match_policy(pol, &c->q)) continue;
650 /* If this is something simple, then apply the resulting policy rule. */
651 if (pol->act.act != A_USER) goto match;
653 /* The global policy has decided to let the user have a say, so we must
654 * parse the user file.
657 dstr_putf(&d, "%s/.yaid.policy", pw->pw_dir);
658 if (open_policy_file(&pf, d.buf, "user policy file", &c->q))
660 while (!read_policy_file(&pf)) {
662 /* Give up after 100 lines. If the user's policy is that complicated,
663 * something's gone very wrong. Or there's too much commentary or
667 logmsg(&c->q, LOG_ERR, "%s:%d: user policy file too long",
672 /* If this isn't a match, go around for the next rule. */
673 if (!match_policy(&pf.p, &c->q)) continue;
675 /* Check that the user is allowed to request this action. If not, see
676 * if there's a more acceptable action later on.
678 if (!(pol->act.u.user & (1 << pf.p.act.act))) {
679 logmsg(&c->q, LOG_ERR,
680 "%s:%d: user action forbidden by global policy",
685 /* We've found a match, so grab it, close the file, and say we're
688 upol = pf.p; pol = &upol;
690 close_policy_file(&pf);
694 close_policy_file(&pf);
698 /* No match: apply the built-in default policy. */
699 pol = &default_policy;
702 switch (pol->act.act) {
705 /* Report the actual user's name. */
706 logmsg(&c->q, LOG_INFO, "user `%s' (%d)", pw->pw_name, c->q.u.uid);
707 reply(c, "USERID", "UNIX", pw->pw_name);
711 /* Report an arbitrary token which we can look up in our log file. */
713 logmsg(&c->q, LOG_INFO, "user `%s' (%d); token = %s",
714 pw->pw_name, c->q.u.uid, buf);
715 reply(c, "USERID", "OTHER", buf);
719 /* Deny that there's anyone there at all. */
720 logmsg(&c->q, LOG_INFO, "user `%s' (%d); denying",
721 pw->pw_name, c->q.u.uid);
725 /* Report the user as being hidden. */
726 logmsg(&c->q, LOG_INFO, "user `%s' (%d); hiding",
727 pw->pw_name, c->q.u.uid);
728 reply_error(c, E_HIDDEN);
732 /* Tell an egregious lie about who the user is. */
733 logmsg(&c->q, LOG_INFO, "user `%s' (%d); lie = `%s'",
734 pw->pw_name, c->q.u.uid, pol->act.u.lie);
735 reply(c, "USERID", "UNIX", pol->act.u.lie);
739 /* Something has gone very wrong. */
748 logmsg(&c->q, LOG_ERR, "failed to parse query from client");
749 disconnect_client(c);
752 /* Notification that a new client has connected. Prepare to read a query. */
753 static void accept_client(int fd, unsigned mode, void *p)
755 struct listen *l = p;
757 struct sockaddr_storage ssr, ssl;
758 size_t ssz = sizeof(ssr);
761 /* Accept the new connection. */
762 if ((sk = accept(fd, (struct sockaddr *)&ssr, &ssz)) < 0) {
763 if (errno != EAGAIN && errno == EWOULDBLOCK) {
764 logmsg(0, LOG_ERR, "failed to accept incoming %s connection: %s",
765 l->ao->name, strerror(errno));
769 if (fix_up_socket(sk, "incoming client")) { close(sk); return; }
771 /* Build a client block and fill it in. */
772 c = xmalloc(sizeof(*c));
776 /* Collect the local and remote addresses. */
777 l->ao->sockaddr_to_addr(&ssr, &c->q.s[R].addr);
779 if (getsockname(sk, (struct sockaddr *)&ssl, &ssz)) {
781 "failed to read local address for incoming %s connection: %s",
782 l->ao->name, strerror(errno));
787 l->ao->sockaddr_to_addr(&ssl, &c->q.s[L].addr);
788 c->q.s[L].port = c->q.s[R].port = 0;
790 /* Set stuff up for reading the query and sending responses. */
791 selbuf_init(&c->b, &sel, sk, client_line, c);
792 selbuf_setsize(&c->b, 1024);
795 init_writebuf(&c->wb, sk, done_client_write, c);
798 /*----- Main code ---------------------------------------------------------*/
800 /* Set up a listening socket for the address family described by AO,
803 static int make_listening_socket(const struct addrops *ao, int port)
808 struct sockaddr_storage ss;
812 /* Make the socket. */
813 if ((fd = socket(ao->af, SOCK_STREAM, 0)) < 0) {
814 if (errno == EAFNOSUPPORT) return (-1);
815 die(1, "failed to create %s listening socket: %s",
816 ao->name, strerror(errno));
819 /* Build the appropriate local address. */
822 ao->socket_to_sockaddr(&s, &ss, &ssz);
824 /* Perform any initialization specific to the address type. */
825 if (ao->init_listen_socket(fd)) {
826 die(1, "failed to initialize %s listening socket: %s",
827 ao->name, strerror(errno));
830 /* Bind to the address. */
831 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
832 if (bind(fd, (struct sockaddr *)&ss, ssz)) {
833 die(1, "failed to bind %s listening socket: %s",
834 ao->name, strerror(errno));
837 /* Avoid unpleasant race conditions. */
838 if (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)) {
839 die(1, "failed to set %s listening socket nonblocking: %s",
840 ao->name, strerror(errno));
843 /* Prepare to listen. */
845 die(1, "failed to listen for %s: %s", ao->name, strerror(errno));
847 /* Make a record of all of this. */
848 l = xmalloc(sizeof(*l));
850 sel_initfile(&sel, &l->f, fd, SEL_READ, accept_client, l);
857 int main(int argc, char *argv[])
860 const struct addrops *ao;
865 fwatch_init(&polfw, "yaid.policy");
867 if (load_policy_file("yaid.policy", &policy))
870 for (i = 0; i < DA_LEN(&policy); i++)
871 print_policy(&DA(&policy)[i]);
874 if ((randfd = open("/dev/urandom", O_RDONLY)) < 0) {
875 die(1, "failed to open `/dev/urandom' for reading: %s",
880 for (ao = addroptab; ao->name; ao++)
881 if (!make_listening_socket(ao, port)) any = 1;
883 die(1, "no IP protocols supported");
886 if (sel_select(&sel)) die(1, "select failed: %s", strerror(errno));
891 /*----- That's all, folks -------------------------------------------------*/