identd.c revision 1.20 1 /* $NetBSD: identd.c,v 1.20 2004/01/31 21:47:17 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) pointless.nl>
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 #include <sys/wait.h>
16
17 #include <netinet/in.h>
18 #include <netinet/ip_var.h>
19 #include <netinet/tcp.h>
20 #include <netinet/tcp_timer.h>
21 #include <netinet/tcp_var.h>
22
23 #include <arpa/inet.h>
24
25 #include <ctype.h>
26 #include <err.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <grp.h>
30 #include <netdb.h>
31 #include <poll.h>
32 #include <pwd.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <syslog.h>
38 #include <unistd.h>
39
40 #define OPSYS_NAME "UNIX"
41 #define IDENT_SERVICE "auth"
42 #define TIMEOUT 30 /* seconds */
43
44 static int idhandle(int, const char *, const char *, const char *,
45 const char *, int);
46 static void idparse(int, int, int, const char *, const char *, const char *);
47 static void iderror(int, int, int, const char *);
48 static const char *gethost(struct sockaddr_storage *);
49 static int *socketsetup(const char *, const char *, int);
50 static int sysctl_getuid(struct sockaddr_storage *, socklen_t, uid_t *);
51 static int check_noident(const char *);
52 static int check_userident(const char *, char *, size_t);
53 static void random_string(char *, size_t);
54 static void change_format(const char *, struct passwd *, char *, size_t);
55 static void timeout_handler(int);
56 static void waitchild(int);
57 static void fatal(const char *);
58
59 static int bflag, eflag, fflag, Fflag, iflag, Iflag;
60 static int lflag, Lflag, nflag, Nflag, rflag;
61
62 int
63 main(int argc, char *argv[])
64 {
65 int IPv4or6, ch, *socks, timeout;
66 char *address, *charset, *fmt;
67 const char *osname, *portno;
68 char *p;
69 char user[LOGIN_NAME_MAX];
70 struct group *grp;
71 struct passwd *pw;
72 gid_t gid;
73 uid_t uid;
74
75 IPv4or6 = AF_UNSPEC;
76 osname = OPSYS_NAME;
77 portno = IDENT_SERVICE;
78 timeout = TIMEOUT;
79 address = NULL;
80 charset = NULL;
81 fmt = NULL;
82 socks = NULL;
83 gid = uid = 0;
84 bflag = eflag = fflag = Fflag = iflag = Iflag = 0;
85 lflag = Lflag = nflag = Nflag = rflag = 0;
86
87 /* Started from a tty? then run as daemon */
88 if (isatty(0))
89 bflag = 1;
90
91 /* Parse arguments */
92 while ((ch = getopt(argc, argv, "46a:bceF:f:g:IiL:lNno:p:rt:u:")) != -1)
93 switch (ch) {
94 case '4':
95 IPv4or6 = AF_INET;
96 break;
97 case '6':
98 IPv4or6 = AF_INET6;
99 break;
100 case 'a':
101 address = optarg;
102 break;
103 case 'b':
104 bflag = 1;
105 break;
106 case 'c':
107 charset = optarg;
108 break;
109 case 'e':
110 eflag = 1;
111 break;
112 case 'F':
113 Fflag = 1;
114 fmt = optarg;
115 break;
116 case 'f':
117 fflag = 1;
118 (void)strlcpy(user, optarg, sizeof(user));
119 break;
120 case 'g':
121 gid = (gid_t)strtol(optarg, &p, 0);
122 if (*p != '\0') {
123 if ((grp = getgrnam(optarg)) != NULL)
124 gid = grp->gr_gid;
125 else
126 errx(1, "No such group '%s'", optarg);
127 }
128 break;
129 case 'I':
130 Iflag = 1;
131 /* FALLTHROUGH */
132 case 'i':
133 iflag = 1;
134 break;
135 case 'L':
136 Lflag = 1;
137 (void)strlcpy(user, optarg, sizeof(user));
138 break;
139 case 'l':
140 lflag = 1;
141 break;
142 case 'N':
143 Nflag = 1;
144 break;
145 case 'n':
146 nflag = 1;
147 break;
148 case 'o':
149 osname = optarg;
150 break;
151 case 'p':
152 portno = optarg;
153 break;
154 case 'r':
155 rflag = 1;
156 break;
157 case 't':
158 timeout = (int)strtol(optarg, &p, 0);
159 if (*p != '\0')
160 errx(1, "Invalid timeout value '%s'", optarg);
161 break;
162 case 'u':
163 uid = (uid_t)strtol(optarg, &p, 0);
164 if (*p != '\0') {
165 if ((pw = getpwnam(optarg)) != NULL) {
166 uid = pw->pw_uid;
167 gid = pw->pw_gid;
168 } else
169 errx(1, "No such user '%s'", optarg);
170 }
171 break;
172 default:
173 exit(1);
174 }
175
176 if (lflag)
177 openlog("identd", LOG_PID, LOG_DAEMON);
178
179 /* Setup sockets if -b flag */
180 if (bflag) {
181 socks = socketsetup(address, portno, IPv4or6);
182 if (socks == NULL)
183 return 1;
184 }
185
186 /* Switch to another uid/gid ? */
187 if (gid && setgid(gid) == -1) {
188 if (lflag)
189 syslog(LOG_ERR, "setgid: %m");
190 if (bflag)
191 warn("setgid");
192 exit(1);
193 }
194 if (uid && setuid(uid) == -1) {
195 if (lflag)
196 syslog(LOG_ERR, "setuid: %m");
197 if (bflag)
198 warn("setuid");
199 exit(1);
200 }
201
202 /* Daemonize, setup pollfds and start mainloop if -b flag */
203 if (bflag) {
204 int fd, i, nfds, rv;
205 struct pollfd *rfds;
206
207 (void)signal(SIGCHLD, waitchild);
208 (void)daemon(0, 0);
209
210 rfds = malloc(*socks * sizeof(struct pollfd));
211 if (rfds == NULL)
212 fatal("malloc");
213 nfds = *socks;
214 for (i = 0; i < nfds; i++) {
215 rfds[i].fd = socks[i+1];
216 rfds[i].events = POLLIN;
217 rfds[i].revents = 0;
218 }
219 /* Mainloop for daemon */
220 for (;;) {
221 rv = poll(rfds, nfds, INFTIM);
222 if (rv < 0 && errno == EINTR)
223 continue;
224 if (rv < 0)
225 fatal("poll");
226 for (i = 0; i < nfds; i++) {
227 if (rfds[i].revents & POLLIN) {
228 fd = accept(rfds[i].fd, NULL, NULL);
229 if (fd < 0) {
230 if (lflag)
231 syslog(LOG_ERR,
232 "accept: %m");
233 continue;
234 }
235 switch (fork()) {
236 case -1: /* error */
237 if (lflag)
238 syslog(LOG_ERR,
239 "fork: %m");
240 (void)sleep(1);
241 break;
242 case 0: /* child */
243 (void)idhandle(fd, charset,
244 fmt, osname, user, timeout);
245 _exit(0);
246 default: /* parent */
247 (void)close(fd);
248 }
249 }
250 }
251 }
252 } else
253 (void)idhandle(STDIN_FILENO, charset, fmt, osname, user,
254 timeout);
255
256 return 0;
257 }
258
259 static int
260 idhandle(int fd, const char *charset, const char *fmt, const char *osname,
261 const char *user, int timeout)
262 {
263 struct sockaddr_storage ss[2];
264 char userbuf[LOGIN_NAME_MAX];
265 char idbuf[LOGIN_NAME_MAX];
266 char buf[BUFSIZ], *p;
267 int n, lport, fport;
268 struct passwd *pw;
269 socklen_t len;
270 uid_t uid;
271
272 lport = fport = 0;
273
274 (void)strlcpy(idbuf, user, sizeof(idbuf));
275 (void)signal(SIGALRM, timeout_handler);
276 (void)alarm(timeout);
277
278 /* Get foreign internet address */
279 len = sizeof(ss[0]);
280 if (getpeername(fd, (struct sockaddr *)&ss[0], &len) < 0)
281 fatal("getpeername");
282
283 if (lflag)
284 syslog(LOG_INFO, "Connection from %s", gethost(&ss[0]));
285
286 /* Get local internet address */
287 len = sizeof(ss[1]);
288 if (getsockname(fd, (struct sockaddr *)&ss[1], &len) < 0)
289 fatal("getsockname");
290
291 /* Be sure to have the same address family's */
292 if (ss[0].ss_family != ss[1].ss_family) {
293 if (lflag)
294 syslog(LOG_ERR, "Foreign/local AF are different!");
295 return 1;
296 }
297
298 /* Receive data from the client */
299 if ((n = recv(fd, buf, sizeof(buf) - 1, 0)) < 0) {
300 fatal("recv");
301 } else if (n == 0) {
302 if (lflag)
303 syslog(LOG_NOTICE, "recv: EOF");
304 iderror(fd, 0, 0, "UNKNOWN-ERROR");
305 return 1;
306 }
307 buf[n] = '\0';
308
309 /* Get local and remote ports from the received data */
310 p = buf;
311 while (*p != '\0' && isspace(*p))
312 p++;
313 if ((p = strtok(p, " \t,")) != NULL) {
314 lport = atoi(p);
315 if ((p = strtok(NULL, " \t,")) != NULL)
316 fport = atoi(p);
317 }
318
319 /* Are the ports valid? */
320 if (lport < 1 || lport > 65535 || fport < 1 || fport > 65535) {
321 if (lflag)
322 syslog(LOG_NOTICE, "Invalid port(s): %d, %d from %s",
323 lport, fport, gethost(&ss[0]));
324 iderror(fd, 0, 0, eflag ? "UNKNOWN-ERROR" : "INVALID-PORT");
325 return 1;
326 }
327
328 /* If there is a 'lie' user enabled, then handle it now and quit */
329 if (Lflag) {
330 if (lflag)
331 syslog(LOG_NOTICE, "Lying with name %s to %s",
332 idbuf, gethost(&ss[0]));
333 idparse(fd, lport, fport, charset, osname, idbuf);
334 return 0;
335 }
336
337 /* Protocol dependent stuff */
338 switch (ss[0].ss_family) {
339 case AF_INET:
340 ((struct sockaddr_in *)&ss[0])->sin_port = htons(fport);
341 ((struct sockaddr_in *)&ss[1])->sin_port = htons(lport);
342 break;
343 case AF_INET6:
344 ((struct sockaddr_in6 *)&ss[0])->sin6_port = htons(fport);
345 ((struct sockaddr_in6 *)&ss[1])->sin6_port = htons(lport);
346 break;
347 default:
348 if (lflag)
349 syslog(LOG_ERR, "Unsupported protocol, proto no. %d",
350 ss[0].ss_family);
351 return 1;
352 }
353
354 /* Do sysctl call */
355 if (sysctl_getuid(ss, sizeof(ss), &uid) == -1) {
356 if (lflag)
357 syslog(LOG_ERR, "sysctl: %m");
358 if (fflag) {
359 if (lflag)
360 syslog(LOG_NOTICE, "Using fallback name %s "
361 "to %s", idbuf, gethost(&ss[0]));
362 idparse(fd, lport, fport, charset, osname, idbuf);
363 return 0;
364 }
365 iderror(fd, lport, fport, eflag ? "UNKNOWN-ERROR" : "NO-USER");
366 return 1;
367 }
368
369 /* Get username with the uid */
370 if ((pw = getpwuid(uid)) == NULL) {
371 if (lflag)
372 syslog(LOG_ERR, "Couldn't map uid (%u) to name", uid);
373 (void)snprintf(idbuf, sizeof(idbuf), "%u", uid);
374 idparse(fd, lport, fport, charset, osname, idbuf);
375 return 0;
376 }
377
378 if (lflag)
379 syslog(LOG_INFO, "Successfull lookup: %d, %d: %s for %s",
380 lport, fport, pw->pw_name, gethost(&ss[0]));
381
382 /* No ident enabled? */
383 if (Nflag && check_noident(pw->pw_dir)) {
384 if (lflag)
385 syslog(LOG_NOTICE, "Returning HIDDEN-USER for user %s"
386 " to %s", pw->pw_name, gethost(&ss[0]));
387 iderror(fd, lport, fport, "HIDDEN-USER");
388 return 1;
389 }
390
391 /* User ident enabled ? */
392 if (iflag && check_userident(pw->pw_dir, idbuf, sizeof(idbuf))) {
393 (void)strlcpy(userbuf, pw->pw_name, sizeof(userbuf));
394 if (!Iflag) {
395 if (strspn(idbuf, "0123456789") &&
396 getpwuid(atoi(idbuf)) != NULL)
397 (void)strlcpy(idbuf, userbuf, sizeof(idbuf));
398 else if (getpwnam(idbuf) != NULL)
399 (void)strlcpy(idbuf, userbuf, sizeof(idbuf));
400 }
401 if (lflag)
402 syslog(LOG_NOTICE, "Returning user specified '%s' for "
403 "user %s to %s", idbuf, userbuf, gethost(&ss[0]));
404 idparse(fd, lport, fport, charset, osname, idbuf);
405 return 0;
406 }
407
408 /* Send random crap? */
409 if (rflag) {
410 /* Random number or string? */
411 if (nflag)
412 (void)snprintf(idbuf, sizeof(idbuf), "%u",
413 (unsigned int)(arc4random() % 65535));
414 else
415 random_string(idbuf, sizeof(idbuf));
416
417 if (lflag)
418 syslog(LOG_NOTICE, "Returning random '%s' for user %s"
419 " to %s", idbuf, pw->pw_name, gethost(&ss[0]));
420 idparse(fd, lport, fport, charset, osname, idbuf);
421 return 0;
422 }
423
424 /* Return number? */
425 if (nflag)
426 (void)snprintf(idbuf, sizeof(idbuf), "%u", uid);
427 else
428 (void)strlcpy(idbuf, pw->pw_name, sizeof(idbuf));
429
430 if (Fflag) {
431 /* RFC 1413 says that 512 is the limit */
432 change_format(fmt, pw, buf, 512);
433 idparse(fd, lport, fport, charset, osname, buf);
434 } else
435 idparse(fd, lport, fport, charset, osname, idbuf);
436
437 return 0;
438 }
439
440 /* Send/parse the ident result */
441 static void
442 idparse(int fd, int lport, int fport, const char *charset, const char *osname,
443 const char *user)
444 {
445 char *p;
446
447 if (asprintf(&p, "%d , %d : USERID : %s%s%s : %s\r\n", lport, fport,
448 osname, charset ? " , " : "", charset ? charset : "", user) < 0)
449 fatal("asprintf");
450 if (send(fd, p, strlen(p), 0) < 0) {
451 free(p);
452 fatal("send");
453 }
454 free(p);
455 }
456
457 /* Return a specified ident error */
458 static void
459 iderror(int fd, int lport, int fport, const char *error)
460 {
461 char *p;
462
463 if (asprintf(&p, "%d , %d : ERROR : %s\r\n", lport, fport, error) < 0)
464 fatal("asprintf");
465 if (send(fd, p, strlen(p), 0) < 0) {
466 free(p);
467 fatal("send");
468 }
469 free(p);
470 }
471
472 /* Return the IP address of the connecting host */
473 static const char *
474 gethost(struct sockaddr_storage *ss)
475 {
476 static char host[NI_MAXHOST];
477
478 if (getnameinfo((struct sockaddr *)ss, ss->ss_len, host,
479 sizeof(host), NULL, 0, NI_NUMERICHOST) == 0)
480 return host;
481
482 return "UNKNOWN";
483 }
484
485 /* Setup sockets, for daemon mode */
486 static int *
487 socketsetup(const char *address, const char *port, int af)
488 {
489 struct addrinfo hints, *res, *res0;
490 int error, maxs, *s, *socks, y = 1;
491 const char *cause = NULL;
492
493 (void)memset(&hints, 0, sizeof(hints));
494 hints.ai_flags = AI_PASSIVE;
495 hints.ai_family = af;
496 hints.ai_socktype = SOCK_STREAM;
497 error = getaddrinfo(address, port, &hints, &res0);
498 if (error) {
499 if (lflag)
500 syslog(LOG_ERR, "getaddrinfo: %s", gai_strerror(error));
501 errx(1, "%s", gai_strerror(error));
502 /*NOTREACHED*/
503 }
504
505 /* Count max number of sockets we may open */
506 for (maxs = 0, res = res0; res != NULL; res = res->ai_next)
507 maxs++;
508
509 socks = malloc((maxs + 1) * sizeof(int));
510 if (socks == NULL) {
511 if (lflag)
512 syslog(LOG_ERR, "malloc: %m");
513 err(1, "malloc");
514 /* NOTREACHED */
515 }
516
517 *socks = 0;
518 s = socks + 1;
519 for (res = res0; res != NULL; res = res->ai_next) {
520 *s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
521 if (*s < 0) {
522 cause = "socket";
523 continue;
524 }
525 (void)setsockopt(*s, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(y));
526 if (bind(*s, res->ai_addr, res->ai_addrlen) < 0) {
527 cause = "bind";
528 (void)close(*s);
529 continue;
530 }
531 if (listen(*s, 5) < 0) {
532 cause = "listen";
533 (void)close(*s);
534 continue;
535 }
536 *socks = *socks + 1;
537 s++;
538 }
539
540 if (*socks == 0) {
541 free(socks);
542 if (lflag)
543 syslog(LOG_ERR, "%s: %m", cause);
544 err(1, "%s", cause);
545 /* NOTREACHED */
546 }
547 if (res0)
548 freeaddrinfo(res0);
549
550 return socks;
551 }
552
553 /* Return the UID for the connection owner */
554 static int
555 sysctl_getuid(struct sockaddr_storage *ss, socklen_t len, uid_t *uid)
556 {
557 int mib[4];
558 uid_t myuid;
559 size_t uidlen;
560
561 uidlen = sizeof(myuid);
562
563 mib[0] = CTL_NET;
564 mib[1] = ss->ss_family;
565 mib[2] = IPPROTO_TCP;
566 mib[3] = TCPCTL_IDENT;
567
568 if (sysctl(mib, sizeof(mib)/ sizeof(int), &myuid, &uidlen, ss, len) < 0)
569 return -1;
570 *uid = myuid;
571
572 return 0;
573 }
574
575 /* Check if a .noident file exists in the user home directory */
576 static int
577 check_noident(const char *homedir)
578 {
579 struct stat sb;
580 char *path;
581 int ret;
582
583 if (homedir == NULL)
584 return 0;
585 if (asprintf(&path, "%s/.noident", homedir) < 0)
586 return 0;
587 ret = stat(path, &sb);
588
589 free(path);
590 return (ret == 0);
591 }
592
593 /*
594 * Check if a .ident file exists in the user home directory and
595 * return the contents of that file.
596 */
597 static int
598 check_userident(const char *homedir, char *username, size_t len)
599 {
600 struct stat sb;
601 char *path, *p;
602 int fd, n;
603
604 if (len == 0 || homedir == NULL)
605 return 0;
606 if (asprintf(&path, "%s/.ident", homedir) < 0)
607 return 0;
608 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_NOFOLLOW, 0)) < 0) {
609 free(path);
610 return 0;
611 }
612 if (fstat(fd, &sb) < 0 || !S_ISREG(sb.st_mode)) {
613 (void)close(fd);
614 free(path);
615 return 0;
616 }
617 if ((n = read(fd, username, len - 1)) < 1) {
618 (void)close(fd);
619 free(path);
620 return 0;
621 }
622 username[n] = '\0';
623
624 if ((p = strpbrk(username, "\r\n")))
625 *p = '\0';
626
627 (void)close(fd);
628 free(path);
629 return 1;
630 }
631
632 /* Generate a random string */
633 static void
634 random_string(char *str, size_t len)
635 {
636 static const char chars[] = "abcdefghijklmnopqrstuvwxyz1234567890";
637 char *p;
638
639 if (len == 0)
640 return;
641 for (p = str; len > 1; len--)
642 *p++ = chars[arc4random() % (sizeof(chars) - 1)];
643 *p = '\0';
644 }
645
646 /* Change the output format */
647 static void
648 change_format(const char *format, struct passwd *pw, char *dest, size_t len)
649 {
650 struct group *gr;
651 const char *cp;
652 char **gmp;
653 int bp;
654
655 if (len == 0)
656 return;
657 if ((gr = getgrgid(pw->pw_gid)) == NULL)
658 return;
659
660 for (bp = 0, cp = format; *cp != '\0' && bp < 490; cp++) {
661 if (*cp != '%') {
662 dest[bp++] = *cp;
663 continue;
664 }
665 if (*++cp == '\0')
666 break;
667 switch (*cp) {
668 case 'u':
669 (void)snprintf(&dest[bp], len - bp, "%.*s", 490 - bp,
670 pw->pw_name);
671 break;
672 case 'U':
673 (void)snprintf(&dest[bp], len - bp, "%d", pw->pw_uid);
674 break;
675 case 'g':
676 (void)snprintf(&dest[bp], len - bp, "%.*s", 490 - bp,
677 gr->gr_name);
678 break;
679 case 'G':
680 (void)snprintf(&dest[bp], len - bp, "%d", gr->gr_gid);
681 break;
682 case 'l':
683 (void)snprintf(&dest[bp], len - bp, "%.*s", 490 - bp,
684 gr->gr_name);
685 bp += strlen(&dest[bp]);
686 if (bp >= 490)
687 break;
688 setgrent();
689 while ((gr = getgrent()) != NULL) {
690 if (gr->gr_gid == pw->pw_gid)
691 continue;
692 for (gmp = gr->gr_mem; *gmp && **gmp; gmp++) {
693 if (strcmp(*gmp, pw->pw_name) == 0) {
694 (void)snprintf(&dest[bp],
695 len - bp, ",%.*s",
696 490 - bp, gr->gr_name);
697 bp += strlen(&dest[bp]);
698 break;
699 }
700 }
701 if (bp >= 490)
702 break;
703 }
704 endgrent();
705 break;
706 case 'L':
707 (void)snprintf(&dest[bp], len - bp, "%u", gr->gr_gid);
708 bp += strlen(&dest[bp]);
709 if (bp >= 490)
710 break;
711 setgrent();
712 while ((gr = getgrent()) != NULL) {
713 if (gr->gr_gid == pw->pw_gid)
714 continue;
715 for (gmp = gr->gr_mem; *gmp && **gmp; gmp++) {
716 if (strcmp(*gmp, pw->pw_name) == 0) {
717 (void)snprintf(&dest[bp],
718 len - bp, ",%u",
719 gr->gr_gid);
720 bp += strlen(&dest[bp]);
721 break;
722 }
723 }
724 if (bp >= 490)
725 break;
726 }
727 endgrent();
728 break;
729 default:
730 dest[bp] = *cp;
731 dest[bp+1] = '\0';
732 break;
733 }
734 bp += strlen(&dest[bp]);
735 }
736 if (bp >= 490) {
737 (void)snprintf(&dest[490], len - 490, "...");
738 bp = 493;
739 }
740 dest[bp] = '\0';
741 }
742
743 /* Just exit when we caught SIGALRM */
744 static void
745 timeout_handler(int s)
746 {
747 if (lflag)
748 syslog(LOG_DEBUG, "SIGALRM triggered, exiting...");
749 exit(1);
750 }
751
752 /* This is to clean up zombie processes when in daemon mode */
753 static void
754 waitchild(int s)
755 {
756 while (waitpid(-1, NULL, WNOHANG) > 0)
757 continue;
758 }
759
760 /* Report errno through syslog and quit */
761 static void
762 fatal(const char *func)
763 {
764 if (lflag)
765 syslog(LOG_ERR, "%s: %m", func);
766 exit(1);
767 }
768