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