xref: /openbsd-src/lib/libc/net/rcmd.c (revision 9983e72c5de0447f7fc18b4bf4691b06eb70e2bc)
1 /*	$NetBSD: rcmd.c,v 1.12 1995/06/03 22:33:34 mycroft 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. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #if defined(LIBC_SCCS) && !defined(lint)
37 #if 0
38 static char sccsid[] = "@(#)rcmd.c	8.3 (Berkeley) 3/26/94";
39 #else
40 static char *rcsid = "$NetBSD: rcmd.c,v 1.12 1995/06/03 22:33:34 mycroft Exp $";
41 #endif
42 #endif /* LIBC_SCCS and not lint */
43 
44 #include <sys/param.h>
45 #include <sys/socket.h>
46 #include <sys/stat.h>
47 
48 #include <netinet/in.h>
49 #include <arpa/inet.h>
50 
51 #include <signal.h>
52 #include <fcntl.h>
53 #include <netdb.h>
54 #include <unistd.h>
55 #include <pwd.h>
56 #include <errno.h>
57 #include <stdio.h>
58 #include <ctype.h>
59 #include <string.h>
60 #include <syslog.h>
61 
62 int	__ivaliduser __P((FILE *, u_long, const char *, const char *));
63 static int __icheckhost __P((u_int32_t, const char *));
64 static char *__gethostloop __P((u_int32_t));
65 
66 int
67 rcmd(ahost, rport, locuser, remuser, cmd, fd2p)
68 	char **ahost;
69 	u_short rport;
70 	const char *locuser, *remuser, *cmd;
71 	int *fd2p;
72 {
73 	struct hostent *hp;
74 	struct sockaddr_in sin, from;
75 	fd_set reads;
76 	int oldmask;
77 	pid_t pid;
78 	int s, lport, timo;
79 	char c;
80 
81 	pid = getpid();
82 	hp = gethostbyname(*ahost);
83 	if (hp == NULL) {
84 		herror(*ahost);
85 		return (-1);
86 	}
87 	*ahost = hp->h_name;
88 	oldmask = sigblock(sigmask(SIGURG));
89 	for (timo = 1, lport = IPPORT_RESERVED - 1;;) {
90 		s = rresvport(&lport);
91 		if (s < 0) {
92 			if (errno == EAGAIN)
93 				(void)fprintf(stderr,
94 				    "rcmd: socket: All ports in use\n");
95 			else
96 				(void)fprintf(stderr, "rcmd: socket: %s\n",
97 				    strerror(errno));
98 			sigsetmask(oldmask);
99 			return (-1);
100 		}
101 		fcntl(s, F_SETOWN, pid);
102 		sin.sin_len = sizeof(struct sockaddr_in);
103 		sin.sin_family = hp->h_addrtype;
104 		sin.sin_port = rport;
105 		bcopy(hp->h_addr_list[0], &sin.sin_addr, hp->h_length);
106 		if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) >= 0)
107 			break;
108 		(void)close(s);
109 		if (errno == EADDRINUSE) {
110 			lport--;
111 			continue;
112 		}
113 		if (errno == ECONNREFUSED && timo <= 16) {
114 			(void)sleep(timo);
115 			timo *= 2;
116 			continue;
117 		}
118 		if (hp->h_addr_list[1] != NULL) {
119 			int oerrno = errno;
120 
121 			(void)fprintf(stderr, "connect to address %s: ",
122 			    inet_ntoa(sin.sin_addr));
123 			errno = oerrno;
124 			perror(0);
125 			hp->h_addr_list++;
126 			bcopy(hp->h_addr_list[0], &sin.sin_addr, hp->h_length);
127 			(void)fprintf(stderr, "Trying %s...\n",
128 			    inet_ntoa(sin.sin_addr));
129 			continue;
130 		}
131 		(void)fprintf(stderr, "%s: %s\n", hp->h_name, strerror(errno));
132 		sigsetmask(oldmask);
133 		return (-1);
134 	}
135 	lport--;
136 	if (fd2p == 0) {
137 		write(s, "", 1);
138 		lport = 0;
139 	} else {
140 		char num[8];
141 		int s2 = rresvport(&lport), s3;
142 		int len = sizeof(from);
143 
144 		if (s2 < 0)
145 			goto bad;
146 		listen(s2, 1);
147 		(void)snprintf(num, sizeof(num), "%d", lport);
148 		if (write(s, num, strlen(num)+1) != strlen(num)+1) {
149 			(void)fprintf(stderr,
150 			    "rcmd: write (setting up stderr): %s\n",
151 			    strerror(errno));
152 			(void)close(s2);
153 			goto bad;
154 		}
155 		FD_ZERO(&reads);
156 		FD_SET(s, &reads);
157 		FD_SET(s2, &reads);
158 		errno = 0;
159 		if (select(MAX(s, s2) + 1, &reads, 0, 0, 0) < 1 ||
160 		    !FD_ISSET(s2, &reads)) {
161 			if (errno != 0)
162 				(void)fprintf(stderr,
163 				    "rcmd: select (setting up stderr): %s\n",
164 				    strerror(errno));
165 			else
166 				(void)fprintf(stderr,
167 				"select: protocol failure in circuit setup\n");
168 			(void)close(s2);
169 			goto bad;
170 		}
171 		s3 = accept(s2, (struct sockaddr *)&from, &len);
172 		(void)close(s2);
173 		if (s3 < 0) {
174 			(void)fprintf(stderr,
175 			    "rcmd: accept: %s\n", strerror(errno));
176 			lport = 0;
177 			goto bad;
178 		}
179 		*fd2p = s3;
180 		from.sin_port = ntohs(from.sin_port);
181 		if (from.sin_family != AF_INET ||
182 		    from.sin_port >= IPPORT_RESERVED ||
183 		    from.sin_port < IPPORT_RESERVED / 2) {
184 			(void)fprintf(stderr,
185 			    "socket: protocol failure in circuit setup.\n");
186 			goto bad2;
187 		}
188 	}
189 	(void)write(s, locuser, strlen(locuser)+1);
190 	(void)write(s, remuser, strlen(remuser)+1);
191 	(void)write(s, cmd, strlen(cmd)+1);
192 	if (read(s, &c, 1) != 1) {
193 		(void)fprintf(stderr,
194 		    "rcmd: %s: %s\n", *ahost, strerror(errno));
195 		goto bad2;
196 	}
197 	if (c != 0) {
198 		while (read(s, &c, 1) == 1) {
199 			(void)write(STDERR_FILENO, &c, 1);
200 			if (c == '\n')
201 				break;
202 		}
203 		goto bad2;
204 	}
205 	sigsetmask(oldmask);
206 	return (s);
207 bad2:
208 	if (lport)
209 		(void)close(*fd2p);
210 bad:
211 	(void)close(s);
212 	sigsetmask(oldmask);
213 	return (-1);
214 }
215 
216 int
217 rresvport(alport)
218 	int *alport;
219 {
220 	struct sockaddr_in sin;
221 	int s;
222 
223 	sin.sin_len = sizeof(struct sockaddr_in);
224 	sin.sin_family = AF_INET;
225 	sin.sin_addr.s_addr = INADDR_ANY;
226 	s = socket(AF_INET, SOCK_STREAM, 0);
227 	if (s < 0)
228 		return (-1);
229 	for (;;) {
230 		sin.sin_port = htons((u_short)*alport);
231 		if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) >= 0)
232 			return (s);
233 		if (errno != EADDRINUSE) {
234 			(void)close(s);
235 			return (-1);
236 		}
237 		(*alport)--;
238 		if (*alport == IPPORT_RESERVED/2) {
239 			(void)close(s);
240 			errno = EAGAIN;		/* close */
241 			return (-1);
242 		}
243 	}
244 }
245 
246 int	__check_rhosts_file = 1;
247 char	*__rcmd_errstr;
248 
249 int
250 ruserok(rhost, superuser, ruser, luser)
251 	const char *rhost, *ruser, *luser;
252 	int superuser;
253 {
254 	struct hostent *hp;
255 	char **ap;
256 	int i;
257 #define MAXADDRS	35
258 	u_int32_t addrs[MAXADDRS + 1];
259 
260 	if ((hp = gethostbyname(rhost)) == NULL)
261 		return (-1);
262 	for (i = 0, ap = hp->h_addr_list; *ap && i < MAXADDRS; ++ap, ++i)
263 		bcopy(*ap, &addrs[i], sizeof(addrs[i]));
264 	addrs[i] = 0;
265 
266 	for (i = 0; i < MAXADDRS && addrs[i]; i++)
267 		if (iruserok((u_long)addrs[i], superuser, ruser, luser) == 0)
268 			return (0);
269 	return (-1);
270 }
271 
272 /*
273  * New .rhosts strategy: We are passed an ip address. We spin through
274  * hosts.equiv and .rhosts looking for a match. When the .rhosts only
275  * has ip addresses, we don't have to trust a nameserver.  When it
276  * contains hostnames, we spin through the list of addresses the nameserver
277  * gives us and look for a match.
278  *
279  * Returns 0 if ok, -1 if not ok.
280  */
281 int
282 iruserok(raddr, superuser, ruser, luser)
283 	u_int32_t raddr;
284 	int superuser;
285 	const char *ruser, *luser;
286 {
287 	register char *cp;
288 	struct stat sbuf;
289 	struct passwd *pwd;
290 	FILE *hostf;
291 	uid_t uid;
292 	int first;
293 	char pbuf[MAXPATHLEN];
294 
295 	first = 1;
296 	hostf = superuser ? NULL : fopen(_PATH_HEQUIV, "r");
297 again:
298 	if (hostf) {
299 		if (__ivaliduser(hostf, raddr, luser, ruser) == 0) {
300 			(void)fclose(hostf);
301 			return (0);
302 		}
303 		(void)fclose(hostf);
304 	}
305 	if (first == 1 && (__check_rhosts_file || superuser)) {
306 		first = 0;
307 		if ((pwd = getpwnam(luser)) == NULL)
308 			return (-1);
309 		(void)strcpy(pbuf, pwd->pw_dir);
310 		(void)strcat(pbuf, "/.rhosts");
311 
312 		/*
313 		 * Change effective uid while opening .rhosts.  If root and
314 		 * reading an NFS mounted file system, can't read files that
315 		 * are protected read/write owner only.
316 		 */
317 		uid = geteuid();
318 		(void)seteuid(pwd->pw_uid);
319 		hostf = fopen(pbuf, "r");
320 		(void)seteuid(uid);
321 
322 		if (hostf == NULL)
323 			return (-1);
324 		/*
325 		 * If not a regular file, or is owned by someone other than
326 		 * user or root or if writeable by anyone but the owner, quit.
327 		 */
328 		cp = NULL;
329 		if (lstat(pbuf, &sbuf) < 0)
330 			cp = ".rhosts lstat failed";
331 		else if (!S_ISREG(sbuf.st_mode))
332 			cp = ".rhosts not regular file";
333 		else if (fstat(fileno(hostf), &sbuf) < 0)
334 			cp = ".rhosts fstat failed";
335 		else if (sbuf.st_uid && sbuf.st_uid != pwd->pw_uid)
336 			cp = "bad .rhosts owner";
337 		else if (sbuf.st_mode & (S_IWGRP|S_IWOTH))
338 			cp = ".rhosts writeable by other than owner";
339 		/* If there were any problems, quit. */
340 		if (cp) {
341 			__rcmd_errstr = cp;
342 			(void)fclose(hostf);
343 			return (-1);
344 		}
345 		goto again;
346 	}
347 	return (-1);
348 }
349 
350 /*
351  * XXX
352  * Don't make static, used by lpd(8).
353  *
354  * Returns 0 if ok, -1 if not ok.
355  */
356 int
357 __ivaliduser(hostf, raddrl, luser, ruser)
358 	FILE *hostf;
359 	u_long raddrl;
360 	const char *luser, *ruser;
361 {
362 	register char *user, *p;
363 	int ch;
364 	char buf[MAXHOSTNAMELEN + 128];		/* host + login */
365 	const char *auser, *ahost;
366 	int hostok, userok;
367 	char *rhost = (char *)-1;
368 	char domain[MAXHOSTNAMELEN];
369 	u_int32_t raddr = (u_int32_t)raddrl;
370 
371 	getdomainname(domain, sizeof(domain));
372 
373 	while (fgets(buf, sizeof(buf), hostf)) {
374 		p = buf;
375 		/* Skip lines that are too long. */
376 		if (strchr(p, '\n') == NULL) {
377 			while ((ch = getc(hostf)) != '\n' && ch != EOF)
378 				;
379 			continue;
380 		}
381 		if (*p == '#')
382 			continue;
383 		while (*p != '\n' && *p != ' ' && *p != '\t' && *p != '\0') {
384 			*p = isupper(*p) ? tolower(*p) : *p;
385 			p++;
386 		}
387 		if (*p == ' ' || *p == '\t') {
388 			*p++ = '\0';
389 			while (*p == ' ' || *p == '\t')
390 				p++;
391 			user = p;
392 			while (*p != '\n' && *p != ' ' &&
393 			    *p != '\t' && *p != '\0')
394 				p++;
395 		} else
396 			user = p;
397 		*p = '\0';
398 
399 		if (p == buf)
400 			continue;
401 
402 		auser = *user ? user : luser;
403 		ahost = buf;
404 
405 		/*
406 		 * innetgr() must lookup a hostname (we do not attempt
407 		 * to change the semantics so that netgroups may have
408 		 * #.#.#.# addresses in the list.)
409 		 */
410 		if (ahost[0] == '+')
411 			switch (ahost[1]) {
412 			case '\0':
413 				hostok = 1;
414 				break;
415 			case '@':
416 				if (rhost == (char *)-1)
417 					rhost = __gethostloop(raddr);
418 				hostok = 0;
419 				if (rhost)
420 					hostok = innetgr(&ahost[2], rhost,
421 					    NULL, domain);
422 				break;
423 			default:
424 				hostok = __icheckhost(raddr, &ahost[1]);
425 				break;
426 			}
427 		else if (ahost[0] == '-')
428 			switch (ahost[1]) {
429 			case '\0':
430 				hostok = -1;
431 				break;
432 			case '@':
433 				if (rhost == (char *)-1)
434 					rhost = __gethostloop(raddr);
435 				hostok = 0;
436 				if (rhost)
437 					hostok = -innetgr(&ahost[2], rhost,
438 					    NULL, domain);
439 				break;
440 			default:
441 				hostok = -__icheckhost(raddr, &ahost[1]);
442 				break;
443 			}
444 		else
445 			hostok = __icheckhost(raddr, ahost);
446 
447 
448 		if (auser[0] == '+')
449 			switch (auser[1]) {
450 			case '\0':
451 				userok = 1;
452 				break;
453 			case '@':
454 				userok = innetgr(&auser[2], NULL, ruser,
455 				    domain);
456 				break;
457 			default:
458 				userok = strcmp(ruser, &auser[1]) ? 0 : 1;
459 				break;
460 			}
461 		else if (auser[0] == '-')
462 			switch (auser[1]) {
463 			case '\0':
464 				userok = -1;
465 				break;
466 			case '@':
467 				userok = -innetgr(&auser[2], NULL, ruser,
468 				    domain);
469 				break;
470 			default:
471 				userok = strcmp(ruser, &auser[1]) ? 0 : -1;
472 				break;
473 			}
474 		else
475 			userok = strcmp(ruser, auser) ? 0 : 1;
476 
477 		/* Check if one component did not match */
478 		if (hostok == 0 || userok == 0)
479 			continue;
480 
481 		/* Check if we got a forbidden pair */
482 		if (userok <= -1 || hostok <= -1)
483 			return (-1);
484 
485 		/* Check if we got a valid pair */
486 		if (hostok >= 1 && userok >= 1)
487 			return (0);
488 	}
489 	return (-1);
490 }
491 
492 /*
493  * Returns "true" if match, 0 if no match.  If we do not find any
494  * semblance of an A->PTR->A loop, allow a simple #.#.#.# match to work.
495  */
496 static int
497 __icheckhost(raddr, lhost)
498 	u_int32_t raddr;
499 	const char *lhost;
500 {
501 	register struct hostent *hp;
502 	register char **pp;
503 	struct in_addr in;
504 
505 	hp = gethostbyname(lhost);
506 	if (hp != NULL) {
507 		/* Spin through ip addresses. */
508 		for (pp = hp->h_addr_list; *pp; ++pp)
509 			if (!bcmp(&raddr, *pp, sizeof(raddr)))
510 				return (1);
511 	}
512 
513 	in.s_addr = raddr;
514 	if (strcmp(lhost, inet_ntoa(in)) == 0)
515 		return (1);
516 	return (0);
517 }
518 
519 /*
520  * Return the hostname associated with the supplied address.
521  * Do a reverse lookup as well for security. If a loop cannot
522  * be found, pack the result of inet_ntoa() into the string.
523  */
524 static char *
525 __gethostloop(raddr)
526 	u_int32_t raddr;
527 {
528 	static char remotehost[MAXHOSTNAMELEN];
529 	struct hostent *hp;
530 	struct in_addr in;
531 
532 	hp = gethostbyaddr((char *) &raddr, sizeof(raddr), AF_INET);
533 	if (hp == NULL)
534 		return (NULL);
535 
536 	/*
537 	 * Look up the name and check that the supplied
538 	 * address is in the list
539 	 */
540 	strncpy(remotehost, hp->h_name, sizeof(remotehost) - 1);
541 	remotehost[sizeof(remotehost) - 1] = '\0';
542 	hp = gethostbyname(remotehost);
543 	if (hp == NULL)
544 		return (NULL);
545 
546 	for (; hp->h_addr_list[0] != NULL; hp->h_addr_list++)
547 		if (!bcmp(hp->h_addr_list[0], (caddr_t)&raddr, sizeof(raddr)))
548 			return (remotehost);
549 
550 	/*
551 	 * either the DNS adminstrator has made a configuration
552 	 * mistake, or someone has attempted to spoof us
553 	 */
554 	in.s_addr = raddr;
555 	syslog(LOG_NOTICE, "rcmd: address %s not listed for host %s",
556 	    inet_ntoa(in), hp->h_name);
557 	return (NULL);
558 }
559