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