2 * Copyright (c) 1983, 1991, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * $FreeBSD: src/usr.sbin/inetd/builtins.c,v 1.19.2.7 2002/07/22 14:05:56 fanf Exp $
30 #include <sys/filio.h>
31 #include <sys/param.h>
33 #include <sys/socket.h>
34 #include <sys/sysctl.h>
35 #include <sys/ucred.h>
37 #include <sys/utsname.h>
54 void chargen_dg(int, struct servtab *);
55 void chargen_stream(int, struct servtab *) __dead2;
56 void daytime_dg(int, struct servtab *);
57 void daytime_stream(int, struct servtab *);
58 void discard_dg(int, struct servtab *);
59 void discard_stream(int, struct servtab *) __dead2;
60 void echo_dg(int, struct servtab *);
61 void echo_stream(int, struct servtab *) __dead2;
62 static int get_line(int, char *, int);
63 void iderror(int, int, int, const char *) __dead2;
64 void ident_stream(int, struct servtab *) __dead2;
66 unsigned long machtime(void);
67 void machtime_dg(int, struct servtab *);
68 void machtime_stream(int, struct servtab *);
74 struct biltin biltins[] = {
75 /* Echo received data */
76 { "echo", SOCK_STREAM, 1, -1, echo_stream },
77 { "echo", SOCK_DGRAM, 0, 1, echo_dg },
79 /* Internet /dev/null */
80 { "discard", SOCK_STREAM, 1, -1, discard_stream },
81 { "discard", SOCK_DGRAM, 0, 1, discard_dg },
83 /* Return 32 bit time since 1900 */
84 { "time", SOCK_STREAM, 0, -1, machtime_stream },
85 { "time", SOCK_DGRAM, 0, 1, machtime_dg },
87 /* Return human-readable time */
88 { "daytime", SOCK_STREAM, 0, -1, daytime_stream },
89 { "daytime", SOCK_DGRAM, 0, 1, daytime_dg },
91 /* Familiar character generator */
92 { "chargen", SOCK_STREAM, 1, -1, chargen_stream },
93 { "chargen", SOCK_DGRAM, 0, 1, chargen_dg },
95 { "tcpmux", SOCK_STREAM, 1, -1, (bi_fn_t *)tcpmux },
97 { "auth", SOCK_STREAM, 1, -1, ident_stream },
99 { NULL, 0, 0, 0, NULL }
103 * RFC864 Character Generator Protocol. Generates character data without
104 * any regard for input.
114 for (i = 0; i <= 128; ++i)
121 chargen_dg(int s, struct servtab *sep) /* Character generator */
123 struct sockaddr_storage ss;
127 char text[LINESIZ+2];
129 if (endring == NULL) {
135 if (recvfrom(s, text, sizeof(text), 0,
136 (struct sockaddr *)&ss, &size) < 0)
139 if (check_loop((struct sockaddr *)&ss, sep))
142 if ((len = endring - rs) >= LINESIZ)
143 memmove(text, rs, LINESIZ);
145 memmove(text, rs, len);
146 memmove(text + len, ring, LINESIZ - len);
150 text[LINESIZ] = '\r';
151 text[LINESIZ + 1] = '\n';
152 sendto(s, text, sizeof(text), 0, (struct sockaddr *)&ss, size);
157 chargen_stream(int s, struct servtab *sep) /* Character generator */
160 char *rs, text[LINESIZ+2];
162 inetd_setproctitle(sep->se_service, s);
169 text[LINESIZ] = '\r';
170 text[LINESIZ + 1] = '\n';
172 if ((len = endring - rs) >= LINESIZ)
173 memmove(text, rs, LINESIZ);
175 memmove(text, rs, len);
176 memmove(text + len, ring, LINESIZ - len);
180 if (write(s, text, sizeof(text)) != sizeof(text))
187 * RFC867 Daytime Protocol. Sends the current date and time as an ascii
188 * character string without any regard for input.
193 daytime_dg(int s, struct servtab *sep) /* Return human-readable time of day */
197 struct sockaddr_storage ss;
203 if (recvfrom(s, buffer, sizeof(buffer), 0,
204 (struct sockaddr *)&ss, &size) < 0)
207 if (check_loop((struct sockaddr *)&ss, sep))
210 sprintf(buffer, "%.24s\r\n", ctime(&now));
211 sendto(s, buffer, strlen(buffer), 0, (struct sockaddr *)&ss, size);
216 daytime_stream(int s, struct servtab *sep __unused) /* Return human-readable time of day */
223 sprintf(buffer, "%.24s\r\n", ctime(&now));
224 send(s, buffer, strlen(buffer), MSG_EOF);
228 * RFC863 Discard Protocol. Any data received is thrown away and no response
234 discard_dg(int s, struct servtab *sep __unused) /* Discard service -- ignore data */
236 char buffer[BUFSIZE];
238 read(s, buffer, sizeof(buffer));
243 discard_stream(int s, struct servtab *sep) /* Discard service -- ignore data */
246 char buffer[BUFSIZE];
248 inetd_setproctitle(sep->se_service, s);
250 while ((ret = read(s, buffer, sizeof(buffer))) > 0)
252 if (ret == 0 || errno != EINTR)
259 * RFC862 Echo Protocol. Any data received is sent back to the sender as
265 echo_dg(int s, struct servtab *sep) /* Echo service -- echo data back */
267 char buffer[65536]; /* Should be sizeof(max datagram). */
270 struct sockaddr_storage ss;
273 if ((i = recvfrom(s, buffer, sizeof(buffer), 0,
274 (struct sockaddr *)&ss, &size)) < 0)
277 if (check_loop((struct sockaddr *)&ss, sep))
280 sendto(s, buffer, i, 0, (struct sockaddr *)&ss, size);
285 echo_stream(int s, struct servtab *sep) /* Echo service -- echo data back */
287 char buffer[BUFSIZE];
290 inetd_setproctitle(sep->se_service, s);
291 while ((i = read(s, buffer, sizeof(buffer))) > 0 &&
292 write(s, buffer, i) > 0)
298 * RFC1413 Identification Protocol. Given a TCP port number pair, return a
299 * character string which identifies the owner of that connection on the
300 * server's system. Extended to allow for ~/.fakeid support and ~/.noident
304 /* RFC 1413 says the following are the only errors you can return. */
305 #define ID_INVALID "INVALID-PORT" /* Port number improperly specified. */
306 #define ID_NOUSER "NO-USER" /* Port not in use/not identifable. */
307 #define ID_HIDDEN "HIDDEN-USER" /* Hiden at user's request. */
308 #define ID_UNKNOWN "UNKNOWN-ERROR" /* Everything else. */
312 iderror(int lport, int fport, int s, const char *er) /* Generic ident_stream error-sending func */
316 asprintf(&p, "%d , %d : ERROR : %s\r\n", lport, fport, er);
318 syslog(LOG_ERR, "asprintf: %m");
321 send(s, p, strlen(p), MSG_EOF);
329 ident_stream(int s, struct servtab *sep) /* Ident service (AKA "auth") */
333 struct sockaddr_in sin4[2];
335 struct sockaddr_in6 sin6[2];
337 struct sockaddr_storage ss[2];
339 struct timeval tv = {
343 struct passwd *pw = NULL;
345 char buf[BUFSIZE], *p, **av, *osname = NULL, e;
346 char idbuf[MAXLOGNAME] = ""; /* Big enough to hold uid in decimal. */
350 int c, fflag = 0, nflag = 0, rflag = 0, argc = 0;
351 int gflag = 0, iflag = 0, Fflag = 0, getcredfail = 0, onreadlen;
352 u_short lport, fport;
354 inetd_setproctitle(sep->se_service, s);
356 * Reset getopt() since we are a fork() but not an exec() from
357 * a parent which used getopt() already.
362 * Take the internal argument vector and count it out to make an
363 * argument count for getopt. This can be used for any internal
364 * service to read arguments and use getopt() easily.
366 for (av = sep->se_argv; *av; av++)
373 while ((c = getopt(argc, sep->se_argv, "d:fFgino:rt:")) != -1)
377 strlcpy(idbuf, optarg, sizeof(idbuf));
388 rnd32 = 0; /* Shush, compiler. */
390 * The number of bits in "rnd32" divided
391 * by the number of bits needed per iteration
392 * gives a more optimal way to reload the
393 * random number only when necessary.
395 * 32 bits from arc4random corresponds to
396 * about 6 base-36 digits, so we reseed evey 6.
398 for (i = 0; i < sizeof(idbuf) - 1; i++) {
399 static const char *const base36 =
401 "abcdefghijklmnopqrstuvwxyz";
403 rnd32 = arc4random();
404 idbuf[i] = base36[rnd32 % 36];
422 switch (sscanf(optarg, "%d.%d", &sec, &usec)) {
431 warnx("bad -t argument");
439 if (osname == NULL) {
440 if (uname(&un) == -1)
441 iderror(0, 0, s, ID_UNKNOWN);
446 * We're going to prepare for and execute reception of a
447 * packet of data from the user. The data is in the format
448 * "local_port , foreign_port\r\n" (with local being the
449 * server's port and foreign being the client's.)
451 gettimeofday(&to, NULL);
452 to.tv_sec += tv.tv_sec;
453 to.tv_usec += tv.tv_usec;
454 if (to.tv_usec >= 1000000) {
455 to.tv_usec -= 1000000;
460 bufsiz = sizeof(buf) - 1;
463 gettimeofday(&tv, NULL);
464 tv.tv_sec = to.tv_sec - tv.tv_sec;
465 tv.tv_usec = to.tv_usec - tv.tv_usec;
466 if (tv.tv_usec < 0) {
467 tv.tv_usec += 1000000;
473 if (select(s + 1, &fdset, NULL, NULL, &tv) == -1)
474 iderror(0, 0, s, ID_UNKNOWN);
475 if (ioctl(s, FIONREAD, &onreadlen) == -1)
476 iderror(0, 0, s, ID_UNKNOWN);
477 if ((size_t)onreadlen > bufsiz)
479 ssize = read(s, &buf[size], (size_t)onreadlen);
481 iderror(0, 0, s, ID_UNKNOWN);
486 if (memchr(&buf[size - ssize], '\n', ssize) != NULL)
490 /* Read two characters, and check for a delimiting character */
491 if (sscanf(buf, "%hu , %hu%c", &lport, &fport, &e) != 3 || isdigit(e))
492 iderror(0, 0, s, ID_INVALID);
499 * If not "real" (-r), send a HIDDEN-USER error for everything.
500 * If -d is used to set a fallback username, this is used to
501 * override it, and the fallback is returned instead.
505 iderror(lport, fport, s, ID_HIDDEN);
510 * We take the input and construct an array of two sockaddr_ins
511 * which contain the local address information and foreign
512 * address information, respectively, used to look up the
513 * credentials for the socket (which are returned by the
514 * sysctl "net.inet.tcp.getcred" when we call it.)
516 socklen = sizeof(ss[0]);
517 if (getsockname(s, (struct sockaddr *)&ss[0], &socklen) == -1)
518 iderror(lport, fport, s, ID_UNKNOWN);
519 socklen = sizeof(ss[1]);
520 if (getpeername(s, (struct sockaddr *)&ss[1], &socklen) == -1)
521 iderror(lport, fport, s, ID_UNKNOWN);
522 if (ss[0].ss_family != ss[1].ss_family)
523 iderror(lport, fport, s, ID_UNKNOWN);
525 switch (ss[0].ss_family) {
527 sin4[0] = *(struct sockaddr_in *)&ss[0];
528 sin4[0].sin_port = htons(lport);
529 sin4[1] = *(struct sockaddr_in *)&ss[1];
530 sin4[1].sin_port = htons(fport);
531 if (sysctlbyname("net.inet.tcp.getcred", &uc, &size, sin4,
537 sin6[0] = *(struct sockaddr_in6 *)&ss[0];
538 sin6[0].sin6_port = htons(lport);
539 sin6[1] = *(struct sockaddr_in6 *)&ss[1];
540 sin6[1].sin6_port = htons(fport);
541 if (sysctlbyname("net.inet6.tcp6.getcred", &uc, &size, sin6,
546 default: /* should not reach here */
547 getcredfail = EAFNOSUPPORT;
550 if (getcredfail != 0) {
552 iderror(lport, fport, s,
553 getcredfail == ENOENT ? ID_NOUSER : ID_UNKNOWN);
557 /* Look up the pw to get the username and home directory*/
559 pw = getpwuid(uc.cr_uid);
561 iderror(lport, fport, s, errno == 0 ? ID_NOUSER : ID_UNKNOWN);
564 snprintf(idbuf, sizeof(idbuf), "%u", (unsigned)pw->pw_uid);
566 strlcpy(idbuf, pw->pw_name, sizeof(idbuf));
569 * If enabled, we check for a file named ".noident" in the user's
570 * home directory. If found, we return HIDDEN-USER.
573 if (asprintf(&p, "%s/.noident", pw->pw_dir) == -1)
574 iderror(lport, fport, s, ID_UNKNOWN);
575 if (lstat(p, &sb) == 0) {
577 iderror(lport, fport, s, ID_HIDDEN);
583 * Here, if enabled, we read a user's ".fakeid" file in their
584 * home directory. It consists of a line containing the name
591 * Here we set ourself to effectively be the user, so we don't
592 * open any files we have no permission to open, especially
593 * symbolic links to sensitive root-owned files or devices.
595 if (initgroups(pw->pw_name, pw->pw_gid) == -1)
596 iderror(lport, fport, s, ID_UNKNOWN);
597 if (seteuid(pw->pw_uid) == -1)
598 iderror(lport, fport, s, ID_UNKNOWN);
600 * We can't stat() here since that would be a race
602 * Therefore, we open the file we have permissions to open
603 * and if it's not a regular file, we close it and end up
604 * returning the user's real username.
606 if (asprintf(&p, "%s/.fakeid", pw->pw_dir) == -1)
607 iderror(lport, fport, s, ID_UNKNOWN);
608 fakeid_fd = open(p, O_RDONLY | O_NONBLOCK);
610 if (fakeid_fd == -1 || fstat(fakeid_fd, &sb) == -1 ||
611 !S_ISREG(sb.st_mode))
614 if ((ssize = read(fakeid_fd, buf, sizeof(buf) - 1)) < 0)
619 * Usually, the file will have the desired identity
620 * in the form "identity\n". Allow for leading white
621 * space and trailing white space/end of line.
624 p += strspn(p, " \t");
625 p[strcspn(p, " \t\r\n")] = '\0';
626 if (strlen(p) > MAXLOGNAME - 1) /* Too long (including nul)? */
627 p[MAXLOGNAME - 1] = '\0';
630 * If the name is a zero-length string or matches it
631 * the id or name of another user (unless permitted by -F)
632 * then it is invalid.
638 if (p[strspn(p, "0123456789")] == '\0' &&
639 getpwuid(atoi(p)) != NULL)
642 if (getpwnam(p) != NULL)
647 strlcpy(idbuf, p, sizeof(idbuf));
655 /* Finally, we make and send the reply. */
656 if (asprintf(&p, "%d , %d : USERID : %s : %s\r\n", lport, fport, osname,
658 syslog(LOG_ERR, "asprintf: %m");
661 send(s, p, strlen(p), MSG_EOF);
668 * RFC738 Time Server.
669 * Return a machine readable date and time, in the form of the
670 * number of seconds since midnight, Jan 1, 1900. Since gettimeofday
671 * returns the number of seconds since midnight, Jan 1, 1970,
672 * we must add 2208988800 seconds to this figure to make up for
673 * some seventy years Bell Labs was asleep.
681 if (gettimeofday(&tv, NULL) < 0) {
683 warnx("unable to get time of day");
686 #define OFFSET ((u_long)25567 * 24*60*60)
687 return (htonl((long)(tv.tv_sec + OFFSET)));
693 machtime_dg(int s, struct servtab *sep)
695 unsigned long result;
696 struct sockaddr_storage ss;
700 if (recvfrom(s, (char *)&result, sizeof(result), 0,
701 (struct sockaddr *)&ss, &size) < 0)
704 if (check_loop((struct sockaddr *)&ss, sep))
708 sendto(s, (char *) &result, sizeof(result), 0,
709 (struct sockaddr *)&ss, size);
714 machtime_stream(int s, struct servtab *sep __unused)
716 unsigned long result;
719 send(s, (char *) &result, sizeof(result), MSG_EOF);
723 * RFC1078 TCP Port Service Multiplexer (TCPMUX). Service connections to
724 * services based on the service name sent.
726 * Based on TCPMUX.C by Mark K. Lottor November 1988
727 * sri-nic::ps:<mkl>tcpmux.c
730 #define MAX_SERV_LEN (256+2) /* 2 bytes for \r\n */
731 #define strwrite(fd, buf) write(fd, buf, sizeof(buf)-1)
733 static int /* # of characters upto \r,\n or \0 */
734 get_line(int fd, char *buf, int len)
740 sigemptyset(&sa.sa_mask);
741 sa.sa_handler = SIG_DFL;
742 sigaction(SIGALRM, &sa, NULL);
745 n = read(fd, buf, len-count);
752 if (*buf == '\r' || *buf == '\n' || *buf == '\0')
757 } while (count < len);
765 char service[MAX_SERV_LEN+1];
768 /* Get requested service name */
769 if ((len = get_line(s, service, MAX_SERV_LEN)) < 0) {
770 strwrite(s, "-Error reading service name\r\n");
776 warnx("tcpmux: someone wants %s", service);
779 * Help is a required command, and lists available services,
782 if (!strcasecmp(service, "help")) {
783 for (sep = servtab; sep; sep = sep->se_next) {
786 write(s,sep->se_service,strlen(sep->se_service));
792 /* Try matching a service in inetd.conf with the request */
793 for (sep = servtab; sep; sep = sep->se_next) {
796 if (!strcasecmp(service, sep->se_service)) {
797 if (ISMUXPLUS(sep)) {
798 strwrite(s, "+Go\r\n");
803 strwrite(s, "-Service not available\r\n");