builtins.c revision 326761
1159979Sglebius/*-
2159979Sglebius * Copyright (c) 1983, 1991, 1993, 1994
3159979Sglebius *	The Regents of the University of California.  All rights reserved.
4159979Sglebius *
5159979Sglebius * Redistribution and use in source and binary forms, with or without
6159979Sglebius * modification, are permitted provided that the following conditions
7159979Sglebius * are met:
8159979Sglebius * 1. Redistributions of source code must retain the above copyright
9159979Sglebius *    notice, this list of conditions and the following disclaimer.
10159979Sglebius * 2. Redistributions in binary form must reproduce the above copyright
11159979Sglebius *    notice, this list of conditions and the following disclaimer in the
12159979Sglebius *    documentation and/or other materials provided with the distribution.
13159979Sglebius *
14159979Sglebius * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15159979Sglebius * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16159979Sglebius * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17159979Sglebius * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18159979Sglebius * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19159979Sglebius * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20159979Sglebius * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21159979Sglebius * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22159979Sglebius * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23159979Sglebius * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24159979Sglebius * SUCH DAMAGE.
25159979Sglebius */
26159979Sglebius
27159979Sglebius#include <sys/cdefs.h>
28160050Sru__FBSDID("$FreeBSD: stable/10/usr.sbin/inetd/builtins.c 326761 2017-12-11 05:10:11Z delphij $");
29159979Sglebius
30159979Sglebius#include <sys/filio.h>
31159979Sglebius#include <sys/ioccom.h>
32159979Sglebius#include <sys/param.h>
33159979Sglebius#include <sys/stat.h>
34159979Sglebius#include <sys/socket.h>
35159979Sglebius#include <sys/sysctl.h>
36159979Sglebius#include <sys/ucred.h>
37159979Sglebius#include <sys/uio.h>
38159979Sglebius#include <sys/utsname.h>
39159979Sglebius
40159979Sglebius#include <ctype.h>
41159979Sglebius#include <err.h>
42159979Sglebius#include <errno.h>
43159979Sglebius#include <fcntl.h>
44159979Sglebius#include <limits.h>
45159979Sglebius#include <pwd.h>
46159979Sglebius#include <signal.h>
47159979Sglebius#include <stdlib.h>
48159979Sglebius#include <string.h>
49159979Sglebius#include <sysexits.h>
50159979Sglebius#include <syslog.h>
51159979Sglebius#include <unistd.h>
52159979Sglebius
53159979Sglebius#include "inetd.h"
54159979Sglebius
55159979Sglebiusvoid		chargen_dg(int, struct servtab *);
56159979Sglebiusvoid		chargen_stream(int, struct servtab *);
57159979Sglebiusvoid		daytime_dg(int, struct servtab *);
58159979Sglebiusvoid		daytime_stream(int, struct servtab *);
59159979Sglebiusvoid		discard_dg(int, struct servtab *);
60159979Sglebiusvoid		discard_stream(int, struct servtab *);
61159979Sglebiusvoid		echo_dg(int, struct servtab *);
62159979Sglebiusvoid		echo_stream(int, struct servtab *);
63159979Sglebiusstatic int	getline(int, char *, int);
64159979Sglebiusvoid		iderror(int, int, int, const char *);
65159979Sglebiusvoid		ident_stream(int, struct servtab *);
66159979Sglebiusvoid		initring(void);
67159979Sglebiusuint32_t	machtime(void);
68159979Sglebiusvoid		machtime_dg(int, struct servtab *);
69159979Sglebiusvoid		machtime_stream(int, struct servtab *);
70159979Sglebius
71159979Sglebiuschar ring[128];
72159979Sglebiuschar *endring;
73159979Sglebius
74159979Sglebius
75159979Sglebiusstruct biltin biltins[] = {
76159979Sglebius	/* Echo received data */
77159979Sglebius	{ "echo",	SOCK_STREAM,	1, -1,	echo_stream },
78159979Sglebius	{ "echo",	SOCK_DGRAM,	0, 1,	echo_dg },
79159979Sglebius
80159979Sglebius	/* Internet /dev/null */
81159979Sglebius	{ "discard",	SOCK_STREAM,	1, -1,	discard_stream },
82159979Sglebius	{ "discard",	SOCK_DGRAM,	0, 1,	discard_dg },
83159979Sglebius
84159979Sglebius	/* Return 32 bit time since 1900 */
85159979Sglebius	{ "time",	SOCK_STREAM,	0, -1,	machtime_stream },
86159979Sglebius	{ "time",	SOCK_DGRAM,	0, 1,	machtime_dg },
87159979Sglebius
88159979Sglebius	/* Return human-readable time */
89159979Sglebius	{ "daytime",	SOCK_STREAM,	0, -1,	daytime_stream },
90159979Sglebius	{ "daytime",	SOCK_DGRAM,	0, 1,	daytime_dg },
91159979Sglebius
92159979Sglebius	/* Familiar character generator */
93159979Sglebius	{ "chargen",	SOCK_STREAM,	1, -1,	chargen_stream },
94159979Sglebius	{ "chargen",	SOCK_DGRAM,	0, 1,	chargen_dg },
95159979Sglebius
96159979Sglebius	{ "tcpmux",	SOCK_STREAM,	1, -1,	(bi_fn_t *)tcpmux },
97159979Sglebius
98159979Sglebius	{ "auth",	SOCK_STREAM,	1, -1,	ident_stream },
99159979Sglebius
100159979Sglebius	{ NULL,		0,		0, 0,	NULL }
101159979Sglebius};
102159979Sglebius
103159979Sglebius/*
104159979Sglebius * RFC864 Character Generator Protocol. Generates character data without
105159979Sglebius * any regard for input.
106159979Sglebius */
107159979Sglebius
108159979Sglebiusvoid
109159979Sglebiusinitring(void)
110159979Sglebius{
111159979Sglebius	int i;
112159979Sglebius
113159979Sglebius	endring = ring;
114159979Sglebius
115242997Sjoel	for (i = 0; i <= 128; ++i)
116242997Sjoel		if (isprint(i))
117159979Sglebius			*endring++ = i;
118159979Sglebius}
119159979Sglebius
120159979Sglebius/* Character generator
121159979Sglebius * The RFC says that we should send back a random number of
122159979Sglebius * characters chosen from the range 0 to 512. We send LINESIZ+2.
123159979Sglebius */
124159979Sglebius/* ARGSUSED */
125159979Sglebiusvoid
126159979Sglebiuschargen_dg(int s, struct servtab *sep)
127159979Sglebius{
128159979Sglebius	struct sockaddr_storage ss;
129159979Sglebius	static char *rs;
130159979Sglebius	int len;
131159979Sglebius	socklen_t size;
132159979Sglebius	char text[LINESIZ+2];
133159979Sglebius
134159979Sglebius	if (endring == 0) {
135159979Sglebius		initring();
136159979Sglebius		rs = ring;
137159979Sglebius	}
138159979Sglebius
139159979Sglebius	size = sizeof(ss);
140159979Sglebius	if (recvfrom(s, text, sizeof(text), 0,
141159979Sglebius		     (struct sockaddr *)&ss, &size) < 0)
142159979Sglebius		return;
143159979Sglebius
144159979Sglebius	if (check_loop((struct sockaddr *)&ss, sep))
145159979Sglebius		return;
146159979Sglebius
147159979Sglebius	if ((len = endring - rs) >= LINESIZ)
148159979Sglebius		memmove(text, rs, LINESIZ);
149159979Sglebius	else {
150159979Sglebius		memmove(text, rs, len);
151159979Sglebius		memmove(text + len, ring, LINESIZ - len);
152242997Sjoel	}
153159979Sglebius	if (++rs == endring)
154159979Sglebius		rs = ring;
155159979Sglebius	text[LINESIZ] = '\r';
156159979Sglebius	text[LINESIZ + 1] = '\n';
157159979Sglebius	(void) sendto(s, text, sizeof(text), 0, (struct sockaddr *)&ss, size);
158159979Sglebius}
159242997Sjoel
160159979Sglebius/* Character generator */
161159979Sglebius/* ARGSUSED */
162159979Sglebiusvoid
163159979Sglebiuschargen_stream(int s, struct servtab *sep)
164159979Sglebius{
165159979Sglebius	int len;
166159979Sglebius	char *rs, text[LINESIZ+2];
167159979Sglebius
168159979Sglebius	inetd_setproctitle(sep->se_service, s);
169159979Sglebius
170159979Sglebius	if (!endring)
171159979Sglebius		initring();
172159979Sglebius
173159979Sglebius	text[LINESIZ] = '\r';
174159979Sglebius	text[LINESIZ + 1] = '\n';
175159979Sglebius	for (rs = ring;;) {
176159979Sglebius		if ((len = endring - rs) >= LINESIZ)
177159979Sglebius			memmove(text, rs, LINESIZ);
178242997Sjoel		else {
179159979Sglebius			memmove(text, rs, len);
180159979Sglebius			memmove(text + len, ring, LINESIZ - len);
181159979Sglebius		}
182159979Sglebius		if (++rs == endring)
183159979Sglebius			rs = ring;
184159979Sglebius		if (write(s, text, sizeof(text)) != sizeof(text))
185242997Sjoel			break;
186159979Sglebius	}
187159979Sglebius	exit(0);
188159979Sglebius}
189159979Sglebius
190159979Sglebius/*
191242997Sjoel * RFC867 Daytime Protocol. Sends the current date and time as an ascii
192159979Sglebius * character string without any regard for input.
193159979Sglebius */
194159979Sglebius
195159979Sglebius/* Return human-readable time of day */
196242997Sjoel/* ARGSUSED */
197159979Sglebiusvoid
198159979Sglebiusdaytime_dg(int s, struct servtab *sep)
199159979Sglebius{
200159979Sglebius	char buffer[256];
201159979Sglebius	time_t now;
202159979Sglebius	struct sockaddr_storage ss;
203159979Sglebius	socklen_t size;
204159979Sglebius
205159979Sglebius	now = time((time_t *) 0);
206159979Sglebius
207159979Sglebius	size = sizeof(ss);
208159979Sglebius	if (recvfrom(s, buffer, sizeof(buffer), 0,
209159979Sglebius		     (struct sockaddr *)&ss, &size) < 0)
210165216Smpp		return;
211159979Sglebius
212159979Sglebius	if (check_loop((struct sockaddr *)&ss, sep))
213159979Sglebius		return;
214159979Sglebius
215159979Sglebius	(void) sprintf(buffer, "%.24s\r\n", ctime(&now));
216159979Sglebius	(void) sendto(s, buffer, strlen(buffer), 0,
217159979Sglebius		      (struct sockaddr *)&ss, size);
218159979Sglebius}
219159979Sglebius
220159979Sglebius/* Return human-readable time of day */
221160050Sru/* ARGSUSED */
222159979Sglebiusvoid
223159979Sglebiusdaytime_stream(int s, struct servtab *sep __unused)
224159979Sglebius{
225160050Sru	char buffer[256];
226159979Sglebius	time_t now;
227160050Sru
228159979Sglebius	now = time((time_t *) 0);
229159979Sglebius
230159979Sglebius	(void) sprintf(buffer, "%.24s\r\n", ctime(&now));
231159979Sglebius	(void) send(s, buffer, strlen(buffer), MSG_EOF);
232159979Sglebius}
233159979Sglebius
234159979Sglebius/*
235159979Sglebius * RFC863 Discard Protocol. Any data received is thrown away and no response
236159979Sglebius * is sent.
237159979Sglebius */
238160050Sru
239159979Sglebius/* Discard service -- ignore data */
240160050Sru/* ARGSUSED */
241159979Sglebiusvoid
242159979Sglebiusdiscard_dg(int s, struct servtab *sep __unused)
243159979Sglebius{
244159979Sglebius	char buffer[BUFSIZE];
245159979Sglebius
246160050Sru	(void) read(s, buffer, sizeof(buffer));
247159979Sglebius}
248160050Sru
249159979Sglebius/* Discard service -- ignore data */
250159979Sglebius/* ARGSUSED */
251159979Sglebiusvoid
252159979Sglebiusdiscard_stream(int s, struct servtab *sep)
253159979Sglebius{
254159979Sglebius	int ret;
255159979Sglebius	char buffer[BUFSIZE];
256159979Sglebius
257159979Sglebius	inetd_setproctitle(sep->se_service, s);
258159979Sglebius	while (1) {
259159979Sglebius		while ((ret = read(s, buffer, sizeof(buffer))) > 0)
260159979Sglebius			;
261159979Sglebius		if (ret == 0 || errno != EINTR)
262159979Sglebius			break;
263159979Sglebius	}
264159979Sglebius	exit(0);
265159979Sglebius}
266159979Sglebius
267159979Sglebius/*
268159979Sglebius * RFC862 Echo Protocol. Any data received is sent back to the sender as
269159979Sglebius * received.
270159979Sglebius */
271159979Sglebius
272159979Sglebius/* Echo service -- echo data back */
273159979Sglebius/* ARGSUSED */
274159979Sglebiusvoid
275159979Sglebiusecho_dg(int s, struct servtab *sep)
276159979Sglebius{
277159979Sglebius	char buffer[65536]; /* Should be sizeof(max datagram). */
278159979Sglebius	int i;
279159979Sglebius	socklen_t size;
280159979Sglebius	struct sockaddr_storage ss;
281159979Sglebius
282159979Sglebius	size = sizeof(ss);
283159979Sglebius	if ((i = recvfrom(s, buffer, sizeof(buffer), 0,
284159979Sglebius			  (struct sockaddr *)&ss, &size)) < 0)
285159979Sglebius		return;
286159979Sglebius
287249373Sjoel	if (check_loop((struct sockaddr *)&ss, sep))
288159979Sglebius		return;
289159979Sglebius
290159979Sglebius	(void) sendto(s, buffer, i, 0, (struct sockaddr *)&ss, size);
291159979Sglebius}
292159979Sglebius
293159979Sglebius/* Echo service -- echo data back */
294159979Sglebius/* ARGSUSED */
295159979Sglebiusvoid
296159979Sglebiusecho_stream(int s, struct servtab *sep)
297159979Sglebius{
298159979Sglebius	char buffer[BUFSIZE];
299159979Sglebius	int i;
300159979Sglebius
301159979Sglebius	inetd_setproctitle(sep->se_service, s);
302160050Sru	while ((i = read(s, buffer, sizeof(buffer))) > 0 &&
303159979Sglebius	    write(s, buffer, i) > 0)
304160050Sru		;
305159979Sglebius	exit(0);
306159979Sglebius}
307159979Sglebius
308159979Sglebius/*
309159979Sglebius * RFC1413 Identification Protocol. Given a TCP port number pair, return a
310160050Sru * character string which identifies the owner of that connection on the
311159979Sglebius * server's system. Extended to allow for ~/.fakeid support and ~/.noident
312159979Sglebius * support.
313159979Sglebius */
314159979Sglebius
315159979Sglebius/* RFC 1413 says the following are the only errors you can return. */
316159979Sglebius#define ID_INVALID	"INVALID-PORT"	/* Port number improperly specified. */
317159979Sglebius#define ID_NOUSER	"NO-USER"	/* Port not in use/not identifable. */
318159979Sglebius#define ID_HIDDEN	"HIDDEN-USER"	/* Hiden at user's request. */
319159979Sglebius#define ID_UNKNOWN	"UNKNOWN-ERROR"	/* Everything else. */
320159979Sglebius
321159979Sglebius/* Generic ident_stream error-sending func */
322159979Sglebius/* ARGSUSED */
323159979Sglebiusvoid
324159979Sglebiusiderror(int lport, int fport, int s, const char *er)
325159979Sglebius{
326162871Sru	char *p;
327162871Sru
328162871Sru	asprintf(&p, "%d , %d : ERROR : %s\r\n", lport, fport, er);
329162871Sru	if (p == NULL) {
330162871Sru		syslog(LOG_ERR, "asprintf: %m");
331159979Sglebius		exit(EX_OSERR);
332159979Sglebius	}
333162871Sru	send(s, p, strlen(p), MSG_EOF);
334162871Sru	free(p);
335162871Sru
336162871Sru	exit(0);
337162871Sru}
338162871Sru
339/* Ident service (AKA "auth") */
340/* ARGSUSED */
341void
342ident_stream(int s, struct servtab *sep)
343{
344	struct utsname un;
345	struct stat sb;
346	struct sockaddr_in sin4[2];
347#ifdef INET6
348	struct sockaddr_in6 sin6[2];
349#endif
350	struct sockaddr_storage ss[2];
351	struct xucred uc;
352	struct timeval tv = {
353		10,
354		0
355	}, to;
356	struct passwd *pw = NULL;
357	fd_set fdset;
358	char buf[BUFSIZE], *p, **av, *osname = NULL, e;
359	char idbuf[MAXLOGNAME] = ""; /* Big enough to hold uid in decimal. */
360	socklen_t socklen;
361	ssize_t ssize;
362	size_t size, bufsiz;
363	int c, fflag = 0, nflag = 0, rflag = 0, argc = 0;
364	int gflag = 0, iflag = 0, Fflag = 0, getcredfail = 0, onreadlen;
365	u_short lport, fport;
366
367	inetd_setproctitle(sep->se_service, s);
368	/*
369	 * Reset getopt() since we are a fork() but not an exec() from
370	 * a parent which used getopt() already.
371	 */
372	optind = 1;
373	optreset = 1;
374	/*
375	 * Take the internal argument vector and count it out to make an
376	 * argument count for getopt. This can be used for any internal
377	 * service to read arguments and use getopt() easily.
378	 */
379	for (av = sep->se_argv; *av; av++)
380		argc++;
381	if (argc) {
382		int sec, usec;
383		size_t i;
384		u_int32_t rnd32;
385
386		while ((c = getopt(argc, sep->se_argv, "d:fFgino:rt:")) != -1)
387			switch (c) {
388			case 'd':
389				if (!gflag)
390					strlcpy(idbuf, optarg, sizeof(idbuf));
391				break;
392			case 'f':
393				fflag = 1;
394				break;
395			case 'F':
396				fflag = 1;
397				Fflag=1;
398				break;
399			case 'g':
400				gflag = 1;
401				rnd32 = 0;	/* Shush, compiler. */
402				/*
403				 * The number of bits in "rnd32" divided
404				 * by the number of bits needed per iteration
405				 * gives a more optimal way to reload the
406				 * random number only when necessary.
407				 *
408				 * 32 bits from arc4random corresponds to
409				 * about 6 base-36 digits, so we reseed evey 6.
410				 */
411				for (i = 0; i < sizeof(idbuf) - 1; i++) {
412					static const char *const base36 =
413					    "0123456789"
414					    "abcdefghijklmnopqrstuvwxyz";
415					if (i % 6 == 0)
416						rnd32 = arc4random();
417					idbuf[i] = base36[rnd32 % 36];
418					rnd32 /= 36;
419				}
420				idbuf[i] = '\0';
421				break;
422			case 'i':
423				iflag = 1;
424				break;
425			case 'n':
426				nflag = 1;
427				break;
428			case 'o':
429				osname = optarg;
430				break;
431			case 'r':
432				rflag = 1;
433				break;
434			case 't':
435				switch (sscanf(optarg, "%d.%d", &sec, &usec)) {
436				case 2:
437					tv.tv_usec = usec;
438					/* FALLTHROUGH */
439				case 1:
440					tv.tv_sec = sec;
441					break;
442				default:
443					if (debug)
444						warnx("bad -t argument");
445					break;
446				}
447				break;
448			default:
449				break;
450			}
451	}
452	if (osname == NULL) {
453		if (uname(&un) == -1)
454			iderror(0, 0, s, ID_UNKNOWN);
455		osname = un.sysname;
456	}
457
458	/*
459	 * We're going to prepare for and execute reception of a
460	 * packet of data from the user. The data is in the format
461	 * "local_port , foreign_port\r\n" (with local being the
462	 * server's port and foreign being the client's.)
463	 */
464	gettimeofday(&to, NULL);
465	to.tv_sec += tv.tv_sec;
466	to.tv_usec += tv.tv_usec;
467	if (to.tv_usec >= 1000000) {
468		to.tv_usec -= 1000000;
469		to.tv_sec++;
470	}
471
472	size = 0;
473	bufsiz = sizeof(buf) - 1;
474	FD_ZERO(&fdset);
475 	while (bufsiz > 0) {
476		gettimeofday(&tv, NULL);
477		tv.tv_sec = to.tv_sec - tv.tv_sec;
478		tv.tv_usec = to.tv_usec - tv.tv_usec;
479		if (tv.tv_usec < 0) {
480			tv.tv_usec += 1000000;
481			tv.tv_sec--;
482		}
483		if (tv.tv_sec < 0)
484			break;
485		FD_SET(s, &fdset);
486		if (select(s + 1, &fdset, NULL, NULL, &tv) == -1)
487			iderror(0, 0, s, ID_UNKNOWN);
488		if (ioctl(s, FIONREAD, &onreadlen) == -1)
489			iderror(0, 0, s, ID_UNKNOWN);
490		if ((size_t)onreadlen > bufsiz)
491			onreadlen = bufsiz;
492		ssize = read(s, &buf[size], (size_t)onreadlen);
493		if (ssize == -1)
494			iderror(0, 0, s, ID_UNKNOWN);
495		else if (ssize == 0)
496			break;
497		bufsiz -= ssize;
498		size += ssize;
499		if (memchr(&buf[size - ssize], '\n', ssize) != NULL)
500			break;
501 	}
502	buf[size] = '\0';
503	/* Read two characters, and check for a delimiting character */
504	if (sscanf(buf, "%hu , %hu%c", &lport, &fport, &e) != 3 || isdigit(e))
505		iderror(0, 0, s, ID_INVALID);
506
507	/* Send garbage? */
508	if (gflag)
509		goto printit;
510
511	/*
512	 * If not "real" (-r), send a HIDDEN-USER error for everything.
513	 * If -d is used to set a fallback username, this is used to
514	 * override it, and the fallback is returned instead.
515	 */
516	if (!rflag) {
517		if (*idbuf == '\0')
518			iderror(lport, fport, s, ID_HIDDEN);
519		goto printit;
520	}
521
522	/*
523	 * We take the input and construct an array of two sockaddr_ins
524	 * which contain the local address information and foreign
525	 * address information, respectively, used to look up the
526	 * credentials for the socket (which are returned by the
527	 * sysctl "net.inet.tcp.getcred" when we call it.)
528	 */
529	socklen = sizeof(ss[0]);
530	if (getsockname(s, (struct sockaddr *)&ss[0], &socklen) == -1)
531		iderror(lport, fport, s, ID_UNKNOWN);
532	socklen = sizeof(ss[1]);
533	if (getpeername(s, (struct sockaddr *)&ss[1], &socklen) == -1)
534		iderror(lport, fport, s, ID_UNKNOWN);
535	if (ss[0].ss_family != ss[1].ss_family)
536		iderror(lport, fport, s, ID_UNKNOWN);
537	size = sizeof(uc);
538	switch (ss[0].ss_family) {
539	case AF_INET:
540		sin4[0] = *(struct sockaddr_in *)&ss[0];
541		sin4[0].sin_port = htons(lport);
542		sin4[1] = *(struct sockaddr_in *)&ss[1];
543		sin4[1].sin_port = htons(fport);
544		if (sysctlbyname("net.inet.tcp.getcred", &uc, &size, sin4,
545				 sizeof(sin4)) == -1)
546			getcredfail = errno;
547		break;
548#ifdef INET6
549	case AF_INET6:
550		sin6[0] = *(struct sockaddr_in6 *)&ss[0];
551		sin6[0].sin6_port = htons(lport);
552		sin6[1] = *(struct sockaddr_in6 *)&ss[1];
553		sin6[1].sin6_port = htons(fport);
554		if (sysctlbyname("net.inet6.tcp6.getcred", &uc, &size, sin6,
555				 sizeof(sin6)) == -1)
556			getcredfail = errno;
557		break;
558#endif
559	default: /* should not reach here */
560		getcredfail = EAFNOSUPPORT;
561		break;
562	}
563	if (getcredfail != 0 || uc.cr_version != XUCRED_VERSION) {
564		if (*idbuf == '\0')
565			iderror(lport, fport, s,
566			    getcredfail == ENOENT ? ID_NOUSER : ID_UNKNOWN);
567		goto printit;
568	}
569
570	/* Look up the pw to get the username and home directory*/
571	errno = 0;
572	pw = getpwuid(uc.cr_uid);
573	if (pw == NULL)
574		iderror(lport, fport, s, errno == 0 ? ID_NOUSER : ID_UNKNOWN);
575
576	if (iflag)
577		snprintf(idbuf, sizeof(idbuf), "%u", (unsigned)pw->pw_uid);
578	else
579		strlcpy(idbuf, pw->pw_name, sizeof(idbuf));
580
581	/*
582	 * If enabled, we check for a file named ".noident" in the user's
583	 * home directory. If found, we return HIDDEN-USER.
584	 */
585	if (nflag) {
586		if (asprintf(&p, "%s/.noident", pw->pw_dir) == -1)
587			iderror(lport, fport, s, ID_UNKNOWN);
588		if (lstat(p, &sb) == 0) {
589			free(p);
590			iderror(lport, fport, s, ID_HIDDEN);
591		}
592		free(p);
593	}
594
595	/*
596	 * Here, if enabled, we read a user's ".fakeid" file in their
597	 * home directory. It consists of a line containing the name
598	 * they want.
599	 */
600	if (fflag) {
601		int fakeid_fd;
602
603		/*
604		 * Here we set ourself to effectively be the user, so we don't
605		 * open any files we have no permission to open, especially
606		 * symbolic links to sensitive root-owned files or devices.
607		 */
608		if (initgroups(pw->pw_name, pw->pw_gid) == -1)
609			iderror(lport, fport, s, ID_UNKNOWN);
610		if (seteuid(pw->pw_uid) == -1)
611			iderror(lport, fport, s, ID_UNKNOWN);
612		/*
613		 * We can't stat() here since that would be a race
614		 * condition.
615		 * Therefore, we open the file we have permissions to open
616		 * and if it's not a regular file, we close it and end up
617		 * returning the user's real username.
618		 */
619		if (asprintf(&p, "%s/.fakeid", pw->pw_dir) == -1)
620			iderror(lport, fport, s, ID_UNKNOWN);
621		fakeid_fd = open(p, O_RDONLY | O_NONBLOCK);
622		free(p);
623		if (fakeid_fd == -1 || fstat(fakeid_fd, &sb) == -1 ||
624		    !S_ISREG(sb.st_mode))
625			goto fakeid_fail;
626
627		if ((ssize = read(fakeid_fd, buf, sizeof(buf) - 1)) < 0)
628			goto fakeid_fail;
629		buf[ssize] = '\0';
630
631		/*
632		 * Usually, the file will have the desired identity
633		 * in the form "identity\n". Allow for leading white
634		 * space and trailing white space/end of line.
635		 */
636		p = buf;
637		p += strspn(p, " \t");
638		p[strcspn(p, " \t\r\n")] = '\0';
639		if (strlen(p) > MAXLOGNAME - 1) /* Too long (including nul)? */
640			p[MAXLOGNAME - 1] = '\0';
641
642		/*
643		 * If the name is a zero-length string or matches it
644		 * the id or name of another user (unless permitted by -F)
645		 * then it is invalid.
646		 */
647		if (*p == '\0')
648			goto fakeid_fail;
649		if (!Fflag) {
650			if (iflag) {
651				if (p[strspn(p, "0123456789")] == '\0' &&
652				    getpwuid(atoi(p)) != NULL)
653					goto fakeid_fail;
654			} else {
655				if (getpwnam(p) != NULL)
656					goto fakeid_fail;
657			}
658		}
659
660		strlcpy(idbuf, p, sizeof(idbuf));
661
662fakeid_fail:
663		if (fakeid_fd != -1)
664			close(fakeid_fd);
665	}
666
667printit:
668	/* Finally, we make and send the reply. */
669	if (asprintf(&p, "%d , %d : USERID : %s : %s\r\n", lport, fport, osname,
670	    idbuf) == -1) {
671		syslog(LOG_ERR, "asprintf: %m");
672		exit(EX_OSERR);
673	}
674	send(s, p, strlen(p), MSG_EOF);
675	free(p);
676
677	exit(0);
678}
679
680/*
681 * RFC738/868 Time Server.
682 * Return a machine readable date and time, in the form of the
683 * number of seconds since midnight, Jan 1, 1900.  Since gettimeofday
684 * returns the number of seconds since midnight, Jan 1, 1970,
685 * we must add 2208988800 seconds to this figure to make up for
686 * some seventy years Bell Labs was asleep.
687 */
688
689uint32_t
690machtime(void)
691{
692
693#define	OFFSET ((uint32_t)25567 * 24*60*60)
694	return (htonl((uint32_t)(time(NULL) + OFFSET)));
695#undef OFFSET
696}
697
698/* ARGSUSED */
699void
700machtime_dg(int s, struct servtab *sep)
701{
702	uint32_t result;
703	struct sockaddr_storage ss;
704	socklen_t size;
705
706	size = sizeof(ss);
707	if (recvfrom(s, (char *)&result, sizeof(result), 0,
708		     (struct sockaddr *)&ss, &size) < 0)
709		return;
710
711	if (check_loop((struct sockaddr *)&ss, sep))
712		return;
713
714	result = machtime();
715	(void) sendto(s, (char *) &result, sizeof(result), 0,
716		      (struct sockaddr *)&ss, size);
717}
718
719/* ARGSUSED */
720void
721machtime_stream(int s, struct servtab *sep __unused)
722{
723	uint32_t result;
724
725	result = machtime();
726	(void) send(s, (char *) &result, sizeof(result), MSG_EOF);
727}
728
729/*
730 * RFC1078 TCP Port Service Multiplexer (TCPMUX). Service connections to
731 * services based on the service name sent.
732 *
733 *  Based on TCPMUX.C by Mark K. Lottor November 1988
734 *  sri-nic::ps:<mkl>tcpmux.c
735 */
736
737#define MAX_SERV_LEN	(256+2)		/* 2 bytes for \r\n */
738#define strwrite(fd, buf)	(void) write(fd, buf, sizeof(buf)-1)
739
740static int		/* # of characters up to \r,\n or \0 */
741getline(int fd, char *buf, int len)
742{
743	int count = 0, n;
744	struct sigaction sa;
745
746	sa.sa_flags = 0;
747	sigemptyset(&sa.sa_mask);
748	sa.sa_handler = SIG_DFL;
749	sigaction(SIGALRM, &sa, (struct sigaction *)0);
750	do {
751		alarm(10);
752		n = read(fd, buf, len-count);
753		alarm(0);
754		if (n == 0)
755			return (count);
756		if (n < 0)
757			return (-1);
758		while (--n >= 0) {
759			if (*buf == '\r' || *buf == '\n' || *buf == '\0')
760				return (count);
761			count++;
762			buf++;
763		}
764	} while (count < len);
765	return (count);
766}
767
768struct servtab *
769tcpmux(int s)
770{
771	struct servtab *sep;
772	char service[MAX_SERV_LEN+1];
773	int len;
774
775	/* Get requested service name */
776	if ((len = getline(s, service, MAX_SERV_LEN)) < 0) {
777		strwrite(s, "-Error reading service name\r\n");
778		return (NULL);
779	}
780	service[len] = '\0';
781
782	if (debug)
783		warnx("tcpmux: someone wants %s", service);
784
785	/*
786	 * Help is a required command, and lists available services,
787	 * one per line.
788	 */
789	if (!strcasecmp(service, "help")) {
790		for (sep = servtab; sep; sep = sep->se_next) {
791			if (!ISMUX(sep))
792				continue;
793			(void)write(s,sep->se_service,strlen(sep->se_service));
794			strwrite(s, "\r\n");
795		}
796		return (NULL);
797	}
798
799	/* Try matching a service in inetd.conf with the request */
800	for (sep = servtab; sep; sep = sep->se_next) {
801		if (!ISMUX(sep))
802			continue;
803		if (!strcasecmp(service, sep->se_service)) {
804			if (ISMUXPLUS(sep)) {
805				strwrite(s, "+Go\r\n");
806			}
807			return (sep);
808		}
809	}
810	strwrite(s, "-Service not available\r\n");
811	return (NULL);
812}
813