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