Home | History | Annotate | Line # | Download | only in identd
identd.c revision 1.27
      1 /* $NetBSD: identd.c,v 1.27 2005/05/18 00:31:32 peter 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/types.h>
     11 #include <sys/socket.h>
     12 #include <sys/stat.h>
     13 #include <sys/param.h>
     14 #include <sys/sysctl.h>
     15 
     16 #include <netinet/in.h>
     17 #include <netinet/ip_var.h>
     18 #include <netinet/tcp.h>
     19 #include <netinet/tcp_timer.h>
     20 #include <netinet/tcp_var.h>
     21 
     22 #include <arpa/inet.h>
     23 
     24 #include <ctype.h>
     25 #include <err.h>
     26 #include <errno.h>
     27 #include <fcntl.h>
     28 #include <grp.h>
     29 #include <netdb.h>
     30 #include <poll.h>
     31 #include <pwd.h>
     32 #include <signal.h>
     33 #include <stdarg.h>
     34 #include <stdio.h>
     35 #include <stdlib.h>
     36 #include <string.h>
     37 #include <syslog.h>
     38 #include <unistd.h>
     39 
     40 #include "identd.h"
     41 
     42 __RCSID("$NetBSD: identd.c,v 1.27 2005/05/18 00:31:32 peter Exp $");
     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, 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 	IPv4or6 = AF_UNSPEC;
    103 	osname = OPSYS_NAME;
    104 	portno = IDENT_SERVICE;
    105 	timeout = TIMEOUT;
    106 	nat_lookup = NULL;
    107 	proxy_addr = NULL;
    108 	filter = proxy = NULL;
    109 	address = charset = fmt = NULL;
    110 	uid = gid = 0;
    111 	bflag = eflag = fflag = Fflag = iflag = Iflag = 0;
    112 	lflag = Lflag = nflag = Nflag = rflag = 0;
    113 
    114 	/* Started from a tty? then run as daemon. */
    115 	if (isatty(0))
    116 		bflag = 1;
    117 
    118 	/* Parse command line arguments. */
    119 	while ((ch = getopt(argc, argv,
    120 	    "46a:bceF:f:g:IiL:lm:Nno:P:p:rt:u:")) != -1) {
    121 		switch (ch) {
    122 		case '4':
    123 			IPv4or6 = AF_INET;
    124 			break;
    125 		case '6':
    126 			IPv4or6 = AF_INET6;
    127 			break;
    128 		case 'a':
    129 			address = optarg;
    130 			break;
    131 		case 'b':
    132 			bflag = 1;
    133 			break;
    134 		case 'c':
    135 			charset = optarg;
    136 			break;
    137 		case 'e':
    138 			eflag = 1;
    139 			break;
    140 		case 'F':
    141 			Fflag = 1;
    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 static int
    312 idhandle(int fd, const char *charset, const char *fmt, const char *osname,
    313     const char *user, struct sockaddr *proxy, int timeout)
    314 {
    315 	struct sockaddr_storage ss[2];
    316 	char userbuf[LOGIN_NAME_MAX];	/* actual user name (or numeric uid) */
    317 	char idbuf[LOGIN_NAME_MAX];	/* name to be used in response */
    318 	char buf[BUFSIZ], *p;
    319 	int n, lport, fport;
    320 	struct passwd *pw;
    321 	socklen_t len;
    322 	uid_t uid;
    323 
    324 	lport = fport = 0;
    325 
    326 	(void)strlcpy(idbuf, user, sizeof(idbuf));
    327 	(void)signal(SIGALRM, timeout_handler);
    328 	(void)alarm(timeout);
    329 
    330 	/* Get foreign internet address. */
    331 	len = sizeof(ss[0]);
    332 	if (getpeername(fd, (struct sockaddr *)&ss[0], &len) < 0)
    333 		fatal("getpeername");
    334 
    335 	maybe_syslog(LOG_INFO, "Connection from %s",
    336 	    gethost((struct sockaddr *)&ss[0]));
    337 
    338 	/* Get local internet address. */
    339 	len = sizeof(ss[1]);
    340 	if (getsockname(fd, (struct sockaddr *)&ss[1], &len) < 0)
    341 		fatal("getsockname");
    342 
    343 	/* Be sure to have the same address families. */
    344 	if (ss[0].ss_family != ss[1].ss_family) {
    345 		maybe_syslog(LOG_ERR, "Different foreign/local address family");
    346 		return 1;
    347 	}
    348 
    349 	/* Receive data from the client. */
    350 	if ((n = recv(fd, buf, sizeof(buf) - 1, 0)) < 0) {
    351 		fatal("recv");
    352 	} else if (n == 0) {
    353 		maybe_syslog(LOG_NOTICE, "recv: EOF");
    354 		iderror(fd, 0, 0, "UNKNOWN-ERROR");
    355 		return 1;
    356 	}
    357 	buf[n] = '\0';
    358 
    359 	/* Get local and remote ports from the received data. */
    360 	p = buf;
    361 	while (*p != '\0' && isspace((unsigned char)*p))
    362 		p++;
    363 	if ((p = strtok(p, " \t,")) != NULL) {
    364 		lport = atoi(p);
    365 		if ((p = strtok(NULL, " \t,")) != NULL)
    366 			fport = atoi(p);
    367 	}
    368 
    369 	/* Are the ports valid? */
    370 	if (lport < 1 || lport > 65535 || fport < 1 || fport > 65535) {
    371 		maybe_syslog(LOG_NOTICE, "Invalid port(s): %d, %d from %s",
    372 		    lport, fport, gethost((struct sockaddr *)&ss[0]));
    373 		iderror(fd, 0, 0, eflag ? "UNKNOWN-ERROR" : "INVALID-PORT");
    374 		return 1;
    375 	}
    376 
    377 	/* If there is a 'lie' user enabled, then handle it now and stop. */
    378 	if (Lflag) {
    379 		maybe_syslog(LOG_NOTICE, "Lying with name %s to %s",
    380 		    idbuf, gethost((struct sockaddr *)&ss[0]));
    381 		idparse(fd, lport, fport, charset, osname, idbuf);
    382 		return 0;
    383 	}
    384 
    385 	/* Protocol dependent stuff. */
    386 	switch (ss[0].ss_family) {
    387 	case AF_INET:
    388 		satosin(&ss[0])->sin_port = htons(fport);
    389 		satosin(&ss[1])->sin_port = htons(lport);
    390 		break;
    391 	case AF_INET6:
    392 		satosin6(&ss[0])->sin6_port = htons(fport);
    393 		satosin6(&ss[1])->sin6_port = htons(lport);
    394 		break;
    395 	default:
    396 		maybe_syslog(LOG_ERR, "Unsupported protocol (no. %d)",
    397 		    ss[0].ss_family);
    398 		return 1;
    399 	}
    400 
    401 	/* Try to get the UID of the connection owner using sysctl. */
    402 	if (ident_getuid(ss, sizeof(ss), proxy, &uid) == -1) {
    403 		/* Lookup failed, try to forward if enabled. */
    404 		if (nat_lookup != NULL) {
    405 			struct sockaddr nat_addr;
    406 			int nat_lport;
    407 
    408 			(void)memset(&nat_addr, 0, sizeof(nat_addr));
    409 
    410 			if ((*nat_lookup)(ss, &nat_addr, &nat_lport) &&
    411 			    forward(fd, &nat_addr, nat_lport, fport, lport)) {
    412 				maybe_syslog(LOG_INFO,
    413 				    "Succesfully forwarded the request to %s",
    414 				    gethost(&nat_addr));
    415 				return 0;
    416 			}
    417 		}
    418 		/* Fall back to a default name? */
    419 		if (fflag) {
    420 			maybe_syslog(LOG_NOTICE, "Using fallback name %s to %s",
    421 			    idbuf, gethost((struct sockaddr *)&ss[0]));
    422 			idparse(fd, lport, fport, charset, osname, idbuf);
    423 			return 0;
    424 		}
    425 		maybe_syslog(LOG_ERR, "Lookup failed, returning error to %s",
    426 		    gethost((struct sockaddr *)&ss[0]));
    427 		iderror(fd, lport, fport, eflag ? "UNKNOWN-ERROR" : "NO-USER");
    428 		return 1;
    429 	}
    430 
    431 	/* Fill in userbuf with user name if possible, else numeric UID. */
    432 	if ((pw = getpwuid(uid)) == NULL) {
    433 		maybe_syslog(LOG_ERR, "Couldn't map uid (%u) to name", uid);
    434 		(void)snprintf(userbuf, sizeof(userbuf), "%u", uid);
    435 	} else {
    436 		maybe_syslog(LOG_INFO, "Successful lookup: %d, %d: %s for %s",
    437 		    lport, fport, pw->pw_name,
    438 		    gethost((struct sockaddr *)&ss[0]));
    439 		(void)strlcpy(userbuf, pw->pw_name, sizeof(userbuf));
    440 	}
    441 
    442 	/* No ident enabled? */
    443 	if (Nflag && pw && check_noident(pw->pw_dir)) {
    444 		maybe_syslog(LOG_NOTICE, "Returning HIDDEN-USER for user %s"
    445 		    " to %s", pw->pw_name, gethost((struct sockaddr *)&ss[0]));
    446 		iderror(fd, lport, fport, "HIDDEN-USER");
    447 		return 1;
    448 	}
    449 
    450 	/* User ident enabled? */
    451 	if (iflag && pw && check_userident(pw->pw_dir, idbuf, sizeof(idbuf))) {
    452 		if (!Iflag) {
    453 			if ((strspn(idbuf, "0123456789") &&
    454 			     getpwuid(atoi(idbuf)) != NULL) ||
    455 			    (getpwnam(idbuf) != NULL)) {
    456 				maybe_syslog(LOG_NOTICE,
    457 				    "Ignoring user-specified '%s' for user %s",
    458 				    idbuf, userbuf);
    459 				(void)strlcpy(idbuf, userbuf, sizeof(idbuf));
    460 			}
    461 		}
    462 		maybe_syslog(LOG_NOTICE,
    463 		    "Returning user-specified '%s' for user %s to %s",
    464 		    idbuf, userbuf, gethost((struct sockaddr *)&ss[0]));
    465 		idparse(fd, lport, fport, charset, osname, idbuf);
    466 		return 0;
    467 	}
    468 
    469 	/* Send a random message? */
    470 	if (rflag) {
    471 		/* Random number or string? */
    472 		if (nflag)
    473 			(void)snprintf(idbuf, sizeof(idbuf), "%u",
    474 			    (unsigned int)(arc4random() % 65535));
    475 		else
    476 			random_string(idbuf, sizeof(idbuf));
    477 
    478 		maybe_syslog(LOG_NOTICE,
    479 		    "Returning random '%s' for user %s to %s",
    480 		    idbuf, userbuf, gethost((struct sockaddr *)&ss[0]));
    481 		idparse(fd, lport, fport, charset, osname, idbuf);
    482 		return 0;
    483 	}
    484 
    485 	/* Return numberic user ID? */
    486 	if (nflag)
    487 		(void)snprintf(idbuf, sizeof(idbuf), "%u", uid);
    488 	else
    489 		(void)strlcpy(idbuf, userbuf, sizeof(idbuf));
    490 
    491 	/*
    492 	 * Change the output format?  Note that 512 is the maximum
    493 	 * size of the result according to RFC 1413.
    494 	 */
    495 	if (Fflag && change_format(fmt, pw, buf, 512))
    496 		idparse(fd, lport, fport, charset, osname, buf);
    497 	else
    498 		idparse(fd, lport, fport, charset, osname, idbuf);
    499 
    500 	return 0;
    501 }
    502 
    503 /* Send/parse the ident result. */
    504 static void
    505 idparse(int fd, int lport, int fport, const char *charset, const char *osname,
    506     const char *user)
    507 {
    508 	char *p;
    509 
    510 	if (asprintf(&p, "%d,%d:USERID:%s%s%s:%s\r\n", lport, fport,
    511 	    osname, charset ? "," : "", charset ? charset : "", user) < 0)
    512 		fatal("asprintf");
    513 	if (send(fd, p, strlen(p), 0) < 0) {
    514 		free(p);
    515 		fatal("send");
    516 	}
    517 	free(p);
    518 }
    519 
    520 /* Return a specified ident error. */
    521 static void
    522 iderror(int fd, int lport, int fport, const char *error)
    523 {
    524 	char *p;
    525 
    526 	if (asprintf(&p, "%d,%d:ERROR:%s\r\n", lport, fport, error) < 0)
    527 		fatal("asprintf");
    528 	if (send(fd, p, strlen(p), 0) < 0) {
    529 		free(p);
    530 		fatal("send");
    531 	}
    532 	free(p);
    533 }
    534 
    535 /* Return the IP address of the connecting host. */
    536 static const char *
    537 gethost(struct sockaddr *sa)
    538 {
    539 	static char host[NI_MAXHOST];
    540 
    541 	if (getnameinfo(sa, sa->sa_len, host, sizeof(host),
    542 	    NULL, 0, NI_NUMERICHOST) == 0)
    543 		return host;
    544 
    545 	return "UNKNOWN";
    546 }
    547 
    548 /* Setup sockets, for daemon mode. */
    549 static int *
    550 socketsetup(const char *address, const char *port, int af)
    551 {
    552 	struct addrinfo hints, *res, *res0;
    553 	int error, maxs, *s, *socks, y = 1;
    554 	const char *cause = NULL;
    555 
    556 	(void)memset(&hints, 0, sizeof(hints));
    557 	hints.ai_flags = AI_PASSIVE;
    558 	hints.ai_family = af;
    559 	hints.ai_socktype = SOCK_STREAM;
    560 	error = getaddrinfo(address, port, &hints, &res0);
    561 	if (error) {
    562 		die("getaddrinfo: %s", gai_strerror(error));
    563 		/* NOTREACHED */
    564 	}
    565 
    566 	/* Count max number of sockets we may open. */
    567 	for (maxs = 0, res = res0; res != NULL; res = res->ai_next)
    568 		maxs++;
    569 
    570 	socks = malloc((maxs + 1) * sizeof(int));
    571 	if (socks == NULL) {
    572 		die("malloc: %s", strerror(errno));
    573 		/* NOTREACHED */
    574 	}
    575 
    576 	*socks = 0;
    577 	s = socks + 1;
    578 	for (res = res0; res != NULL; res = res->ai_next) {
    579 		*s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    580 		if (*s < 0) {
    581 			cause = "socket";
    582 			continue;
    583 		}
    584 		(void)setsockopt(*s, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(y));
    585 		if (bind(*s, res->ai_addr, res->ai_addrlen) < 0) {
    586 			cause = "bind";
    587 			(void)close(*s);
    588 			continue;
    589 		}
    590 		if (listen(*s, 5) < 0) {
    591 			cause = "listen";
    592 			(void)close(*s);
    593 			continue;
    594 		}
    595 		*socks = *socks + 1;
    596 		s++;
    597 	}
    598 
    599 	if (*socks == 0) {
    600 		free(socks);
    601 		die("%s: %s", cause, strerror(errno));
    602 		/* NOTREACHED */
    603 	}
    604 	if (res0)
    605 		freeaddrinfo(res0);
    606 
    607 	return socks;
    608 }
    609 
    610 /* UID lookup wrapper. */
    611 static int
    612 ident_getuid(struct sockaddr_storage *ss, socklen_t len,
    613     struct sockaddr *proxy, uid_t *uid)
    614 {
    615 	int rc;
    616 
    617 	rc = sysctl_getuid(ss, len, uid);
    618 	if (rc == -1 && proxy != NULL)
    619 		rc = sysctl_proxy_getuid(ss, proxy, uid);
    620 
    621 	return rc;
    622 }
    623 
    624 /* Try to get the UID of the connection owner using sysctl. */
    625 static int
    626 sysctl_getuid(struct sockaddr_storage *ss, socklen_t len, uid_t *uid)
    627 {
    628 	int mib[4];
    629 	uid_t myuid;
    630 	size_t uidlen;
    631 
    632 	uidlen = sizeof(myuid);
    633 
    634 	mib[0] = CTL_NET;
    635 	mib[1] = ss->ss_family;
    636 	mib[2] = IPPROTO_TCP;
    637 	mib[3] = TCPCTL_IDENT;
    638 
    639 	if (sysctl(mib, sizeof(mib)/ sizeof(int), &myuid, &uidlen, ss, len) < 0)
    640 		return -1;
    641 	*uid = myuid;
    642 
    643 	return 0;
    644 }
    645 
    646 /* Try to get the UID of the connection owner using sysctl (proxy version). */
    647 static int
    648 sysctl_proxy_getuid(struct sockaddr_storage *ss, struct sockaddr *proxy,
    649     uid_t *uid)
    650 {
    651 	struct sockaddr_storage new[2];
    652 	int i, rc, name[CTL_MAXNAME];
    653 	struct kinfo_pcb *kp;
    654 	size_t sz, len;
    655 	const char *list;
    656 
    657 	rc = -1;
    658 	sz = CTL_MAXNAME;
    659 	list = NULL;
    660 
    661 	/* Retrieve a list of sockets. */
    662 	switch (ss[0].ss_family) {
    663 	case AF_INET:
    664 		/* We only accept queries from the proxy. */
    665 		if (in_hosteq(satosin(&ss[0])->sin_addr,
    666 		    satosin(proxy)->sin_addr))
    667 			list = "net.inet.tcp.pcblist";
    668 		break;
    669 	case AF_INET6:
    670 		/* We only accept queries from the proxy. */
    671 		if (IN6_ARE_ADDR_EQUAL(&satosin6(&ss[0])->sin6_addr,
    672 		    &satosin6(proxy)->sin6_addr))
    673 			list = "net.inet6.tcp.pcblist";
    674 		break;
    675 	default:
    676 		maybe_syslog(LOG_ERR, "Unsupported protocol for proxy (no. %d)",
    677 		    ss[0].ss_family);
    678 	}
    679 	if (list != NULL)
    680 		rc = sysctlnametomib(list, &name[0], &sz);
    681 	if (rc == -1)
    682 		return -1;
    683 	len = sz;
    684 
    685 	name[len++] = PCB_ALL;
    686 	name[len++] = 0;
    687 	name[len++] = sizeof(struct kinfo_pcb);
    688 	name[len++] = INT_MAX;
    689 
    690 	kp = NULL;
    691 	sz = 0;
    692 	do {
    693 		rc = sysctl(&name[0], len, kp, &sz, NULL, 0);
    694 		if (rc == -1 && errno != ENOMEM)
    695 			return -1;
    696 		if (kp == NULL) {
    697 			kp = malloc(sz);
    698 			rc = -1;
    699 		}
    700 		if (kp == NULL)
    701 			return -1;
    702 	} while (rc == -1);
    703 
    704 	rc = -1;
    705 	/*
    706 	 * Walk through the list of sockets and try to find a match.
    707 	 * We don't know who has sent the query (we only know that the
    708 	 * proxy has forwarded to us) so just try to match the ports and
    709 	 * the local address.
    710 	 */
    711 	for (i = 0; i < sz / sizeof(struct kinfo_pcb); i++) {
    712 		switch (ss[0].ss_family) {
    713 		case AF_INET:
    714 			/* Foreign and local ports must match. */
    715 			if (satosin(&ss[0])->sin_port !=
    716 			    satosin(&kp[i].ki_src)->sin_port)
    717 				continue;
    718 			if (satosin(&ss[1])->sin_port !=
    719 			    satosin(&kp[i].ki_dst)->sin_port)
    720 				continue;
    721 			/* Foreign address may not match proxy address. */
    722 			if (in_hosteq(satosin(proxy)->sin_addr,
    723 			    satosin(&kp[i].ki_dst)->sin_addr))
    724 				continue;
    725 			/* Local addresses must match. */
    726 			if (!in_hosteq(satosin(&ss[1])->sin_addr,
    727 			    satosin(&kp[i].ki_src)->sin_addr))
    728 				continue;
    729 			break;
    730 		case AF_INET6:
    731 			/* Foreign and local ports must match. */
    732 			if (satosin6(&ss[0])->sin6_port !=
    733 			    satosin6(&kp[i].ki_src)->sin6_port)
    734 				continue;
    735 			if (satosin6(&ss[1])->sin6_port !=
    736 			    satosin6(&kp[i].ki_dst)->sin6_port)
    737 				continue;
    738 			/* Foreign address may not match proxy address. */
    739 			if (IN6_ARE_ADDR_EQUAL(&satosin6(proxy)->sin6_addr,
    740 			    &satosin6(&kp[i].ki_dst)->sin6_addr))
    741 				continue;
    742 			/* Local addresses must match. */
    743 			if (!IN6_ARE_ADDR_EQUAL(&satosin6(&ss[1])->sin6_addr,
    744 			    &satosin6(&kp[i].ki_src)->sin6_addr))
    745 				continue;
    746 			break;
    747 		}
    748 
    749 		/*
    750 		 * We have found the foreign address, copy it to a new
    751 		 * struct and retrieve the UID of the connection owner.
    752 		 */
    753 		(void)memcpy(&new[0], &kp[i].ki_dst, kp[i].ki_dst.sa_len);
    754 		(void)memcpy(&new[1], &kp[i].ki_src, kp[i].ki_src.sa_len);
    755 
    756 		rc = sysctl_getuid(new, sizeof(new), uid);
    757 
    758 		/* Done. */
    759 		break;
    760 	}
    761 
    762 	free(kp);
    763 	return rc;
    764 }
    765 
    766 /* Forward ident queries. Returns 1 when succesful, or zero if not. */
    767 static int
    768 forward(int fd, struct sockaddr *nat_addr, int nat_lport, int fport, int lport)
    769 {
    770 	char buf[BUFSIZ], reply[BUFSIZ], *p;
    771 	int sock, n;
    772 
    773 	/* Connect to the NAT host. */
    774 	sock = socket(nat_addr->sa_family, SOCK_STREAM, 0);
    775 	if (sock < 0) {
    776 		maybe_syslog(LOG_ERR, "socket: %m");
    777 		return 0;
    778 	}
    779 	if (connect(sock, nat_addr, nat_addr->sa_len) < 0) {
    780 		maybe_syslog(LOG_ERR, "Can't connect to %s: %m",
    781 		    gethost(nat_addr));
    782 		(void)close(sock);
    783 		return 0;
    784 	}
    785 
    786 	/*
    787 	 * Send the ident query to the NAT host, but use as local port
    788 	 * the port of the NAT host.
    789 	 */
    790 	(void)snprintf(buf, sizeof(buf), "%d , %d\r\n", nat_lport, fport);
    791 	if (send(sock, buf, strlen(buf), 0) < 0) {
    792 		maybe_syslog(LOG_ERR, "send: %m");
    793 		(void)close(sock);
    794 		return 0;
    795 	}
    796 
    797 	/* Read the reply from the NAT host. */
    798 	if ((n = recv(sock, reply, sizeof(reply) - 1, 0)) < 0) {
    799 		maybe_syslog(LOG_ERR, "recv: %m");
    800 		(void)close(sock);
    801 		return 0;
    802 	} else if (n == 0) {
    803 		maybe_syslog(LOG_NOTICE, "recv: EOF");
    804 		(void)close(sock);
    805 		return 0;
    806 	}
    807 	reply[n] = '\0';
    808 	(void)close(sock);
    809 
    810 	/* Extract everything after the port specs from the ident reply. */
    811 	for (p = reply; *p != '\0' && *p != ':'; p++)
    812 		continue;
    813 	if (*p == '\0' || *++p == '\0') {
    814 		maybe_syslog(LOG_ERR, "Malformed ident reply from %s",
    815 		    gethost(nat_addr));
    816 		return 0;
    817 	}
    818 	/* Build reply for the requesting host, use the original local port. */
    819 	(void)snprintf(buf, sizeof(buf), "%d,%d:%s", lport, fport, p);
    820 
    821 	/* Send the reply from the NAT host back to the requesting host. */
    822 	if (send(fd, buf, strlen(buf), 0) < 0) {
    823 		maybe_syslog(LOG_ERR, "send: %m");
    824 		return 0;
    825 	}
    826 
    827 	return 1;
    828 }
    829 
    830 /* Check if a .noident file exists in the user home directory. */
    831 static int
    832 check_noident(const char *homedir)
    833 {
    834 	struct stat sb;
    835 	char *path;
    836 	int ret;
    837 
    838 	if (homedir == NULL)
    839 		return 0;
    840 	if (asprintf(&path, "%s/.noident", homedir) < 0)
    841 		return 0;
    842 	ret = stat(path, &sb);
    843 
    844 	free(path);
    845 	return (ret == 0);
    846 }
    847 
    848 /*
    849  * Check if a .ident file exists in the user home directory and
    850  * return the contents of that file.
    851  */
    852 static int
    853 check_userident(const char *homedir, char *username, size_t len)
    854 {
    855 	struct stat sb;
    856 	char *path, *p;
    857 	int fd, n;
    858 
    859 	if (len == 0 || homedir == NULL)
    860 		return 0;
    861 	if (asprintf(&path, "%s/.ident", homedir) < 0)
    862 		return 0;
    863 	if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_NOFOLLOW, 0)) < 0) {
    864 		free(path);
    865 		return 0;
    866 	}
    867 	if (fstat(fd, &sb) < 0 || !S_ISREG(sb.st_mode)) {
    868 		(void)close(fd);
    869 		free(path);
    870 		return 0;
    871 	}
    872 	if ((n = read(fd, username, len - 1)) < 1) {
    873 		(void)close(fd);
    874 		free(path);
    875 		return 0;
    876 	}
    877 	username[n] = '\0';
    878 
    879 	if ((p = strpbrk(username, "\r\n")) != NULL)
    880 		*p = '\0';
    881 
    882 	(void)close(fd);
    883 	free(path);
    884 	return 1;
    885 }
    886 
    887 /* Generate a random string. */
    888 static void
    889 random_string(char *str, size_t len)
    890 {
    891 	static const char chars[] = "abcdefghijklmnopqrstuvwxyz1234567890";
    892 	char *p;
    893 
    894 	if (len == 0)
    895 		return;
    896 	for (p = str; len > 1; len--)
    897 		*p++ = chars[arc4random() % (sizeof(chars) - 1)];
    898 	*p = '\0';
    899 }
    900 
    901 /* Change the output format. */
    902 static int
    903 change_format(const char *format, struct passwd *pw, char *dest, size_t len)
    904 {
    905 	struct group *gr;
    906 	const char *cp;
    907 	char **gmp;
    908 	int bp;
    909 
    910 	if (len == 0 || ((gr = getgrgid(pw->pw_gid)) == NULL))
    911 		return 0;
    912 
    913 	for (bp = 0, cp = format; *cp != '\0' && bp < 490; cp++) {
    914 		if (*cp != '%') {
    915 			dest[bp++] = *cp;
    916 			continue;
    917 		}
    918 		if (*++cp == '\0')
    919 			break;
    920 		switch (*cp) {
    921 		case 'u':
    922 			(void)snprintf(&dest[bp], len - bp, "%.*s", 490 - bp,
    923 			    pw->pw_name);
    924 			break;
    925 		case 'U':
    926 			(void)snprintf(&dest[bp], len - bp, "%d", pw->pw_uid);
    927 			break;
    928 		case 'g':
    929 			(void)snprintf(&dest[bp], len - bp, "%.*s", 490 - bp,
    930 			    gr->gr_name);
    931 			break;
    932 		case 'G':
    933 			(void)snprintf(&dest[bp], len - bp, "%d", gr->gr_gid);
    934 			break;
    935 		case 'l':
    936 			(void)snprintf(&dest[bp], len - bp, "%.*s", 490 - bp,
    937 			    gr->gr_name);
    938 			bp += strlen(&dest[bp]);
    939 			if (bp >= 490)
    940 				break;
    941 			setgrent();
    942 			while ((gr = getgrent()) != NULL) {
    943 				if (gr->gr_gid == pw->pw_gid)
    944 					continue;
    945 				for (gmp = gr->gr_mem; *gmp && **gmp; gmp++) {
    946 					if (strcmp(*gmp, pw->pw_name) == 0) {
    947 						(void)snprintf(&dest[bp],
    948 						    len - bp, ",%.*s",
    949 						    490 - bp, gr->gr_name);
    950 						bp += strlen(&dest[bp]);
    951 						break;
    952 					}
    953 				}
    954 				if (bp >= 490)
    955 					break;
    956 			}
    957 			endgrent();
    958 			break;
    959 		case 'L':
    960 			(void)snprintf(&dest[bp], len - bp, "%u", gr->gr_gid);
    961 			bp += strlen(&dest[bp]);
    962 			if (bp >= 490)
    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, ",%u",
    972 						    gr->gr_gid);
    973 						bp += strlen(&dest[bp]);
    974 						break;
    975 					}
    976 				}
    977 				if (bp >= 490)
    978 					break;
    979 			}
    980 			endgrent();
    981 			break;
    982 		default:
    983 			dest[bp] = *cp;
    984 			dest[bp+1] = '\0';
    985 			break;
    986 		}
    987 		bp += strlen(&dest[bp]);
    988 	}
    989 	if (bp >= 490) {
    990 		(void)snprintf(&dest[490], len - 490, "...");
    991 		bp = 493;
    992 	}
    993 	dest[bp] = '\0';
    994 
    995 	return 1;
    996 }
    997 
    998 /* Just exit when we caught SIGALRM. */
    999 static void
   1000 timeout_handler(int s)
   1001 {
   1002 	maybe_syslog(LOG_DEBUG, "SIGALRM triggered, exiting...");
   1003 	exit(EXIT_FAILURE);
   1004 }
   1005 
   1006 /* Report error message string through syslog and quit. */
   1007 static void
   1008 fatal(const char *func)
   1009 {
   1010 	maybe_syslog(LOG_ERR, "%s: %m", func);
   1011 	exit(EXIT_FAILURE);
   1012 }
   1013 
   1014 /*
   1015  * Report an error through syslog and/or stderr and quit.  Only used when
   1016  * running identd in the background and when it isn't a daemon yet.
   1017  */
   1018 static void
   1019 die(const char *message, ...)
   1020 {
   1021 	va_list ap;
   1022 
   1023 	va_start(ap, message);
   1024 	if (bflag)
   1025 		vwarnx(message, ap);
   1026 	if (lflag)
   1027 		vsyslog(LOG_ERR, message, ap);
   1028 	va_end(ap);
   1029 
   1030 	exit(EXIT_FAILURE);
   1031 }
   1032 
   1033 /* Log using syslog, but only if enabled with the -l flag. */
   1034 void
   1035 maybe_syslog(int priority, const char *message, ...)
   1036 {
   1037 	va_list ap;
   1038 
   1039 	if (lflag) {
   1040 		va_start(ap, message);
   1041 		vsyslog(priority, message, ap);
   1042 		va_end(ap);
   1043 	}
   1044 }
   1045