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