xref: /openbsd-src/lib/libc/net/rcmd.c (revision 034b81d3f738d705c4e4c93567381936548b8e4e)
1 /*
2  * Copyright (c) 1995, 1996 Theo de Raadt.  All rights reserved.
3  * Copyright (c) 1983, 1993, 1994
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. All advertising materials mentioning features or use of this software
15  *    must display the following acknowledgement:
16  *	This product includes software developed by the University of
17  *	California, Berkeley and its contributors.
18  *	This product includes software developed by Theo de Raadt.
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 static char *rcsid = "$OpenBSD: rcmd.c,v 1.25 1997/07/06 07:55:58 deraadt Exp $";
38 #endif /* LIBC_SCCS and not lint */
39 
40 #include <sys/param.h>
41 #include <sys/socket.h>
42 #include <sys/stat.h>
43 
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
46 
47 #include <signal.h>
48 #include <fcntl.h>
49 #include <netdb.h>
50 #include <unistd.h>
51 #include <pwd.h>
52 #include <errno.h>
53 #include <stdio.h>
54 #include <ctype.h>
55 #include <string.h>
56 #include <syslog.h>
57 #include <stdlib.h>
58 
59 int	__ivaliduser __P((FILE *, in_addr_t, const char *, const char *));
60 static int __icheckhost __P((u_int32_t, const char *));
61 static char *__gethostloop __P((u_int32_t));
62 
63 int
64 rcmd(ahost, rport, locuser, remuser, cmd, fd2p)
65 	char **ahost;
66 	in_port_t rport;
67 	const char *locuser, *remuser, *cmd;
68 	int *fd2p;
69 {
70 	struct hostent *hp;
71 	struct sockaddr_in sin, from;
72 	fd_set *readsp = NULL;
73 	int oldmask;
74 	pid_t pid;
75 	int s, lport, timo;
76 	char c, *p;
77 
78 	/* call rcmdsh() with specified remote shell if appropriate. */
79 	if (!issetugid() && (p = getenv("RSH"))) {
80 		struct servent *sp = getservbyname("shell", "tcp");
81 
82 		if (sp && sp->s_port == rport)
83 			return (rcmdsh(ahost, rport, locuser, remuser,
84 			    cmd, p));
85 	}
86 
87 	/* use rsh(1) if non-root and remote port is shell. */
88 	if (geteuid()) {
89 		struct servent *sp = getservbyname("shell", "tcp");
90 
91 		if (sp && sp->s_port == rport)
92 			return (rcmdsh(ahost, rport, locuser, remuser,
93 			    cmd, NULL));
94 	}
95 
96 	pid = getpid();
97 	hp = gethostbyname(*ahost);
98 	if (hp == NULL) {
99 		herror(*ahost);
100 		return (-1);
101 	}
102 	*ahost = hp->h_name;
103 
104 	oldmask = sigblock(sigmask(SIGURG));
105 	for (timo = 1, lport = IPPORT_RESERVED - 1;;) {
106 		s = rresvport(&lport);
107 		if (s < 0) {
108 			if (errno == EAGAIN)
109 				(void)fprintf(stderr,
110 				    "rcmd: socket: All ports in use\n");
111 			else
112 				(void)fprintf(stderr, "rcmd: socket: %s\n",
113 				    strerror(errno));
114 			sigsetmask(oldmask);
115 			return (-1);
116 		}
117 		fcntl(s, F_SETOWN, pid);
118 		bzero(&sin, sizeof sin);
119 		sin.sin_len = sizeof(struct sockaddr_in);
120 		sin.sin_family = hp->h_addrtype;
121 		sin.sin_port = rport;
122 		bcopy(hp->h_addr_list[0], &sin.sin_addr, hp->h_length);
123 		if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) >= 0)
124 			break;
125 		(void)close(s);
126 		if (errno == EADDRINUSE) {
127 			lport--;
128 			continue;
129 		}
130 		if (errno == ECONNREFUSED && timo <= 16) {
131 			(void)sleep(timo);
132 			timo *= 2;
133 			continue;
134 		}
135 		if (hp->h_addr_list[1] != NULL) {
136 			int oerrno = errno;
137 
138 			(void)fprintf(stderr, "connect to address %s: ",
139 			    inet_ntoa(sin.sin_addr));
140 			errno = oerrno;
141 			perror(0);
142 			hp->h_addr_list++;
143 			bcopy(hp->h_addr_list[0], &sin.sin_addr, hp->h_length);
144 			(void)fprintf(stderr, "Trying %s...\n",
145 			    inet_ntoa(sin.sin_addr));
146 			continue;
147 		}
148 		(void)fprintf(stderr, "%s: %s\n", hp->h_name, strerror(errno));
149 		sigsetmask(oldmask);
150 		return (-1);
151 	}
152 #if 0
153 	/*
154 	 * try to rresvport() to the same port. This will make rresvport()
155 	 * fail it's first bind, resulting in it choosing a random port.
156 	 */
157 	lport--;
158 #endif
159 	if (fd2p == 0) {
160 		write(s, "", 1);
161 		lport = 0;
162 	} else {
163 		char num[8];
164 		int s2 = rresvport(&lport), s3;
165 		int len = sizeof(from);
166 		int fdssize = howmany(MAX(s, s2)+1, NFDBITS) * sizeof(fd_mask);
167 
168 		if (s2 < 0)
169 			goto bad;
170 		readsp = (fd_set *)malloc(fdssize);
171 		if (readsp == NULL)
172 			goto bad;
173 		listen(s2, 1);
174 		(void)snprintf(num, sizeof(num), "%d", lport);
175 		if (write(s, num, strlen(num)+1) != strlen(num)+1) {
176 			(void)fprintf(stderr,
177 			    "rcmd: write (setting up stderr): %s\n",
178 			    strerror(errno));
179 			(void)close(s2);
180 			goto bad;
181 		}
182 again:
183 		bzero(readsp, fdssize);
184 		FD_SET(s, readsp);
185 		FD_SET(s2, readsp);
186 		errno = 0;
187 		if (select(MAX(s, s2) + 1, readsp, 0, 0, 0) < 1 ||
188 		    !FD_ISSET(s2, readsp)) {
189 			if (errno != 0)
190 				(void)fprintf(stderr,
191 				    "rcmd: select (setting up stderr): %s\n",
192 				    strerror(errno));
193 			else
194 				(void)fprintf(stderr,
195 				"select: protocol failure in circuit setup\n");
196 			(void)close(s2);
197 			goto bad;
198 		}
199 		s3 = accept(s2, (struct sockaddr *)&from, &len);
200 		/*
201 		 * XXX careful for ftp bounce attacks. If discovered, shut them
202 		 * down and check for the real auxiliary channel to connect.
203 		 */
204 		if (from.sin_family == AF_INET && from.sin_port == htons(20)) {
205 			close(s3);
206 			goto again;
207 		}
208 		(void)close(s2);
209 		if (s3 < 0) {
210 			(void)fprintf(stderr,
211 			    "rcmd: accept: %s\n", strerror(errno));
212 			lport = 0;
213 			goto bad;
214 		}
215 		*fd2p = s3;
216 		from.sin_port = ntohs(from.sin_port);
217 		if (from.sin_family != AF_INET ||
218 		    from.sin_port >= IPPORT_RESERVED ||
219 		    from.sin_port < IPPORT_RESERVED / 2) {
220 			(void)fprintf(stderr,
221 			    "socket: protocol failure in circuit setup.\n");
222 			goto bad2;
223 		}
224 	}
225 	(void)write(s, locuser, strlen(locuser)+1);
226 	(void)write(s, remuser, strlen(remuser)+1);
227 	(void)write(s, cmd, strlen(cmd)+1);
228 	if (read(s, &c, 1) != 1) {
229 		(void)fprintf(stderr,
230 		    "rcmd: %s: %s\n", *ahost, strerror(errno));
231 		goto bad2;
232 	}
233 	if (c != 0) {
234 		while (read(s, &c, 1) == 1) {
235 			(void)write(STDERR_FILENO, &c, 1);
236 			if (c == '\n')
237 				break;
238 		}
239 		goto bad2;
240 	}
241 	sigsetmask(oldmask);
242 	free(readsp);
243 	return (s);
244 bad2:
245 	if (lport)
246 		(void)close(*fd2p);
247 bad:
248 	if (readsp)
249 		free(readsp);
250 	(void)close(s);
251 	sigsetmask(oldmask);
252 	return (-1);
253 }
254 
255 int
256 rresvport(alport)
257 	int *alport;
258 {
259 	struct sockaddr_in sin;
260 	int s;
261 
262 	bzero(&sin, sizeof sin);
263 	sin.sin_len = sizeof(struct sockaddr_in);
264 	sin.sin_family = AF_INET;
265 	sin.sin_addr.s_addr = INADDR_ANY;
266 	s = socket(AF_INET, SOCK_STREAM, 0);
267 	if (s < 0)
268 		return (-1);
269 	sin.sin_port = htons((in_port_t)*alport);
270 	if (*alport < IPPORT_RESERVED - 1) {
271 		if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) >= 0)
272 			return (s);
273 		if (errno != EADDRINUSE) {
274 			(void)close(s);
275 			return (-1);
276 		}
277 	}
278 	sin.sin_port = 0;
279 	if (bindresvport(s, &sin) == -1) {
280 		(void)close(s);
281 		return (-1);
282 	}
283 	*alport = (int)ntohs(sin.sin_port);
284 	return (s);
285 }
286 
287 int	__check_rhosts_file = 1;
288 char	*__rcmd_errstr;
289 
290 int
291 ruserok(rhost, superuser, ruser, luser)
292 	const char *rhost, *ruser, *luser;
293 	int superuser;
294 {
295 	struct hostent *hp;
296 	char **ap;
297 	int i;
298 #define MAXADDRS	35
299 	u_int32_t addrs[MAXADDRS + 1];
300 
301 	if ((hp = gethostbyname(rhost)) == NULL)
302 		return (-1);
303 	for (i = 0, ap = hp->h_addr_list; *ap && i < MAXADDRS; ++ap, ++i)
304 		bcopy(*ap, &addrs[i], sizeof(addrs[i]));
305 	addrs[i] = 0;
306 
307 	for (i = 0; i < MAXADDRS && addrs[i]; i++)
308 		if (iruserok((in_addr_t)addrs[i], superuser, ruser, luser) == 0)
309 			return (0);
310 	return (-1);
311 }
312 
313 /*
314  * New .rhosts strategy: We are passed an ip address. We spin through
315  * hosts.equiv and .rhosts looking for a match. When the .rhosts only
316  * has ip addresses, we don't have to trust a nameserver.  When it
317  * contains hostnames, we spin through the list of addresses the nameserver
318  * gives us and look for a match.
319  *
320  * Returns 0 if ok, -1 if not ok.
321  */
322 int
323 iruserok(raddr, superuser, ruser, luser)
324 	u_int32_t raddr;
325 	int superuser;
326 	const char *ruser, *luser;
327 {
328 	register char *cp;
329 	struct stat sbuf;
330 	struct passwd *pwd;
331 	FILE *hostf;
332 	uid_t uid;
333 	int first;
334 	char pbuf[MAXPATHLEN];
335 
336 	first = 1;
337 	hostf = superuser ? NULL : fopen(_PATH_HEQUIV, "r");
338 again:
339 	if (hostf) {
340 		if (__ivaliduser(hostf, raddr, luser, ruser) == 0) {
341 			(void)fclose(hostf);
342 			return (0);
343 		}
344 		(void)fclose(hostf);
345 	}
346 	if (first == 1 && (__check_rhosts_file || superuser)) {
347 		first = 0;
348 		if ((pwd = getpwnam(luser)) == NULL)
349 			return (-1);
350 		(void)strcpy(pbuf, pwd->pw_dir);
351 		(void)strcat(pbuf, "/.rhosts");
352 
353 		/*
354 		 * Change effective uid while opening .rhosts.  If root and
355 		 * reading an NFS mounted file system, can't read files that
356 		 * are protected read/write owner only.
357 		 */
358 		uid = geteuid();
359 		(void)seteuid(pwd->pw_uid);
360 		hostf = fopen(pbuf, "r");
361 		(void)seteuid(uid);
362 
363 		if (hostf == NULL)
364 			return (-1);
365 		/*
366 		 * If not a regular file, or is owned by someone other than
367 		 * user or root or if writeable by anyone but the owner, quit.
368 		 */
369 		cp = NULL;
370 		if (lstat(pbuf, &sbuf) < 0)
371 			cp = ".rhosts lstat failed";
372 		else if (!S_ISREG(sbuf.st_mode))
373 			cp = ".rhosts not regular file";
374 		else if (fstat(fileno(hostf), &sbuf) < 0)
375 			cp = ".rhosts fstat failed";
376 		else if (sbuf.st_uid && sbuf.st_uid != pwd->pw_uid)
377 			cp = "bad .rhosts owner";
378 		else if (sbuf.st_mode & (S_IWGRP|S_IWOTH))
379 			cp = ".rhosts writeable by other than owner";
380 		/* If there were any problems, quit. */
381 		if (cp) {
382 			__rcmd_errstr = cp;
383 			(void)fclose(hostf);
384 			return (-1);
385 		}
386 		goto again;
387 	}
388 	return (-1);
389 }
390 
391 /*
392  * XXX
393  * Don't make static, used by lpd(8).
394  *
395  * Returns 0 if ok, -1 if not ok.
396  */
397 int
398 __ivaliduser(hostf, raddrl, luser, ruser)
399 	FILE *hostf;
400 	in_addr_t raddrl;
401 	const char *luser, *ruser;
402 {
403 	register char *user, *p;
404 	int ch;
405 	char buf[MAXHOSTNAMELEN + 128];		/* host + login */
406 	const char *auser, *ahost;
407 	int hostok, userok;
408 	char *rhost = (char *)-1;
409 	char domain[MAXHOSTNAMELEN];
410 	u_int32_t raddr = (u_int32_t)raddrl;
411 
412 	getdomainname(domain, sizeof(domain));
413 
414 	while (fgets(buf, sizeof(buf), hostf)) {
415 		p = buf;
416 		/* Skip lines that are too long. */
417 		if (strchr(p, '\n') == NULL) {
418 			while ((ch = getc(hostf)) != '\n' && ch != EOF)
419 				;
420 			continue;
421 		}
422 		if (*p == '#')
423 			continue;
424 		while (*p != '\n' && *p != ' ' && *p != '\t' && *p != '\0') {
425 			if (!isprint(*p))
426 				goto bail;
427 			*p = isupper(*p) ? tolower(*p) : *p;
428 			p++;
429 		}
430 		if (*p == ' ' || *p == '\t') {
431 			*p++ = '\0';
432 			while (*p == ' ' || *p == '\t')
433 				p++;
434 			user = p;
435 			while (*p != '\n' && *p != ' ' &&
436 			    *p != '\t' && *p != '\0')
437 				p++;
438 		} else
439 			user = p;
440 		*p = '\0';
441 
442 		if (p == buf)
443 			continue;
444 
445 		auser = *user ? user : luser;
446 		ahost = buf;
447 
448 		/*
449 		 * innetgr() must lookup a hostname (we do not attempt
450 		 * to change the semantics so that netgroups may have
451 		 * #.#.#.# addresses in the list.)
452 		 */
453 		if (ahost[0] == '+')
454 			switch (ahost[1]) {
455 			case '\0':
456 				hostok = 1;
457 				break;
458 			case '@':
459 				if (rhost == (char *)-1)
460 					rhost = __gethostloop(raddr);
461 				hostok = 0;
462 				if (rhost)
463 					hostok = innetgr(&ahost[2], rhost,
464 					    NULL, domain);
465 				break;
466 			default:
467 				hostok = __icheckhost(raddr, &ahost[1]);
468 				break;
469 			}
470 		else if (ahost[0] == '-')
471 			switch (ahost[1]) {
472 			case '\0':
473 				hostok = -1;
474 				break;
475 			case '@':
476 				if (rhost == (char *)-1)
477 					rhost = __gethostloop(raddr);
478 				hostok = 0;
479 				if (rhost)
480 					hostok = -innetgr(&ahost[2], rhost,
481 					    NULL, domain);
482 				break;
483 			default:
484 				hostok = -__icheckhost(raddr, &ahost[1]);
485 				break;
486 			}
487 		else
488 			hostok = __icheckhost(raddr, ahost);
489 
490 
491 		if (auser[0] == '+')
492 			switch (auser[1]) {
493 			case '\0':
494 				userok = 1;
495 				break;
496 			case '@':
497 				userok = innetgr(&auser[2], NULL, ruser,
498 				    domain);
499 				break;
500 			default:
501 				userok = strcmp(ruser, &auser[1]) ? 0 : 1;
502 				break;
503 			}
504 		else if (auser[0] == '-')
505 			switch (auser[1]) {
506 			case '\0':
507 				userok = -1;
508 				break;
509 			case '@':
510 				userok = -innetgr(&auser[2], NULL, ruser,
511 				    domain);
512 				break;
513 			default:
514 				userok = strcmp(ruser, &auser[1]) ? 0 : -1;
515 				break;
516 			}
517 		else
518 			userok = strcmp(ruser, auser) ? 0 : 1;
519 
520 		/* Check if one component did not match */
521 		if (hostok == 0 || userok == 0)
522 			continue;
523 
524 		/* Check if we got a forbidden pair */
525 		if (userok <= -1 || hostok <= -1)
526 			return (-1);
527 
528 		/* Check if we got a valid pair */
529 		if (hostok >= 1 && userok >= 1)
530 			return (0);
531 	}
532 bail:
533 	return (-1);
534 }
535 
536 /*
537  * Returns "true" if match, 0 if no match.  If we do not find any
538  * semblance of an A->PTR->A loop, allow a simple #.#.#.# match to work.
539  */
540 static int
541 __icheckhost(raddr, lhost)
542 	u_int32_t raddr;
543 	const char *lhost;
544 {
545 	register struct hostent *hp;
546 	register char **pp;
547 	struct in_addr in;
548 
549 	hp = gethostbyname(lhost);
550 	if (hp != NULL) {
551 		/* Spin through ip addresses. */
552 		for (pp = hp->h_addr_list; *pp; ++pp)
553 			if (!bcmp(&raddr, *pp, sizeof(raddr)))
554 				return (1);
555 	}
556 
557 	in.s_addr = raddr;
558 	if (strcmp(lhost, inet_ntoa(in)) == 0)
559 		return (1);
560 	return (0);
561 }
562 
563 /*
564  * Return the hostname associated with the supplied address.
565  * Do a reverse lookup as well for security. If a loop cannot
566  * be found, pack the result of inet_ntoa() into the string.
567  */
568 static char *
569 __gethostloop(raddr)
570 	u_int32_t raddr;
571 {
572 	static char remotehost[MAXHOSTNAMELEN];
573 	struct hostent *hp;
574 	struct in_addr in;
575 
576 	hp = gethostbyaddr((char *) &raddr, sizeof(raddr), AF_INET);
577 	if (hp == NULL)
578 		return (NULL);
579 
580 	/*
581 	 * Look up the name and check that the supplied
582 	 * address is in the list
583 	 */
584 	strncpy(remotehost, hp->h_name, sizeof(remotehost) - 1);
585 	remotehost[sizeof(remotehost) - 1] = '\0';
586 	hp = gethostbyname(remotehost);
587 	if (hp == NULL)
588 		return (NULL);
589 
590 	for (; hp->h_addr_list[0] != NULL; hp->h_addr_list++)
591 		if (!bcmp(hp->h_addr_list[0], (caddr_t)&raddr, sizeof(raddr)))
592 			return (remotehost);
593 
594 	/*
595 	 * either the DNS adminstrator has made a configuration
596 	 * mistake, or someone has attempted to spoof us
597 	 */
598 	in.s_addr = raddr;
599 	syslog(LOG_NOTICE, "rcmd: address %s not listed for host %s",
600 	    inet_ntoa(in), hp->h_name);
601 	return (NULL);
602 }
603