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