xref: /netbsd-src/lib/libc/net/rcmd.c (revision 1d83cc5b6c865e8c6ab5eda300f2bb99da79e6d4)
1 /*	$NetBSD: rcmd.c,v 1.64 2006/11/03 20:21:16 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 1983, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #if defined(LIBC_SCCS) && !defined(lint)
34 #if 0
35 static char sccsid[] = "@(#)rcmd.c	8.3 (Berkeley) 3/26/94";
36 #else
37 __RCSID("$NetBSD: rcmd.c,v 1.64 2006/11/03 20:21:16 christos Exp $");
38 #endif
39 #endif /* LIBC_SCCS and not lint */
40 
41 #ifdef _LIBC
42 #include "namespace.h"
43 #endif
44 #include <sys/param.h>
45 #include <sys/socket.h>
46 #include <sys/stat.h>
47 #include <sys/poll.h>
48 #include <sys/wait.h>
49 
50 #include <netinet/in.h>
51 #include <rpc/rpc.h>
52 #include <arpa/inet.h>
53 #include <netgroup.h>
54 
55 #include <assert.h>
56 #include <ctype.h>
57 #include <err.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <grp.h>
61 #include <netdb.h>
62 #include <paths.h>
63 #include <pwd.h>
64 #include <signal.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <syslog.h>
69 #include <unistd.h>
70 
71 #include "pathnames.h"
72 
73 int	orcmd __P((char **, u_int, const char *, const char *, const char *,
74 	    int *));
75 int	orcmd_af __P((char **, u_int, const char *, const char *, const char *,
76 	    int *, int));
77 int	__ivaliduser __P((FILE *, u_int32_t, const char *, const char *));
78 int	__ivaliduser_sa __P((FILE *, const struct sockaddr *, socklen_t,
79 	    const char *, const char *));
80 static	int rshrcmd __P((char **, u_int32_t, const char *, const char *,
81 	    const char *, int *, const char *));
82 static	int resrcmd __P((struct addrinfo *, char **, u_int32_t, const char *,
83 	    const char *, const char *, int *));
84 static	int __icheckhost __P((const struct sockaddr *, socklen_t,
85 	    const char *));
86 static	char *__gethostloop __P((const struct sockaddr *, socklen_t));
87 
88 int
89 rcmd(ahost, rport, locuser, remuser, cmd, fd2p)
90 	char **ahost;
91 	u_short rport;
92 	const char *locuser, *remuser, *cmd;
93 	int *fd2p;
94 {
95 
96 	return rcmd_af(ahost, rport, locuser, remuser, cmd, fd2p, AF_INET);
97 }
98 
99 int
100 rcmd_af(ahost, rport, locuser, remuser, cmd, fd2p, af)
101 	char **ahost;
102 	u_short rport;
103 	const char *locuser, *remuser, *cmd;
104 	int *fd2p;
105 	int af;
106 {
107 	static char hbuf[MAXHOSTNAMELEN];
108 	char pbuf[NI_MAXSERV];
109 	struct addrinfo hints, *res;
110 	int error;
111 	struct servent *sp;
112 
113 	_DIAGASSERT(ahost != NULL);
114 	_DIAGASSERT(locuser != NULL);
115 	_DIAGASSERT(remuser != NULL);
116 	_DIAGASSERT(cmd != NULL);
117 	/* fd2p may be NULL */
118 
119 	snprintf(pbuf, sizeof(pbuf), "%u", ntohs(rport));
120 	memset(&hints, 0, sizeof(hints));
121 	hints.ai_family = af;
122 	hints.ai_socktype = SOCK_STREAM;
123 	hints.ai_flags = AI_CANONNAME;
124 	error = getaddrinfo(*ahost, pbuf, &hints, &res);
125 	if (error) {
126 		warnx("%s: %s", *ahost, gai_strerror(error));	/*XXX*/
127 		return (-1);
128 	}
129 	if (res->ai_canonname) {
130 		/*
131 		 * Canonicalise hostname.
132 		 * XXX: Should we really do this?
133 		 */
134 		strlcpy(hbuf, res->ai_canonname, sizeof(hbuf));
135 		*ahost = hbuf;
136 	}
137 
138 	/*
139 	 * Check if rport is the same as the shell port, and that the fd2p.  If
140 	 * it is not, the program isn't expecting 'rsh' and so we can't use the
141 	 * RCMD_CMD environment.
142 	 */
143 	sp = getservbyname("shell", "tcp");
144 	if (sp != NULL && sp->s_port == rport)
145 		error = rshrcmd(ahost, (u_int32_t)rport,
146 		    locuser, remuser, cmd, fd2p, getenv("RCMD_CMD"));
147 	else
148 		error = resrcmd(res, ahost, (u_int32_t)rport,
149 		    locuser, remuser, cmd, fd2p);
150 	freeaddrinfo(res);
151 	return (error);
152 }
153 
154 /* this is simply a wrapper around hprcmd() that handles ahost first */
155 int
156 orcmd(ahost, rport, locuser, remuser, cmd, fd2p)
157 	char **ahost;
158 	u_int rport;
159 	const char *locuser, *remuser, *cmd;
160 	int *fd2p;
161 {
162 	return orcmd_af(ahost, rport, locuser, remuser, cmd, fd2p, AF_INET);
163 }
164 
165 int
166 orcmd_af(ahost, rport, locuser, remuser, cmd, fd2p, af)
167 	char **ahost;
168 	u_int rport;
169 	const char *locuser, *remuser, *cmd;
170 	int *fd2p;
171 	int af;
172 {
173 	static char hbuf[MAXHOSTNAMELEN];
174 	char pbuf[NI_MAXSERV];
175 	struct addrinfo hints, *res;
176 	int error;
177 
178 	_DIAGASSERT(ahost != NULL);
179 	_DIAGASSERT(locuser != NULL);
180 	_DIAGASSERT(remuser != NULL);
181 	_DIAGASSERT(cmd != NULL);
182 	/* fd2p may be NULL */
183 
184 	snprintf(pbuf, sizeof(pbuf), "%u", ntohs(rport));
185 	memset(&hints, 0, sizeof(hints));
186 	hints.ai_family = af;
187 	hints.ai_socktype = SOCK_STREAM;
188 	hints.ai_flags = AI_CANONNAME;
189 	error = getaddrinfo(*ahost, pbuf, &hints, &res);
190 	if (error) {
191 		warnx("%s: %s", *ahost, gai_strerror(error));	/*XXX*/
192 		return (-1);
193 	}
194 	if (res->ai_canonname) {
195 		strlcpy(hbuf, res->ai_canonname, sizeof(hbuf));
196 		*ahost = hbuf;
197 	}
198 
199 	error = resrcmd(res, ahost, rport, locuser, remuser, cmd, fd2p);
200 	freeaddrinfo(res);
201 	return (error);
202 }
203 
204 /*ARGSUSED*/
205 static int
206 resrcmd(res, ahost, rport, locuser, remuser, cmd, fd2p)
207 	struct addrinfo *res;
208 	char **ahost;
209 	u_int32_t rport;
210 	const char *locuser, *remuser, *cmd;
211 	int *fd2p;
212 {
213 	struct addrinfo *r;
214 	struct sockaddr_storage from;
215 	struct pollfd reads[2];
216 	sigset_t nmask, omask;
217 	pid_t pid;
218 	int s, lport, timo;
219 	int pollr;
220 	char c;
221 	int refused;
222 
223 	_DIAGASSERT(res != NULL);
224 	_DIAGASSERT(ahost != NULL);
225 	_DIAGASSERT(locuser != NULL);
226 	_DIAGASSERT(remuser != NULL);
227 	_DIAGASSERT(cmd != NULL);
228 	/* fd2p may be NULL */
229 
230 	r = res;
231 	refused = 0;
232 	pid = getpid();
233 	sigemptyset(&nmask);
234 	sigaddset(&nmask, SIGURG);
235 	if (sigprocmask(SIG_BLOCK, &nmask, &omask) == -1)
236 		return -1;
237 	for (timo = 1, lport = IPPORT_RESERVED - 1;;) {
238 		s = rresvport_af(&lport, r->ai_family);
239 		if (s < 0) {
240 			if (errno == EAGAIN)
241 				warnx("rcmd: socket: All ports in use");
242 			else
243 				warn("rcmd: socket");
244 			if (r->ai_next) {
245 				r = r->ai_next;
246 				continue;
247 			} else {
248 				(void)sigprocmask(SIG_SETMASK, &omask, NULL);
249 				return (-1);
250 			}
251 		}
252 		fcntl(s, F_SETOWN, pid);
253 		if (connect(s, r->ai_addr, r->ai_addrlen) >= 0)
254 			break;
255 		(void)close(s);
256 		if (errno == EADDRINUSE) {
257 			lport--;
258 			continue;
259 		} else if (errno == ECONNREFUSED)
260 			refused++;
261 		if (r->ai_next) {
262 			int oerrno = errno;
263 			char hbuf[NI_MAXHOST];
264 			const int niflags = NI_NUMERICHOST;
265 
266 			hbuf[0] = '\0';
267 			if (getnameinfo(r->ai_addr, r->ai_addrlen,
268 			    hbuf, sizeof(hbuf), NULL, 0, niflags) != 0)
269 				strlcpy(hbuf, "(invalid)", sizeof(hbuf));
270 			errno = oerrno;
271 			warn("rcmd: connect to address %s", hbuf);
272 			r = r->ai_next;
273 			hbuf[0] = '\0';
274 			if (getnameinfo(r->ai_addr, r->ai_addrlen,
275 			    hbuf, sizeof(hbuf), NULL, 0, niflags) != 0)
276 				strlcpy(hbuf, "(invalid)", sizeof(hbuf));
277 			(void)fprintf(stderr, "Trying %s...\n", hbuf);
278 			continue;
279 		}
280 		if (refused && timo <= 16) {
281 			(void)sleep((unsigned int)timo);
282 			timo *= 2;
283 			r = res;
284 			refused = 0;
285 			continue;
286 		}
287 		(void)fprintf(stderr, "%s: %s\n", res->ai_canonname,
288 		    strerror(errno));
289 		(void)sigprocmask(SIG_SETMASK, &omask, NULL);
290 		return (-1);
291 	}
292 	lport--;
293 	if (fd2p == 0) {
294 		write(s, "", 1);
295 		lport = 0;
296 	} else {
297 		char num[8];
298 		int s2 = rresvport_af(&lport, r->ai_family), s3;
299 		socklen_t len = sizeof(from);
300 
301 		if (s2 < 0)
302 			goto bad;
303 		listen(s2, 1);
304 		(void)snprintf(num, sizeof(num), "%d", lport);
305 		if (write(s, num, strlen(num) + 1) !=
306 		    (ssize_t) (strlen(num) + 1)) {
307 			warn("rcmd: write (setting up stderr)");
308 			(void)close(s2);
309 			goto bad;
310 		}
311 		reads[0].fd = s;
312 		reads[0].events = POLLIN;
313 		reads[1].fd = s2;
314 		reads[1].events = POLLIN;
315 		errno = 0;
316 		pollr = poll(reads, 2, INFTIM);
317 		if (pollr < 1 || (reads[1].revents & POLLIN) == 0) {
318 			if (errno != 0)
319 				warn("poll: setting up stderr");
320 			else
321 				warnx("poll: protocol failure in circuit setup");
322 			(void)close(s2);
323 			goto bad;
324 		}
325 		s3 = accept(s2, (struct sockaddr *)(void *)&from, &len);
326 		(void)close(s2);
327 		if (s3 < 0) {
328 			warn("rcmd: accept");
329 			lport = 0;
330 			goto bad;
331 		}
332 		*fd2p = s3;
333 		switch (((struct sockaddr *)(void *)&from)->sa_family) {
334 		case AF_INET:
335 #ifdef INET6
336 		case AF_INET6:
337 #endif
338 			if (getnameinfo((struct sockaddr *)(void *)&from, len,
339 			    NULL, 0, num, sizeof(num), NI_NUMERICSERV) != 0 ||
340 			    (atoi(num) >= IPPORT_RESERVED ||
341 			     atoi(num) < IPPORT_RESERVED / 2)) {
342 				warnx("rcmd: protocol failure in circuit setup.");
343 				goto bad2;
344 			}
345 			break;
346 		default:
347 			break;
348 		}
349 	}
350 
351 	(void)write(s, locuser, strlen(locuser)+1);
352 	(void)write(s, remuser, strlen(remuser)+1);
353 	(void)write(s, cmd, strlen(cmd)+1);
354 	if (read(s, &c, 1) != 1) {
355 		warn("%s", *ahost);
356 		goto bad2;
357 	}
358 	if (c != 0) {
359 		while (read(s, &c, 1) == 1) {
360 			(void)write(STDERR_FILENO, &c, 1);
361 			if (c == '\n')
362 				break;
363 		}
364 		goto bad2;
365 	}
366 	(void)sigprocmask(SIG_SETMASK, &omask, NULL);
367 	return (s);
368 bad2:
369 	if (lport)
370 		(void)close(*fd2p);
371 bad:
372 	(void)close(s);
373 	(void)sigprocmask(SIG_SETMASK, &omask, NULL);
374 	return (-1);
375 }
376 
377 /*
378  * based on code written by Chris Siebenmann <cks@utcc.utoronto.ca>
379  */
380 /* ARGSUSED */
381 static int
382 rshrcmd(ahost, rport, locuser, remuser, cmd, fd2p, rshcmd)
383 	char  	**ahost;
384 	u_int32_t	rport;
385 	const	char *locuser, *remuser, *cmd;
386 	int	*fd2p;
387 	const	char *rshcmd;
388 {
389 	pid_t pid;
390 	int sp[2], ep[2];
391 	char *p;
392 	struct passwd *pw, pwres;
393 	char pwbuf[1024];
394 
395 	_DIAGASSERT(ahost != NULL);
396 	_DIAGASSERT(locuser != NULL);
397 	_DIAGASSERT(remuser != NULL);
398 	_DIAGASSERT(cmd != NULL);
399 	/* fd2p may be NULL */
400 
401 	/* What rsh/shell to use. */
402 	if (rshcmd == NULL)
403 		rshcmd = _PATH_BIN_RCMD;
404 
405 	/* locuser must exist on this host. */
406 	if (getpwnam_r(locuser, &pwres, pwbuf, sizeof(pwbuf), &pw) != 0 ||
407 	    pw == NULL) {
408 		warnx("rshrcmd: unknown user: %s", locuser);
409 		return(-1);
410 	}
411 
412 	/* get a socketpair we'll use for stdin and stdout. */
413 	if (socketpair(AF_LOCAL, SOCK_STREAM, 0, sp) < 0) {
414 		warn("rshrcmd: socketpair");
415 		return (-1);
416 	}
417 	/* we will use this for the fd2 pointer */
418 	if (fd2p) {
419 		if (socketpair(AF_LOCAL, SOCK_STREAM, 0, ep) < 0) {
420 			warn("rshrcmd: socketpair");
421 			return (-1);
422 		}
423 		*fd2p = ep[0];
424 	}
425 
426 	pid = fork();
427 	if (pid < 0) {
428 		warn("rshrcmd: fork");
429 		return (-1);
430 	}
431 	if (pid == 0) {
432 		/*
433 		 * child
434 		 * - we use sp[1] to be stdin/stdout, and close sp[0]
435 		 * - with fd2p, we use ep[1] for stderr, and close ep[0]
436 		 */
437 		(void)close(sp[0]);
438 		if (dup2(sp[1], 0) < 0 || dup2(0, 1) < 0) {
439 			warn("rshrcmd: dup2");
440 			_exit(1);
441 		}
442 		if (fd2p) {
443 			if (dup2(ep[1], 2) < 0) {
444 				warn("rshrcmd: dup2");
445 				_exit(1);
446 			}
447 			(void)close(ep[0]);
448 			(void)close(ep[1]);
449 		} else if (dup2(0, 2) < 0) {
450 			warn("rshrcmd: dup2");
451 			_exit(1);
452 		}
453 		/* fork again to lose parent. */
454 		pid = fork();
455 		if (pid < 0) {
456 			warn("rshrcmd: second fork");
457 			_exit(1);
458 		}
459 		if (pid > 0)
460 			_exit(0);
461 
462 		/* Orphan.  Become local user for rshprog. */
463 		if (setuid(pw->pw_uid)) {
464 			warn("rshrcmd: setuid(%lu)", (u_long)pw->pw_uid);
465 			_exit(1);
466 		}
467 
468 		/*
469 		 * If we are rcmd'ing to "localhost" as the same user as we are,
470 		 * then avoid running remote shell for efficiency.
471 		 */
472 		if (strcmp(*ahost, "localhost") == 0 &&
473 		    strcmp(locuser, remuser) == 0) {
474 			if (pw->pw_shell[0] == '\0')
475 				rshcmd = _PATH_BSHELL;
476 			else
477 				rshcmd = pw->pw_shell;
478 			p = strrchr(rshcmd, '/');
479 			execlp(rshcmd, p ? p + 1 : rshcmd, "-c", cmd, NULL);
480 		} else {
481 			p = strrchr(rshcmd, '/');
482 			execlp(rshcmd, p ? p + 1 : rshcmd, *ahost, "-l",
483 			    remuser, cmd, NULL);
484 		}
485 		warn("rshrcmd: exec %s", rshcmd);
486 		_exit(1);
487 	}
488 	/* Parent */
489 	(void)close(sp[1]);
490 	if (fd2p)
491 		(void)close(ep[1]);
492 
493 	(void)waitpid(pid, NULL, 0);
494 	return (sp[0]);
495 }
496 
497 int
498 rresvport(alport)
499 	int *alport;
500 {
501 
502 	_DIAGASSERT(alport != NULL);
503 
504 	return rresvport_af(alport, AF_INET);
505 }
506 
507 int
508 rresvport_af(alport, family)
509 	int *alport;
510 	int family;
511 {
512 	struct sockaddr_storage ss;
513 	struct sockaddr *sa;
514 	int salen;
515 	int s;
516 	u_int16_t *portp;
517 
518 	_DIAGASSERT(alport != NULL);
519 
520 	memset(&ss, 0, sizeof(ss));
521 	sa = (struct sockaddr *)(void *)&ss;
522 	switch (family) {
523 	case AF_INET:
524 #ifdef BSD4_4
525 		sa->sa_len =
526 #endif
527 		salen = sizeof(struct sockaddr_in);
528 		portp = &((struct sockaddr_in *)(void *)sa)->sin_port;
529 		break;
530 #ifdef INET6
531 	case AF_INET6:
532 #ifdef BSD4_4
533 		sa->sa_len =
534 #endif
535 		salen = sizeof(struct sockaddr_in6);
536 		portp = &((struct sockaddr_in6 *)(void *)sa)->sin6_port;
537 		break;
538 #endif
539 	default:
540 		errno = EAFNOSUPPORT;
541 		return (-1);
542 	}
543 	sa->sa_family = family;
544 	s = socket(family, SOCK_STREAM, 0);
545 	if (s < 0)
546 		return (-1);
547 #ifdef BSD4_4
548 	switch (family) {
549 	case AF_INET:
550 	case AF_INET6:
551 		*portp = 0;
552 		if (bindresvport(s, (struct sockaddr_in *)(void *)sa) < 0) {
553 			int sverr = errno;
554 
555 			(void)close(s);
556 			errno = sverr;
557 			return (-1);
558 		}
559 		*alport = (int)ntohs(*portp);
560 		return (s);
561 	default:
562 		/* is it necessary to try keep code for other AFs? */
563 		break;
564 	}
565 #endif
566 	for (;;) {
567 		*portp = htons((u_short)*alport);
568 		if (bind(s, sa, (socklen_t)salen) >= 0)
569 			return (s);
570 		if (errno != EADDRINUSE) {
571 			(void)close(s);
572 			return (-1);
573 		}
574 		(*alport)--;
575 		if (*alport == IPPORT_RESERVED/2) {
576 			(void)close(s);
577 			errno = EAGAIN;		/* close */
578 			return (-1);
579 		}
580 	}
581 }
582 
583 int	__check_rhosts_file = 1;
584 const char *__rcmd_errstr;
585 
586 int
587 ruserok(rhost, superuser, ruser, luser)
588 	const char *rhost, *ruser, *luser;
589 	int superuser;
590 {
591 	struct addrinfo hints, *res, *r;
592 	int error;
593 
594 	_DIAGASSERT(rhost != NULL);
595 	_DIAGASSERT(ruser != NULL);
596 	_DIAGASSERT(luser != NULL);
597 
598 	memset(&hints, 0, sizeof(hints));
599 	hints.ai_family = PF_UNSPEC;
600 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
601 	error = getaddrinfo(rhost, "0", &hints, &res);
602 	if (error)
603 		return (-1);
604 
605 	for (r = res; r; r = r->ai_next) {
606 		if (iruserok_sa(r->ai_addr, (int)r->ai_addrlen, superuser,
607 		    ruser, luser) == 0) {
608 			freeaddrinfo(res);
609 			return (0);
610 		}
611 	}
612 	freeaddrinfo(res);
613 	return (-1);
614 }
615 
616 /*
617  * New .rhosts strategy: We are passed an ip address. We spin through
618  * hosts.equiv and .rhosts looking for a match. When the .rhosts only
619  * has ip addresses, we don't have to trust a nameserver.  When it
620  * contains hostnames, we spin through the list of addresses the nameserver
621  * gives us and look for a match.
622  *
623  * Returns 0 if ok, -1 if not ok.
624  */
625 int
626 iruserok(raddr, superuser, ruser, luser)
627 	u_int32_t raddr;
628 	int superuser;
629 	const char *ruser, *luser;
630 {
631 	struct sockaddr_in irsin;
632 
633 	memset(&irsin, 0, sizeof(irsin));
634 	irsin.sin_family = AF_INET;
635 #ifdef BSD4_4
636 	irsin.sin_len = sizeof(struct sockaddr_in);
637 #endif
638 	memcpy(&irsin.sin_addr, &raddr, sizeof(irsin.sin_addr));
639 	return iruserok_sa(&irsin, sizeof(struct sockaddr_in), superuser, ruser,
640 		    luser);
641 }
642 
643 /*
644  * 2nd and 3rd arguments are typed like this, to avoid dependency between
645  * unistd.h and sys/socket.h.  There's no better way.
646  */
647 int
648 iruserok_sa(raddr, rlen, superuser, ruser, luser)
649 	const void *raddr;
650 	int rlen;
651 	int superuser;
652 	const char *ruser, *luser;
653 {
654 	const struct sockaddr *sa;
655 	struct stat sbuf;
656 	struct passwd *pwd, pwres;
657 	FILE *hostf;
658 	uid_t uid;
659 	gid_t gid;
660 	int isvaliduser;
661 	char pbuf[MAXPATHLEN];
662 	char pwbuf[1024];
663 
664 	_DIAGASSERT(raddr != NULL);
665 	_DIAGASSERT(ruser != NULL);
666 	_DIAGASSERT(luser != NULL);
667 
668 	sa = raddr;
669 
670 	__rcmd_errstr = NULL;
671 
672 	hostf = superuser ? NULL : fopen(_PATH_HEQUIV, "r");
673 
674 	if (hostf) {
675 		if (__ivaliduser_sa(hostf, sa, (socklen_t)rlen, luser,
676 		    ruser) == 0) {
677 			(void)fclose(hostf);
678 			return (0);
679 		}
680 		(void)fclose(hostf);
681 	}
682 
683 	isvaliduser = -1;
684 	if (__check_rhosts_file || superuser) {
685 
686 		if (getpwnam_r(luser, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0
687 		    || pwd == NULL)
688 			return (-1);
689 		(void)strlcpy(pbuf, pwd->pw_dir, sizeof(pbuf));
690 		(void)strlcat(pbuf, "/.rhosts", sizeof(pbuf));
691 
692 		/*
693 		 * Change effective uid while opening and reading .rhosts.
694 		 * If root and reading an NFS mounted file system, can't
695 		 * read files that are protected read/write owner only.
696 		 */
697 		uid = geteuid();
698 		gid = getegid();
699 		(void)setegid(pwd->pw_gid);
700 		initgroups(pwd->pw_name, pwd->pw_gid);
701 		(void)seteuid(pwd->pw_uid);
702 		hostf = fopen(pbuf, "r");
703 
704 		if (hostf != NULL) {
705 			/*
706 			 * If not a regular file, or is owned by someone other
707 			 * than user or root or if writable by anyone but the
708 			 * owner, quit.
709 			 */
710 			if (lstat(pbuf, &sbuf) < 0)
711 				__rcmd_errstr = ".rhosts lstat failed";
712 			else if (!S_ISREG(sbuf.st_mode))
713 				__rcmd_errstr = ".rhosts not regular file";
714 			else if (fstat(fileno(hostf), &sbuf) < 0)
715 				__rcmd_errstr = ".rhosts fstat failed";
716 			else if (sbuf.st_uid && sbuf.st_uid != pwd->pw_uid)
717 				__rcmd_errstr = "bad .rhosts owner";
718 			else if (sbuf.st_mode & (S_IWGRP|S_IWOTH))
719 				__rcmd_errstr =
720 					".rhosts writable by other than owner";
721 			else
722 				isvaliduser =
723 				    __ivaliduser_sa(hostf, sa, (socklen_t)rlen,
724 						    luser, ruser);
725 
726 			(void)fclose(hostf);
727 		}
728 		(void)seteuid(uid);
729 		(void)setegid(gid);
730 
731 	}
732 	return (isvaliduser);
733 }
734 
735 /*
736  * XXX
737  * Don't make static, used by lpd(8).  We will be able to change the function
738  * into static function, when we bump libc major #.
739  *
740  * Returns 0 if ok, -1 if not ok.
741  */
742 #ifdef notdef	/*_LIBC*/
743 static
744 #endif
745 int
746 __ivaliduser(hostf, raddr, luser, ruser)
747 	FILE *hostf;
748 	u_int32_t raddr;
749 	const char *luser, *ruser;
750 {
751 	struct sockaddr_in ivusin;
752 
753 	memset(&ivusin, 0, sizeof(ivusin));
754 	ivusin.sin_family = AF_INET;
755 #ifdef BSD4_4
756 	ivusin.sin_len = sizeof(struct sockaddr_in);
757 #endif
758 	memcpy(&ivusin.sin_addr, &raddr, sizeof(ivusin.sin_addr));
759 	return __ivaliduser_sa(hostf, (struct sockaddr *)(void *)&ivusin,
760 	    sizeof(struct sockaddr_in), luser, ruser);
761 }
762 
763 #ifdef notdef	/*_LIBC*/
764 static
765 #endif
766 int
767 __ivaliduser_sa(hostf, raddr, salen, luser, ruser)
768 	FILE *hostf;
769 	const struct sockaddr *raddr;
770 	socklen_t salen;
771 	const char *luser, *ruser;
772 {
773 	register char *user, *p;
774 	int ch;
775 	char buf[MAXHOSTNAMELEN + 128];		/* host + login */
776 	const char *auser, *ahost;
777 	int hostok, userok;
778 	char *rhost = NULL;
779 	int firsttime = 1;
780 	char domain[MAXHOSTNAMELEN];
781 
782 	getdomainname(domain, sizeof(domain));
783 
784 	_DIAGASSERT(hostf != NULL);
785 	_DIAGASSERT(luser != NULL);
786 	_DIAGASSERT(ruser != NULL);
787 
788 	while (fgets(buf, sizeof(buf), hostf)) {
789 		p = buf;
790 		/* Skip lines that are too long. */
791 		if (strchr(p, '\n') == NULL) {
792 			while ((ch = getc(hostf)) != '\n' && ch != EOF)
793 				;
794 			continue;
795 		}
796 		while (*p != '\n' && *p != ' ' && *p != '\t' && *p != '\0') {
797 			*p = isupper((unsigned char)*p) ?
798 			    tolower((unsigned char)*p) : *p;
799 			p++;
800 		}
801 		if (*p == ' ' || *p == '\t') {
802 			*p++ = '\0';
803 			while (*p == ' ' || *p == '\t')
804 				p++;
805 			user = p;
806 			while (*p != '\n' && *p != ' ' &&
807 			    *p != '\t' && *p != '\0')
808 				p++;
809 		} else
810 			user = p;
811 		*p = '\0';
812 
813 		if (p == buf)
814 			continue;
815 
816 		auser = *user ? user : luser;
817 		ahost = buf;
818 
819 		if (ahost[0] == '+')
820 			switch (ahost[1]) {
821 			case '\0':
822 				hostok = 1;
823 				break;
824 
825 			case '@':
826 				if (firsttime) {
827 					rhost = __gethostloop(raddr, salen);
828 					firsttime = 0;
829 				}
830 				if (rhost)
831 					hostok = innetgr(&ahost[2], rhost,
832 					    NULL, domain);
833 				else
834 					hostok = 0;
835 				break;
836 
837 			default:
838 				hostok = __icheckhost(raddr, salen, &ahost[1]);
839 				break;
840 			}
841 		else if (ahost[0] == '-')
842 			switch (ahost[1]) {
843 			case '\0':
844 				hostok = -1;
845 				break;
846 
847 			case '@':
848 				if (firsttime) {
849 					rhost = __gethostloop(raddr, salen);
850 					firsttime = 0;
851 				}
852 				if (rhost)
853 					hostok = -innetgr(&ahost[2], rhost,
854 					    NULL, domain);
855 				else
856 					hostok = 0;
857 				break;
858 
859 			default:
860 				hostok = -__icheckhost(raddr, salen, &ahost[1]);
861 				break;
862 			}
863 		else
864 			hostok = __icheckhost(raddr, salen, ahost);
865 
866 
867 		if (auser[0] == '+')
868 			switch (auser[1]) {
869 			case '\0':
870 				userok = 1;
871 				break;
872 
873 			case '@':
874 				userok = innetgr(&auser[2], NULL, ruser,
875 				    domain);
876 				break;
877 
878 			default:
879 				userok = strcmp(ruser, &auser[1]) == 0;
880 				break;
881 			}
882 		else if (auser[0] == '-')
883 			switch (auser[1]) {
884 			case '\0':
885 				userok = -1;
886 				break;
887 
888 			case '@':
889 				userok = -innetgr(&auser[2], NULL, ruser,
890 				    domain);
891 				break;
892 
893 			default:
894 				userok =
895 				    -(strcmp(ruser, &auser[1]) == 0 ? 1 : 0);
896 				break;
897 			}
898 		else
899 			userok = strcmp(ruser, auser) == 0;
900 
901 		/* Check if one component did not match */
902 		if (hostok == 0 || userok == 0)
903 			continue;
904 
905 		/* Check if we got a forbidden pair */
906 		if (userok == -1 || hostok == -1)
907 			return -1;
908 
909 		/* Check if we got a valid pair */
910 		if (hostok == 1 && userok == 1)
911 			return 0;
912 	}
913 	return -1;
914 }
915 
916 /*
917  * Returns "true" if match, 0 if no match.
918  */
919 static int
920 __icheckhost(raddr, salen, lhost)
921 	const struct sockaddr *raddr;
922 	socklen_t salen;
923 	const char *lhost;
924 {
925 	struct addrinfo hints, *res, *r;
926 	char h1[NI_MAXHOST], h2[NI_MAXHOST];
927 	int error;
928 	const int niflags = NI_NUMERICHOST;
929 
930 	_DIAGASSERT(raddr != NULL);
931 	_DIAGASSERT(lhost != NULL);
932 
933 	h1[0] = '\0';
934 	if (getnameinfo(raddr, salen, h1, sizeof(h1), NULL, 0,
935 	    niflags) != 0)
936 		return (0);
937 
938 	/* Resolve laddr into sockaddr */
939 	memset(&hints, 0, sizeof(hints));
940 	hints.ai_family = raddr->sa_family;
941 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
942 	res = NULL;
943 	error = getaddrinfo(lhost, "0", &hints, &res);
944 	if (error)
945 		return (0);
946 
947 	/*
948 	 * Try string comparisons between raddr and laddr.
949 	 */
950 	for (r = res; r; r = r->ai_next) {
951 		h2[0] = '\0';
952 		if (getnameinfo(r->ai_addr, r->ai_addrlen, h2, sizeof(h2),
953 		    NULL, 0, niflags) != 0)
954 			continue;
955 		if (strcmp(h1, h2) == 0) {
956 			freeaddrinfo(res);
957 			return (1);
958 		}
959 	}
960 
961 	/* No match. */
962 	freeaddrinfo(res);
963 	return (0);
964 }
965 
966 /*
967  * Return the hostname associated with the supplied address.
968  * Do a reverse lookup as well for security. If a loop cannot
969  * be found, pack the numeric IP address into the string.
970  */
971 static char *
972 __gethostloop(raddr, salen)
973 	const struct sockaddr *raddr;
974 	socklen_t salen;
975 {
976 	static char remotehost[NI_MAXHOST];
977 	char h1[NI_MAXHOST], h2[NI_MAXHOST];
978 	struct addrinfo hints, *res, *r;
979 	int error;
980 	const int niflags = NI_NUMERICHOST;
981 
982 	_DIAGASSERT(raddr != NULL);
983 
984 	h1[0] = remotehost[0] = '\0';
985 	if (getnameinfo(raddr, salen, remotehost, sizeof(remotehost),
986 	    NULL, 0, NI_NAMEREQD) != 0)
987 		return (NULL);
988 	if (getnameinfo(raddr, salen, h1, sizeof(h1), NULL, 0,
989 	    niflags) != 0)
990 		return (NULL);
991 
992 	/*
993 	 * Look up the name and check that the supplied
994 	 * address is in the list
995 	 */
996 	memset(&hints, 0, sizeof(hints));
997 	hints.ai_family = raddr->sa_family;
998 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
999 	hints.ai_flags = AI_CANONNAME;
1000 	res = NULL;
1001 	error = getaddrinfo(remotehost, "0", &hints, &res);
1002 	if (error)
1003 		return (NULL);
1004 
1005 	for (r = res; r; r = r->ai_next) {
1006 		h2[0] = '\0';
1007 		if (getnameinfo(r->ai_addr, r->ai_addrlen, h2, sizeof(h2),
1008 		    NULL, 0, niflags) != 0)
1009 			continue;
1010 		if (strcmp(h1, h2) == 0) {
1011 			freeaddrinfo(res);
1012 			return (remotehost);
1013 		}
1014 	}
1015 
1016 	/*
1017 	 * either the DNS adminstrator has made a configuration
1018 	 * mistake, or someone has attempted to spoof us
1019 	 */
1020 	syslog(LOG_NOTICE, "rcmd: address %s not listed for host %s",
1021 	    h1, res->ai_canonname ? res->ai_canonname : remotehost);
1022 	freeaddrinfo(res);
1023 	return (NULL);
1024 }
1025