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