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