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