Home | History | Annotate | Line # | Download | only in identd
identd.c revision 1.32
      1 /* $NetBSD: identd.c,v 1.32 2009/01/18 00:37:53 lukem Exp $ */
      2 
      3 /*
      4  * identd.c - TCP/IP Ident protocol server.
      5  *
      6  * This software is in the public domain.
      7  * Written by Peter Postma <peter (at) NetBSD.org>
      8  */
      9 
     10 #include <sys/cdefs.h>
     11 __RCSID("$NetBSD: identd.c,v 1.32 2009/01/18 00:37:53 lukem Exp $");
     12 
     13 #include <sys/param.h>
     14 #include <sys/socket.h>
     15 #include <sys/stat.h>
     16 #include <sys/sysctl.h>
     17 
     18 #include <netinet/in.h>
     19 #include <netinet/ip_var.h>
     20 #include <netinet/tcp.h>
     21 #include <netinet/tcp_timer.h>
     22 #include <netinet/tcp_var.h>
     23 
     24 #include <arpa/inet.h>
     25 
     26 #include <ctype.h>
     27 #include <err.h>
     28 #include <errno.h>
     29 #include <fcntl.h>
     30 #include <grp.h>
     31 #include <netdb.h>
     32 #include <poll.h>
     33 #include <pwd.h>
     34 #include <signal.h>
     35 #include <stdarg.h>
     36 #include <stdio.h>
     37 #include <stdlib.h>
     38 #include <string.h>
     39 #include <syslog.h>
     40 #include <unistd.h>
     41 
     42 #include "identd.h"
     43 
     44 #define	OPSYS_NAME	"UNIX"
     45 #define	IDENT_SERVICE	"auth"
     46 #define	TIMEOUT		30	/* seconds */
     47 
     48 static int   idhandle(int, const char *, const char *, const char *,
     49 		const char *, struct sockaddr *, int);
     50 static void  idparse(int, int, int, const char *, const char *, const char *);
     51 static void  iderror(int, int, int, const char *);
     52 static const char *gethost(struct sockaddr *);
     53 static int  *socketsetup(const char *, const char *, int);
     54 static int   ident_getuid(struct sockaddr_storage *, socklen_t,
     55 		struct sockaddr *, uid_t *);
     56 static int   sysctl_getuid(struct sockaddr_storage *, socklen_t, uid_t *);
     57 static int   sysctl_proxy_getuid(struct sockaddr_storage *,
     58 		struct sockaddr *, uid_t *);
     59 static int   forward(int, struct sockaddr *, int, int, int);
     60 static int   check_noident(const char *);
     61 static int   check_userident(const char *, char *, size_t);
     62 static void  random_string(char *, size_t);
     63 static int   change_format(const char *, struct passwd *, char *, size_t);
     64 static void  timeout_handler(int);
     65 static void  fatal(const char *);
     66 static void  die(const char *, ...);
     67 
     68 static int   bflag, eflag, fflag, iflag, Iflag;
     69 static int   lflag, Lflag, nflag, Nflag, rflag;
     70 
     71 /* NAT lookup function pointer. */
     72 static int  (*nat_lookup)(struct sockaddr_storage *, struct sockaddr *, int *);
     73 
     74 /* Packet filters. */
     75 static const struct {
     76 	const char *name;
     77 	int (*fn)(struct sockaddr_storage *, struct sockaddr *, int *);
     78 } filters[] = {
     79 #ifdef WITH_PF
     80 	{ "pf", pf_natlookup },
     81 #endif
     82 #ifdef WITH_IPF
     83 	{ "ipfilter", ipf_natlookup },
     84 #endif
     85 	{ NULL, NULL }
     86 };
     87 
     88 int
     89 main(int argc, char *argv[])
     90 {
     91 	int IPv4or6, ch, error, i, *socks, timeout;
     92 	const char *filter, *osname, *portno, *proxy;
     93 	char *address, *charset, *fmt, *p;
     94 	char user[LOGIN_NAME_MAX];
     95 	struct addrinfo *ai, hints;
     96 	struct sockaddr *proxy_addr;
     97 	struct group *grp;
     98 	struct passwd *pw;
     99 	gid_t gid;
    100 	uid_t uid;
    101 
    102 	socks = NULL;
    103 	IPv4or6 = AF_UNSPEC;
    104 	osname = OPSYS_NAME;
    105 	portno = IDENT_SERVICE;
    106 	timeout = TIMEOUT;
    107 	nat_lookup = NULL;
    108 	proxy_addr = NULL;
    109 	filter = proxy = NULL;
    110 	address = charset = fmt = NULL;
    111 	uid = gid = 0;
    112 	bflag = eflag = fflag = iflag = Iflag = 0;
    113 	lflag = Lflag = nflag = Nflag = rflag = 0;
    114 
    115 	/* Started from a tty? then run as daemon. */
    116 	if (isatty(STDIN_FILENO))
    117 		bflag = 1;
    118 
    119 	/* Parse command line arguments. */
    120 	while ((ch = getopt(argc, argv,
    121 	    "46a:bceF:f:g:IiL:lm:Nno:P:p:rt:u:")) != -1) {
    122 		switch (ch) {
    123 		case '4':
    124 			IPv4or6 = AF_INET;
    125 			break;
    126 		case '6':
    127 			IPv4or6 = AF_INET6;
    128 			break;
    129 		case 'a':
    130 			address = optarg;
    131 			break;
    132 		case 'b':
    133 			bflag = 1;
    134 			break;
    135 		case 'c':
    136 			charset = optarg;
    137 			break;
    138 		case 'e':
    139 			eflag = 1;
    140 			break;
    141 		case 'F':
    142 			fmt = optarg;
    143 			break;
    144 		case 'f':
    145 			fflag = 1;
    146 			(void)strlcpy(user, optarg, sizeof(user));
    147 			break;
    148 		case 'g':
    149 			gid = (gid_t)strtol(optarg, &p, 0);
    150 			if (*p != '\0') {
    151 				if ((grp = getgrnam(optarg)) != NULL)
    152 					gid = grp->gr_gid;
    153 				else
    154 					die("No such group `%s'", optarg);
    155 			}
    156 			break;
    157 		case 'I':
    158 			Iflag = 1;
    159 			/* FALLTHROUGH */
    160 		case 'i':
    161 			iflag = 1;
    162 			break;
    163 		case 'L':
    164 			Lflag = 1;
    165 			(void)strlcpy(user, optarg, sizeof(user));
    166 			break;
    167 		case 'l':
    168 			if (!lflag)
    169 				openlog("identd", LOG_PID, LOG_DAEMON);
    170 			lflag = 1;
    171 			break;
    172 		case 'm':
    173 			filter = optarg;
    174 			break;
    175 		case 'N':
    176 			Nflag = 1;
    177 			break;
    178 		case 'n':
    179 			nflag = 1;
    180 			break;
    181 		case 'o':
    182 			osname = optarg;
    183 			break;
    184 		case 'P':
    185 			proxy = optarg;
    186 			break;
    187 		case 'p':
    188 			portno = optarg;
    189 			break;
    190 		case 'r':
    191 			rflag = 1;
    192 			break;
    193 		case 't':
    194 			timeout = (int)strtol(optarg, &p, 0);
    195 			if (*p != '\0' || timeout < 1)
    196 				die("Invalid timeout value `%s'", optarg);
    197 			break;
    198 		case 'u':
    199 			uid = (uid_t)strtol(optarg, &p, 0);
    200 			if (*p != '\0') {
    201 				if ((pw = getpwnam(optarg)) != NULL) {
    202 					uid = pw->pw_uid;
    203 					gid = pw->pw_gid;
    204 				} else
    205 					die("No such user `%s'", optarg);
    206 			}
    207 			break;
    208 		default:
    209 			exit(EXIT_FAILURE);
    210 		}
    211 	}
    212 
    213 	/* Verify proxy address, if enabled. */
    214 	if (proxy != NULL) {
    215 		(void)memset(&hints, 0, sizeof(hints));
    216 		hints.ai_family = IPv4or6;
    217 		hints.ai_socktype = SOCK_STREAM;
    218 		error = getaddrinfo(proxy, NULL, &hints, &ai);
    219 		if (error != 0)
    220 			die("Bad proxy `%s': %s", proxy, gai_strerror(error));
    221 		if (ai->ai_next != NULL)
    222 			die("Bad proxy `%s': resolves to multiple addresses",
    223 			    proxy);
    224 		proxy_addr = ai->ai_addr;
    225 	}
    226 
    227 	/* Verify filter, if enabled. */
    228 	if (filter != NULL) {
    229 		for (i = 0; filters[i].name != NULL; i++) {
    230 			if (strcasecmp(filter, filters[i].name) == 0) {
    231 				nat_lookup = filters[i].fn;
    232 				break;
    233 			}
    234 		}
    235 		if (nat_lookup == NULL)
    236 			die("Packet filter `%s' is not supported", filter);
    237 	}
    238 
    239 	/* Setup sockets when running in the background. */
    240 	if (bflag)
    241 		socks = socketsetup(address, portno, IPv4or6);
    242 
    243 	/* Switch to another uid/gid? */
    244 	if (gid && setgid(gid) == -1)
    245 		die("Failed to set GID to `%d': %s", gid, strerror(errno));
    246 	if (uid && setuid(uid) == -1)
    247 		die("Failed to set UID to `%d': %s", uid, strerror(errno));
    248 
    249 	/*
    250 	 * When running as daemon: daemonize, setup pollfds and go into
    251 	 * the mainloop.  Otherwise, just read the input from stdin and
    252 	 * let inetd handle the sockets.
    253 	 */
    254 	if (bflag) {
    255 		int fd, nfds, rv;
    256 		struct pollfd *rfds;
    257 
    258 		if (daemon(0, 0) < 0)
    259 			die("daemon: %s", strerror(errno));
    260 
    261 		rfds = malloc(*socks * sizeof(struct pollfd));
    262 		if (rfds == NULL)
    263 			fatal("malloc");
    264 		nfds = *socks;
    265 		for (i = 0; i < nfds; i++) {
    266 			rfds[i].fd = socks[i+1];
    267 			rfds[i].events = POLLIN;
    268 			rfds[i].revents = 0;
    269 		}
    270 		/* Mainloop for daemon. */
    271 		for (;;) {
    272 			rv = poll(rfds, nfds, INFTIM);
    273 			if (rv < 0) {
    274 				if (errno == EINTR)
    275 					continue;
    276 				fatal("poll");
    277 			}
    278 			for (i = 0; i < nfds; i++) {
    279 				if (rfds[i].revents & POLLIN) {
    280 					fd = accept(rfds[i].fd, NULL, NULL);
    281 					if (fd < 0) {
    282 						maybe_syslog(LOG_ERR,
    283 						    "accept: %m");
    284 						continue;
    285 					}
    286 					switch (fork()) {
    287 					case -1:	/* error */
    288 						maybe_syslog(LOG_ERR,
    289 						    "fork: %m");
    290 						(void)sleep(1);
    291 						break;
    292 					case 0:		/* child */
    293 						(void)idhandle(fd, charset,
    294 						    fmt, osname, user,
    295 						    proxy_addr, timeout);
    296 						_exit(EXIT_SUCCESS);
    297 					default:	/* parent */
    298 						(void)signal(SIGCHLD, SIG_IGN);
    299 						(void)close(fd);
    300 					}
    301 				}
    302 			}
    303 		}
    304 	} else
    305 		(void)idhandle(STDIN_FILENO, charset, fmt, osname, user,
    306 		    proxy_addr, timeout);
    307 
    308 	return 0;
    309 }
    310 
    311 /*
    312  * Handle a request on the ident port.  Returns 0 on success or 1 on
    313  * failure.  The return values are currently ignored.
    314  */
    315 static int
    316 idhandle(int fd, const char *charset, const char *fmt, const char *osname,
    317     const char *user, struct sockaddr *proxy, int timeout)
    318 {
    319 	struct sockaddr_storage ss[2];
    320 	char userbuf[LOGIN_NAME_MAX];	/* actual user name (or numeric uid) */
    321 	char idbuf[LOGIN_NAME_MAX];	/* name to be used in response */
    322 	char buf[BUFSIZ], *p;
    323 	struct passwd *pw;
    324 	int lport, fport;
    325 	socklen_t len;
    326 	uid_t uid;
    327 	ssize_t n;
    328 	size_t qlen;
    329 
    330 	lport = fport = 0;
    331 
    332 	(void)strlcpy(idbuf, user, sizeof(idbuf));
    333 	(void)signal(SIGALRM, timeout_handler);
    334 	(void)alarm(timeout);
    335 
    336 	/* Get foreign internet address. */
    337 	len = sizeof(ss[0]);
    338 	if (getpeername(fd, (struct sockaddr *)&ss[0], &len) < 0)
    339 		fatal("getpeername");
    340 
    341 	maybe_syslog(LOG_INFO, "Connection from %s",
    342 	    gethost((struct sockaddr *)&ss[0]));
    343 
    344 	/* Get local internet address. */
    345 	len = sizeof(ss[1]);
    346 	if (getsockname(fd, (struct sockaddr *)&ss[1], &len) < 0)
    347 		fatal("getsockname");
    348 
    349 	/* Be sure to have the same address families. */
    350 	if (ss[0].ss_family != ss[1].ss_family) {
    351 		maybe_syslog(LOG_ERR, "Different foreign/local address family");
    352 		return 1;
    353 	}
    354 
    355 	/* Receive data from the client. */
    356 	qlen = 0;
    357 	for (;;) {
    358 		if ((n = recv(fd, &buf[qlen], sizeof(buf) - qlen, 0)) < 0) {
    359 			fatal("recv");
    360 		} else if (n == 0) {
    361 			maybe_syslog(LOG_NOTICE, "recv: EOF");
    362 			iderror(fd, 0, 0, "UNKNOWN-ERROR");
    363 			return 1;
    364 		}
    365 		/*
    366 		 * 1413 is not clear on what to do if data follows the first
    367 		 * CRLF before we respond.  We do not consider the query
    368 		 * complete until we get a CRLF _at the end of the buffer_.
    369 		 */
    370 		qlen += n;
    371 		if (qlen >= sizeof(buf)) {
    372 			maybe_syslog(LOG_NOTICE, "recv: message too long");
    373 			exit(0);
    374 		}
    375 		if ((qlen >= 2) && (buf[qlen - 2] == '\r') &&
    376 		    (buf[qlen - 1] == '\n'))
    377 			break;
    378 	}
    379 	buf[qlen - 2] = '\0';
    380 
    381 	/* Get local and remote ports from the received data. */
    382 	p = buf;
    383 	while (*p != '\0' && isspace((unsigned char)*p))
    384 		p++;
    385 	if ((p = strtok(p, " \t,")) != NULL) {
    386 		lport = atoi(p);
    387 		if ((p = strtok(NULL, " \t,")) != NULL)
    388 			fport = atoi(p);
    389 	}
    390 
    391 	/* Are the ports valid? */
    392 	if (lport < 1 || lport > 65535 || fport < 1 || fport > 65535) {
    393 		maybe_syslog(LOG_NOTICE, "Invalid port(s): %d, %d from %s",
    394 		    lport, fport, gethost((struct sockaddr *)&ss[0]));
    395 		iderror(fd, 0, 0, eflag ? "UNKNOWN-ERROR" : "INVALID-PORT");
    396 		return 1;
    397 	}
    398 
    399 	/* If there is a 'lie' user enabled, then handle it now and stop. */
    400 	if (Lflag) {
    401 		maybe_syslog(LOG_NOTICE, "Lying with name %s to %s",
    402 		    idbuf, gethost((struct sockaddr *)&ss[0]));
    403 		idparse(fd, lport, fport, charset, osname, idbuf);
    404 		return 0;
    405 	}
    406 
    407 	/* Protocol dependent stuff. */
    408 	switch (ss[0].ss_family) {
    409 	case AF_INET:
    410 		satosin(&ss[0])->sin_port = htons(fport);
    411 		satosin(&ss[1])->sin_port = htons(lport);
    412 		break;
    413 	case AF_INET6:
    414 		satosin6(&ss[0])->sin6_port = htons(fport);
    415 		satosin6(&ss[1])->sin6_port = htons(lport);
    416 		break;
    417 	default:
    418 		maybe_syslog(LOG_ERR, "Unsupported protocol (no. %d)",
    419 		    ss[0].ss_family);
    420 		return 1;
    421 	}
    422 
    423 	/* Try to get the UID of the connection owner using sysctl. */
    424 	if (ident_getuid(ss, sizeof(ss), proxy, &uid) == -1) {
    425 		/* Lookup failed, try to forward if enabled. */
    426 		if (nat_lookup != NULL) {
    427 			struct sockaddr nat_addr;
    428 			int nat_lport;
    429 
    430 			(void)memset(&nat_addr, 0, sizeof(nat_addr));
    431 
    432 			if ((*nat_lookup)(ss, &nat_addr, &nat_lport) &&
    433 			    forward(fd, &nat_addr, nat_lport, fport, lport)) {
    434 				maybe_syslog(LOG_INFO,
    435 				    "Succesfully forwarded the request to %s",
    436 				    gethost(&nat_addr));
    437 				return 0;
    438 			}
    439 		}
    440 		/* Fall back to a default name? */
    441 		if (fflag) {
    442 			maybe_syslog(LOG_NOTICE, "Using fallback name %s to %s",
    443 			    idbuf, gethost((struct sockaddr *)&ss[0]));
    444 			idparse(fd, lport, fport, charset, osname, idbuf);
    445 			return 0;
    446 		}
    447 		maybe_syslog(LOG_ERR, "Lookup failed, returning error to %s",
    448 		    gethost((struct sockaddr *)&ss[0]));
    449 		iderror(fd, lport, fport, eflag ? "UNKNOWN-ERROR" : "NO-USER");
    450 		return 1;
    451 	}
    452 
    453 	/* Fill in userbuf with user name if possible, else numeric UID. */
    454 	if ((pw = getpwuid(uid)) == NULL) {
    455 		maybe_syslog(LOG_ERR, "Couldn't map uid (%u) to name", uid);
    456 		(void)snprintf(userbuf, sizeof(userbuf), "%u", uid);
    457 	} else {
    458 		maybe_syslog(LOG_INFO, "Successful lookup: %d, %d: %s for %s",
    459 		    lport, fport, pw->pw_name,
    460 		    gethost((struct sockaddr *)&ss[0]));
    461 		(void)strlcpy(userbuf, pw->pw_name, sizeof(userbuf));
    462 	}
    463 
    464 	/* No ident enabled? */
    465 	if (Nflag && pw && check_noident(pw->pw_dir)) {
    466 		maybe_syslog(LOG_NOTICE, "Returning HIDDEN-USER for user %s"
    467 		    " to %s", pw->pw_name, gethost((struct sockaddr *)&ss[0]));
    468 		iderror(fd, lport, fport, "HIDDEN-USER");
    469 		return 1;
    470 	}
    471 
    472 	/* User ident enabled? */
    473 	if (iflag && pw && check_userident(pw->pw_dir, idbuf, sizeof(idbuf))) {
    474 		if (!Iflag) {
    475 			if ((strspn(idbuf, "0123456789") &&
    476 			     getpwuid(atoi(idbuf)) != NULL) ||
    477 			    (getpwnam(idbuf) != NULL)) {
    478 				maybe_syslog(LOG_NOTICE,
    479 				    "Ignoring user-specified '%s' for user %s",
    480 				    idbuf, userbuf);
    481 				(void)strlcpy(idbuf, userbuf, sizeof(idbuf));
    482 			}
    483 		}
    484 		maybe_syslog(LOG_NOTICE,
    485 		    "Returning user-specified '%s' for user %s to %s",
    486 		    idbuf, userbuf, gethost((struct sockaddr *)&ss[0]));
    487 		idparse(fd, lport, fport, charset, osname, idbuf);
    488 		return 0;
    489 	}
    490 
    491 	/* Send a random message? */
    492 	if (rflag) {
    493 		/* Random number or string? */
    494 		if (nflag)
    495 			(void)snprintf(idbuf, sizeof(idbuf), "%u",
    496 			    (unsigned int)(arc4random() % 65535));
    497 		else
    498 			random_string(idbuf, sizeof(idbuf));
    499 
    500 		maybe_syslog(LOG_NOTICE,
    501 		    "Returning random '%s' for user %s to %s",
    502 		    idbuf, userbuf, gethost((struct sockaddr *)&ss[0]));
    503 		idparse(fd, lport, fport, charset, osname, idbuf);
    504 		return 0;
    505 	}
    506 
    507 	/* Return numberic user ID? */
    508 	if (nflag)
    509 		(void)snprintf(idbuf, sizeof(idbuf), "%u", uid);
    510 	else
    511 		(void)strlcpy(idbuf, userbuf, sizeof(idbuf));
    512 
    513 	/*
    514 	 * Change the output format?  Note that 512 is the maximum
    515 	 * size of the result according to RFC 1413.
    516 	 */
    517 	if (fmt && change_format(fmt, pw, buf, 512 + 1))
    518 		idparse(fd, lport, fport, charset, osname, buf);
    519 	else
    520 		idparse(fd, lport, fport, charset, osname, idbuf);
    521 
    522 	return 0;
    523 }
    524 
    525 /* Send/parse the ident result. */
    526 static void
    527 idparse(int fd, int lport, int fport, const char *charset, const char *osname,
    528     const char *user)
    529 {
    530 	char *p;
    531 
    532 	if (asprintf(&p, "%d,%d:USERID:%s%s%s:%s\r\n", lport, fport,
    533 	    osname, charset ? "," : "", charset ? charset : "", user) < 0)
    534 		fatal("asprintf");
    535 	if (send(fd, p, strlen(p), 0) < 0) {
    536 		free(p);
    537 		fatal("send");
    538 	}
    539 	free(p);
    540 }
    541 
    542 /* Return a specified ident error. */
    543 static void
    544 iderror(int fd, int lport, int fport, const char *error)
    545 {
    546 	char *p;
    547 
    548 	if (asprintf(&p, "%d,%d:ERROR:%s\r\n", lport, fport, error) < 0)
    549 		fatal("asprintf");
    550 	if (send(fd, p, strlen(p), 0) < 0) {
    551 		free(p);
    552 		fatal("send");
    553 	}
    554 	free(p);
    555 }
    556 
    557 /* Return the IP address of the connecting host. */
    558 static const char *
    559 gethost(struct sockaddr *sa)
    560 {
    561 	static char host[NI_MAXHOST];
    562 
    563 	if (getnameinfo(sa, sa->sa_len, host, sizeof(host),
    564 	    NULL, 0, NI_NUMERICHOST) == 0)
    565 		return host;
    566 
    567 	return "UNKNOWN";
    568 }
    569 
    570 /* Setup sockets, for daemon mode. */
    571 static int *
    572 socketsetup(const char *address, const char *port, int af)
    573 {
    574 	struct addrinfo hints, *res, *res0;
    575 	int error, maxs, *s, *socks;
    576 	const char *cause = NULL;
    577 	socklen_t y = 1;
    578 
    579 	(void)memset(&hints, 0, sizeof(hints));
    580 	hints.ai_flags = AI_PASSIVE;
    581 	hints.ai_family = af;
    582 	hints.ai_socktype = SOCK_STREAM;
    583 	error = getaddrinfo(address, port, &hints, &res0);
    584 	if (error) {
    585 		die("getaddrinfo: %s", gai_strerror(error));
    586 		/* NOTREACHED */
    587 	}
    588 
    589 	/* Count max number of sockets we may open. */
    590 	for (maxs = 0, res = res0; res != NULL; res = res->ai_next)
    591 		maxs++;
    592 
    593 	socks = malloc((maxs + 1) * sizeof(int));
    594 	if (socks == NULL) {
    595 		die("malloc: %s", strerror(errno));
    596 		/* NOTREACHED */
    597 	}
    598 
    599 	*socks = 0;
    600 	s = socks + 1;
    601 	for (res = res0; res != NULL; res = res->ai_next) {
    602 		*s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    603 		if (*s < 0) {
    604 			cause = "socket";
    605 			continue;
    606 		}
    607 		(void)setsockopt(*s, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(y));
    608 		if (bind(*s, res->ai_addr, res->ai_addrlen) < 0) {
    609 			cause = "bind";
    610 			(void)close(*s);
    611 			continue;
    612 		}
    613 		if (listen(*s, 5) < 0) {
    614 			cause = "listen";
    615 			(void)close(*s);
    616 			continue;
    617 		}
    618 		*socks = *socks + 1;
    619 		s++;
    620 	}
    621 
    622 	if (*socks == 0) {
    623 		free(socks);
    624 		die("%s: %s", cause, strerror(errno));
    625 		/* NOTREACHED */
    626 	}
    627 	if (res0)
    628 		freeaddrinfo(res0);
    629 
    630 	return socks;
    631 }
    632 
    633 /* UID lookup wrapper. */
    634 static int
    635 ident_getuid(struct sockaddr_storage *ss, socklen_t len,
    636     struct sockaddr *proxy, uid_t *uid)
    637 {
    638 	int rc;
    639 
    640 	rc = sysctl_getuid(ss, len, uid);
    641 	if (rc == -1 && proxy != NULL)
    642 		rc = sysctl_proxy_getuid(ss, proxy, uid);
    643 
    644 	return rc;
    645 }
    646 
    647 /* Try to get the UID of the connection owner using sysctl. */
    648 static int
    649 sysctl_getuid(struct sockaddr_storage *ss, socklen_t len, uid_t *uid)
    650 {
    651 	int mib[4];
    652 	uid_t myuid;
    653 	size_t uidlen;
    654 
    655 	uidlen = sizeof(myuid);
    656 
    657 	mib[0] = CTL_NET;
    658 	mib[1] = ss->ss_family;
    659 	mib[2] = IPPROTO_TCP;
    660 	mib[3] = TCPCTL_IDENT;
    661 
    662 	if (sysctl(mib, sizeof(mib)/ sizeof(int), &myuid, &uidlen, ss, len) < 0)
    663 		return -1;
    664 	*uid = myuid;
    665 
    666 	return 0;
    667 }
    668 
    669 /* Try to get the UID of the connection owner using sysctl (proxy version). */
    670 static int
    671 sysctl_proxy_getuid(struct sockaddr_storage *ss, struct sockaddr *proxy,
    672     uid_t *uid)
    673 {
    674 	struct sockaddr_storage new[2];
    675 	int rc, name[CTL_MAXNAME];
    676 	size_t i;
    677 	struct kinfo_pcb *kp;
    678 	size_t sz, len;
    679 	const char *list;
    680 
    681 	rc = -1;
    682 	sz = CTL_MAXNAME;
    683 	list = NULL;
    684 
    685 	/* Retrieve a list of sockets. */
    686 	switch (ss[0].ss_family) {
    687 	case AF_INET:
    688 		/* We only accept queries from the proxy. */
    689 		if (in_hosteq(satosin(&ss[0])->sin_addr,
    690 		    satosin(proxy)->sin_addr))
    691 			list = "net.inet.tcp.pcblist";
    692 		break;
    693 	case AF_INET6:
    694 		/* We only accept queries from the proxy. */
    695 		if (IN6_ARE_ADDR_EQUAL(&satosin6(&ss[0])->sin6_addr,
    696 		    &satosin6(proxy)->sin6_addr))
    697 			list = "net.inet6.tcp.pcblist";
    698 		break;
    699 	default:
    700 		maybe_syslog(LOG_ERR, "Unsupported protocol for proxy (no. %d)",
    701 		    ss[0].ss_family);
    702 	}
    703 	if (list != NULL)
    704 		rc = sysctlnametomib(list, &name[0], &sz);
    705 	if (rc == -1)
    706 		return -1;
    707 	len = sz;
    708 
    709 	name[len++] = PCB_ALL;
    710 	name[len++] = 0;
    711 	name[len++] = sizeof(struct kinfo_pcb);
    712 	name[len++] = INT_MAX;
    713 
    714 	kp = NULL;
    715 	sz = 0;
    716 	do {
    717 		rc = sysctl(&name[0], len, kp, &sz, NULL, 0);
    718 		if (rc == -1 && errno != ENOMEM)
    719 			return -1;
    720 		if (kp == NULL) {
    721 			kp = malloc(sz);
    722 			rc = -1;
    723 		}
    724 		if (kp == NULL)
    725 			return -1;
    726 	} while (rc == -1);
    727 
    728 	rc = -1;
    729 	/*
    730 	 * Walk through the list of sockets and try to find a match.
    731 	 * We don't know who has sent the query (we only know that the
    732 	 * proxy has forwarded to us) so just try to match the ports and
    733 	 * the local address.
    734 	 */
    735 	for (i = 0; i < sz / sizeof(struct kinfo_pcb); i++) {
    736 		switch (ss[0].ss_family) {
    737 		case AF_INET:
    738 			/* Foreign and local ports must match. */
    739 			if (satosin(&ss[0])->sin_port !=
    740 			    satosin(&kp[i].ki_src)->sin_port)
    741 				continue;
    742 			if (satosin(&ss[1])->sin_port !=
    743 			    satosin(&kp[i].ki_dst)->sin_port)
    744 				continue;
    745 			/* Foreign address may not match proxy address. */
    746 			if (in_hosteq(satosin(proxy)->sin_addr,
    747 			    satosin(&kp[i].ki_dst)->sin_addr))
    748 				continue;
    749 			/* Local addresses must match. */
    750 			if (!in_hosteq(satosin(&ss[1])->sin_addr,
    751 			    satosin(&kp[i].ki_src)->sin_addr))
    752 				continue;
    753 			break;
    754 		case AF_INET6:
    755 			/* Foreign and local ports must match. */
    756 			if (satosin6(&ss[0])->sin6_port !=
    757 			    satosin6(&kp[i].ki_src)->sin6_port)
    758 				continue;
    759 			if (satosin6(&ss[1])->sin6_port !=
    760 			    satosin6(&kp[i].ki_dst)->sin6_port)
    761 				continue;
    762 			/* Foreign address may not match proxy address. */
    763 			if (IN6_ARE_ADDR_EQUAL(&satosin6(proxy)->sin6_addr,
    764 			    &satosin6(&kp[i].ki_dst)->sin6_addr))
    765 				continue;
    766 			/* Local addresses must match. */
    767 			if (!IN6_ARE_ADDR_EQUAL(&satosin6(&ss[1])->sin6_addr,
    768 			    &satosin6(&kp[i].ki_src)->sin6_addr))
    769 				continue;
    770 			break;
    771 		}
    772 
    773 		/*
    774 		 * We have found the foreign address, copy it to a new
    775 		 * struct and retrieve the UID of the connection owner.
    776 		 */
    777 		(void)memcpy(&new[0], &kp[i].ki_dst, kp[i].ki_dst.sa_len);
    778 		(void)memcpy(&new[1], &kp[i].ki_src, kp[i].ki_src.sa_len);
    779 
    780 		rc = sysctl_getuid(new, sizeof(new), uid);
    781 
    782 		/* Done. */
    783 		break;
    784 	}
    785 
    786 	free(kp);
    787 	return rc;
    788 }
    789 
    790 /* Forward ident queries. Returns 1 when succesful, or zero if not. */
    791 static int
    792 forward(int fd, struct sockaddr *nat_addr, int nat_lport, int fport, int lport)
    793 {
    794 	char buf[BUFSIZ], reply[BUFSIZ], *p;
    795 	ssize_t n;
    796 	int sock;
    797 
    798 	/* Connect to the NAT host. */
    799 	sock = socket(nat_addr->sa_family, SOCK_STREAM, 0);
    800 	if (sock < 0) {
    801 		maybe_syslog(LOG_ERR, "socket: %m");
    802 		return 0;
    803 	}
    804 	if (connect(sock, nat_addr, nat_addr->sa_len) < 0) {
    805 		maybe_syslog(LOG_ERR, "Can't connect to %s: %m",
    806 		    gethost(nat_addr));
    807 		(void)close(sock);
    808 		return 0;
    809 	}
    810 
    811 	/*
    812 	 * Send the ident query to the NAT host, but use as local port
    813 	 * the port of the NAT host.
    814 	 */
    815 	(void)snprintf(buf, sizeof(buf), "%d , %d\r\n", nat_lport, fport);
    816 	if (send(sock, buf, strlen(buf), 0) < 0) {
    817 		maybe_syslog(LOG_ERR, "send: %m");
    818 		(void)close(sock);
    819 		return 0;
    820 	}
    821 
    822 	/* Read the reply from the NAT host. */
    823 	if ((n = recv(sock, reply, sizeof(reply) - 1, 0)) < 0) {
    824 		maybe_syslog(LOG_ERR, "recv: %m");
    825 		(void)close(sock);
    826 		return 0;
    827 	} else if (n == 0) {
    828 		maybe_syslog(LOG_NOTICE, "recv: EOF");
    829 		(void)close(sock);
    830 		return 0;
    831 	}
    832 	reply[n] = '\0';
    833 	(void)close(sock);
    834 
    835 	/* Extract everything after the port specs from the ident reply. */
    836 	for (p = reply; *p != '\0' && *p != ':'; p++)
    837 		continue;
    838 	if (*p == '\0' || *++p == '\0') {
    839 		maybe_syslog(LOG_ERR, "Malformed ident reply from %s",
    840 		    gethost(nat_addr));
    841 		return 0;
    842 	}
    843 	/* Build reply for the requesting host, use the original local port. */
    844 	(void)snprintf(buf, sizeof(buf), "%d,%d:%s", lport, fport, p);
    845 
    846 	/* Send the reply from the NAT host back to the requesting host. */
    847 	if (send(fd, buf, strlen(buf), 0) < 0) {
    848 		maybe_syslog(LOG_ERR, "send: %m");
    849 		return 0;
    850 	}
    851 
    852 	return 1;
    853 }
    854 
    855 /* Check if a .noident file exists in the user home directory. */
    856 static int
    857 check_noident(const char *homedir)
    858 {
    859 	struct stat sb;
    860 	char *path;
    861 	int ret;
    862 
    863 	if (homedir == NULL)
    864 		return 0;
    865 	if (asprintf(&path, "%s/.noident", homedir) < 0)
    866 		return 0;
    867 	ret = stat(path, &sb);
    868 
    869 	free(path);
    870 	return (ret == 0);
    871 }
    872 
    873 /*
    874  * Check if a .ident file exists in the user home directory and
    875  * return the contents of that file.
    876  */
    877 static int
    878 check_userident(const char *homedir, char *username, size_t len)
    879 {
    880 	struct stat sb;
    881 	char *path, *p;
    882 	ssize_t n;
    883 	int fd;
    884 
    885 	if (len == 0 || homedir == NULL)
    886 		return 0;
    887 	if (asprintf(&path, "%s/.ident", homedir) < 0)
    888 		return 0;
    889 	if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_NOFOLLOW, 0)) < 0) {
    890 		free(path);
    891 		return 0;
    892 	}
    893 	if (fstat(fd, &sb) < 0 || !S_ISREG(sb.st_mode)) {
    894 		(void)close(fd);
    895 		free(path);
    896 		return 0;
    897 	}
    898 	if ((n = read(fd, username, len - 1)) < 1) {
    899 		(void)close(fd);
    900 		free(path);
    901 		return 0;
    902 	}
    903 	username[n] = '\0';
    904 
    905 	if ((p = strpbrk(username, "\r\n")) != NULL)
    906 		*p = '\0';
    907 
    908 	(void)close(fd);
    909 	free(path);
    910 	return 1;
    911 }
    912 
    913 /* Generate a random string. */
    914 static void
    915 random_string(char *str, size_t len)
    916 {
    917 	static const char chars[] = "abcdefghijklmnopqrstuvwxyz1234567890";
    918 	char *p;
    919 
    920 	if (len == 0)
    921 		return;
    922 	for (p = str; len > 1; len--)
    923 		*p++ = chars[arc4random() % (sizeof(chars) - 1)];
    924 	*p = '\0';
    925 }
    926 
    927 /* Change the output format. */
    928 static int
    929 change_format(const char *format, struct passwd *pw, char *dest, size_t len)
    930 {
    931 	struct group *gr;
    932 	const char *cp;
    933 	char **gmp;
    934 	size_t bp;
    935 
    936 	if (len == 0 || ((gr = getgrgid(pw->pw_gid)) == NULL))
    937 		return 0;
    938 
    939 	for (bp = 0, cp = format; *cp != '\0' && bp < len - 1; cp++) {
    940 		if (*cp != '%') {
    941 			dest[bp++] = *cp;
    942 			continue;
    943 		}
    944 		if (*++cp == '\0')
    945 			break;
    946 		switch (*cp) {
    947 		case 'u':
    948 			(void)snprintf(&dest[bp], len - bp, "%s", pw->pw_name);
    949 			break;
    950 		case 'U':
    951 			(void)snprintf(&dest[bp], len - bp, "%d", pw->pw_uid);
    952 			break;
    953 		case 'g':
    954 			(void)snprintf(&dest[bp], len - bp, "%s", gr->gr_name);
    955 			break;
    956 		case 'G':
    957 			(void)snprintf(&dest[bp], len - bp, "%d", gr->gr_gid);
    958 			break;
    959 		case 'l':
    960 			(void)snprintf(&dest[bp], len - bp, "%s", gr->gr_name);
    961 			bp += strlen(&dest[bp]);
    962 			if (bp >= len)
    963 				break;
    964 			setgrent();
    965 			while ((gr = getgrent()) != NULL) {
    966 				if (gr->gr_gid == pw->pw_gid)
    967 					continue;
    968 				for (gmp = gr->gr_mem; *gmp && **gmp; gmp++) {
    969 					if (strcmp(*gmp, pw->pw_name) == 0) {
    970 						(void)snprintf(&dest[bp],
    971 						    len - bp, ",%s",
    972 						    gr->gr_name);
    973 						bp += strlen(&dest[bp]);
    974 						break;
    975 					}
    976 				}
    977 				if (bp >= len)
    978 					break;
    979 			}
    980 			endgrent();
    981 			break;
    982 		case 'L':
    983 			(void)snprintf(&dest[bp], len - bp, "%u", gr->gr_gid);
    984 			bp += strlen(&dest[bp]);
    985 			if (bp >= len)
    986 				break;
    987 			setgrent();
    988 			while ((gr = getgrent()) != NULL) {
    989 				if (gr->gr_gid == pw->pw_gid)
    990 					continue;
    991 				for (gmp = gr->gr_mem; *gmp && **gmp; gmp++) {
    992 					if (strcmp(*gmp, pw->pw_name) == 0) {
    993 						(void)snprintf(&dest[bp],
    994 						    len - bp, ",%u",
    995 						    gr->gr_gid);
    996 						bp += strlen(&dest[bp]);
    997 						break;
    998 					}
    999 				}
   1000 				if (bp >= len)
   1001 					break;
   1002 			}
   1003 			endgrent();
   1004 			break;
   1005 		default:
   1006 			dest[bp] = *cp;
   1007 			dest[bp+1] = '\0';
   1008 			break;
   1009 		}
   1010 		bp += strlen(&dest[bp]);
   1011 	}
   1012 	dest[bp] = '\0';
   1013 
   1014 	return 1;
   1015 }
   1016 
   1017 /* Just exit when we caught SIGALRM. */
   1018 static void
   1019 timeout_handler(int __unused s)
   1020 {
   1021 	maybe_syslog(LOG_INFO, "Timeout for request, closing connection...");
   1022 	exit(EXIT_FAILURE);
   1023 }
   1024 
   1025 /* Report error message string through syslog and quit. */
   1026 static void
   1027 fatal(const char *func)
   1028 {
   1029 	maybe_syslog(LOG_ERR, "%s: %m", func);
   1030 	exit(EXIT_FAILURE);
   1031 }
   1032 
   1033 /*
   1034  * Report an error through syslog and/or stderr and quit.  Only used when
   1035  * running identd in the background and when it isn't a daemon yet.
   1036  */
   1037 static void
   1038 die(const char *message, ...)
   1039 {
   1040 	va_list ap;
   1041 
   1042 	va_start(ap, message);
   1043 	if (bflag)
   1044 		vwarnx(message, ap);
   1045 	if (lflag)
   1046 		vsyslog(LOG_ERR, message, ap);
   1047 	va_end(ap);
   1048 
   1049 	exit(EXIT_FAILURE);
   1050 }
   1051 
   1052 /* Log using syslog, but only if enabled with the -l flag. */
   1053 void
   1054 maybe_syslog(int priority, const char *message, ...)
   1055 {
   1056 	va_list ap;
   1057 
   1058 	if (lflag) {
   1059 		va_start(ap, message);
   1060 		vsyslog(priority, message, ap);
   1061 		va_end(ap);
   1062 	}
   1063 }
   1064