xref: /openbsd-src/lib/libc/net/rcmd.c (revision d4b79a2488da7c06172bd5919033d6d93e720c6d)
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.17 1996/09/03 10:53:37 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 *, u_long, 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 	u_short rport;
67 	const char *locuser, *remuser, *cmd;
68 	int *fd2p;
69 {
70 	struct hostent *hp;
71 	struct sockaddr_in sin, from;
72 	fd_set reads;
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 ((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 
167 		if (s2 < 0)
168 			goto bad;
169 		listen(s2, 1);
170 		(void)snprintf(num, sizeof(num), "%d", lport);
171 		if (write(s, num, strlen(num)+1) != strlen(num)+1) {
172 			(void)fprintf(stderr,
173 			    "rcmd: write (setting up stderr): %s\n",
174 			    strerror(errno));
175 			(void)close(s2);
176 			goto bad;
177 		}
178 again:
179 		FD_ZERO(&reads);
180 		FD_SET(s, &reads);
181 		FD_SET(s2, &reads);
182 		errno = 0;
183 		if (select(MAX(s, s2) + 1, &reads, 0, 0, 0) < 1 ||
184 		    !FD_ISSET(s2, &reads)) {
185 			if (errno != 0)
186 				(void)fprintf(stderr,
187 				    "rcmd: select (setting up stderr): %s\n",
188 				    strerror(errno));
189 			else
190 				(void)fprintf(stderr,
191 				"select: protocol failure in circuit setup\n");
192 			(void)close(s2);
193 			goto bad;
194 		}
195 		s3 = accept(s2, (struct sockaddr *)&from, &len);
196 		/*
197 		 * XXX careful for ftp bounce attacks. If discovered, shut them
198 		 * down and check for the real auxiliary channel to connect.
199 		 */
200 		if (from.sin_family == AF_INET && from.sin_port == htons(20)) {
201 			close(s3);
202 			goto again;
203 		}
204 		(void)close(s2);
205 		if (s3 < 0) {
206 			(void)fprintf(stderr,
207 			    "rcmd: accept: %s\n", strerror(errno));
208 			lport = 0;
209 			goto bad;
210 		}
211 		*fd2p = s3;
212 		from.sin_port = ntohs(from.sin_port);
213 		if (from.sin_family != AF_INET ||
214 		    from.sin_port >= IPPORT_RESERVED ||
215 		    from.sin_port < IPPORT_RESERVED / 2) {
216 			(void)fprintf(stderr,
217 			    "socket: protocol failure in circuit setup.\n");
218 			goto bad2;
219 		}
220 	}
221 	(void)write(s, locuser, strlen(locuser)+1);
222 	(void)write(s, remuser, strlen(remuser)+1);
223 	(void)write(s, cmd, strlen(cmd)+1);
224 	if (read(s, &c, 1) != 1) {
225 		(void)fprintf(stderr,
226 		    "rcmd: %s: %s\n", *ahost, strerror(errno));
227 		goto bad2;
228 	}
229 	if (c != 0) {
230 		while (read(s, &c, 1) == 1) {
231 			(void)write(STDERR_FILENO, &c, 1);
232 			if (c == '\n')
233 				break;
234 		}
235 		goto bad2;
236 	}
237 	sigsetmask(oldmask);
238 	return (s);
239 bad2:
240 	if (lport)
241 		(void)close(*fd2p);
242 bad:
243 	(void)close(s);
244 	sigsetmask(oldmask);
245 	return (-1);
246 }
247 
248 int
249 rresvport(alport)
250 	int *alport;
251 {
252 	struct sockaddr_in sin;
253 	int s;
254 
255 	bzero(&sin, sizeof sin);
256 	sin.sin_len = sizeof(struct sockaddr_in);
257 	sin.sin_family = AF_INET;
258 	sin.sin_addr.s_addr = INADDR_ANY;
259 	s = socket(AF_INET, SOCK_STREAM, 0);
260 	if (s < 0)
261 		return (-1);
262 	sin.sin_port = htons((u_short)*alport);
263 	if (*alport != IPPORT_RESERVED - 1) {
264 		if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) >= 0)
265 			return (s);
266 		if (errno != EADDRINUSE) {
267 			(void)close(s);
268 			return (-1);
269 		}
270 	}
271 	sin.sin_port = 0;
272 	if (bindresvport(s, &sin) == -1) {
273 		(void)close(s);
274 		return (-1);
275 	}
276 	*alport = (int)ntohs(sin.sin_port);
277 	return (s);
278 }
279 
280 int	__check_rhosts_file = 1;
281 char	*__rcmd_errstr;
282 
283 int
284 ruserok(rhost, superuser, ruser, luser)
285 	const char *rhost, *ruser, *luser;
286 	int superuser;
287 {
288 	struct hostent *hp;
289 	char **ap;
290 	int i;
291 #define MAXADDRS	35
292 	u_int32_t addrs[MAXADDRS + 1];
293 
294 	if ((hp = gethostbyname(rhost)) == NULL)
295 		return (-1);
296 	for (i = 0, ap = hp->h_addr_list; *ap && i < MAXADDRS; ++ap, ++i)
297 		bcopy(*ap, &addrs[i], sizeof(addrs[i]));
298 	addrs[i] = 0;
299 
300 	for (i = 0; i < MAXADDRS && addrs[i]; i++)
301 		if (iruserok((u_long)addrs[i], superuser, ruser, luser) == 0)
302 			return (0);
303 	return (-1);
304 }
305 
306 /*
307  * New .rhosts strategy: We are passed an ip address. We spin through
308  * hosts.equiv and .rhosts looking for a match. When the .rhosts only
309  * has ip addresses, we don't have to trust a nameserver.  When it
310  * contains hostnames, we spin through the list of addresses the nameserver
311  * gives us and look for a match.
312  *
313  * Returns 0 if ok, -1 if not ok.
314  */
315 int
316 iruserok(raddr, superuser, ruser, luser)
317 	u_int32_t raddr;
318 	int superuser;
319 	const char *ruser, *luser;
320 {
321 	register char *cp;
322 	struct stat sbuf;
323 	struct passwd *pwd;
324 	FILE *hostf;
325 	uid_t uid;
326 	int first;
327 	char pbuf[MAXPATHLEN];
328 
329 	first = 1;
330 	hostf = superuser ? NULL : fopen(_PATH_HEQUIV, "r");
331 again:
332 	if (hostf) {
333 		if (__ivaliduser(hostf, raddr, luser, ruser) == 0) {
334 			(void)fclose(hostf);
335 			return (0);
336 		}
337 		(void)fclose(hostf);
338 	}
339 	if (first == 1 && (__check_rhosts_file || superuser)) {
340 		first = 0;
341 		if ((pwd = getpwnam(luser)) == NULL)
342 			return (-1);
343 		(void)strcpy(pbuf, pwd->pw_dir);
344 		(void)strcat(pbuf, "/.rhosts");
345 
346 		/*
347 		 * Change effective uid while opening .rhosts.  If root and
348 		 * reading an NFS mounted file system, can't read files that
349 		 * are protected read/write owner only.
350 		 */
351 		uid = geteuid();
352 		(void)seteuid(pwd->pw_uid);
353 		hostf = fopen(pbuf, "r");
354 		(void)seteuid(uid);
355 
356 		if (hostf == NULL)
357 			return (-1);
358 		/*
359 		 * If not a regular file, or is owned by someone other than
360 		 * user or root or if writeable by anyone but the owner, quit.
361 		 */
362 		cp = NULL;
363 		if (lstat(pbuf, &sbuf) < 0)
364 			cp = ".rhosts lstat failed";
365 		else if (!S_ISREG(sbuf.st_mode))
366 			cp = ".rhosts not regular file";
367 		else if (fstat(fileno(hostf), &sbuf) < 0)
368 			cp = ".rhosts fstat failed";
369 		else if (sbuf.st_uid && sbuf.st_uid != pwd->pw_uid)
370 			cp = "bad .rhosts owner";
371 		else if (sbuf.st_mode & (S_IWGRP|S_IWOTH))
372 			cp = ".rhosts writeable by other than owner";
373 		/* If there were any problems, quit. */
374 		if (cp) {
375 			__rcmd_errstr = cp;
376 			(void)fclose(hostf);
377 			return (-1);
378 		}
379 		goto again;
380 	}
381 	return (-1);
382 }
383 
384 /*
385  * XXX
386  * Don't make static, used by lpd(8).
387  *
388  * Returns 0 if ok, -1 if not ok.
389  */
390 int
391 __ivaliduser(hostf, raddrl, luser, ruser)
392 	FILE *hostf;
393 	u_long raddrl;
394 	const char *luser, *ruser;
395 {
396 	register char *user, *p;
397 	int ch;
398 	char buf[MAXHOSTNAMELEN + 128];		/* host + login */
399 	const char *auser, *ahost;
400 	int hostok, userok;
401 	char *rhost = (char *)-1;
402 	char domain[MAXHOSTNAMELEN];
403 	u_int32_t raddr = (u_int32_t)raddrl;
404 
405 	getdomainname(domain, sizeof(domain));
406 
407 	while (fgets(buf, sizeof(buf), hostf)) {
408 		p = buf;
409 		/* Skip lines that are too long. */
410 		if (strchr(p, '\n') == NULL) {
411 			while ((ch = getc(hostf)) != '\n' && ch != EOF)
412 				;
413 			continue;
414 		}
415 		if (*p == '#')
416 			continue;
417 		while (*p != '\n' && *p != ' ' && *p != '\t' && *p != '\0') {
418 			*p = isupper(*p) ? tolower(*p) : *p;
419 			p++;
420 		}
421 		if (*p == ' ' || *p == '\t') {
422 			*p++ = '\0';
423 			while (*p == ' ' || *p == '\t')
424 				p++;
425 			user = p;
426 			while (*p != '\n' && *p != ' ' &&
427 			    *p != '\t' && *p != '\0')
428 				p++;
429 		} else
430 			user = p;
431 		*p = '\0';
432 
433 		if (p == buf)
434 			continue;
435 
436 		auser = *user ? user : luser;
437 		ahost = buf;
438 
439 		/*
440 		 * innetgr() must lookup a hostname (we do not attempt
441 		 * to change the semantics so that netgroups may have
442 		 * #.#.#.# addresses in the list.)
443 		 */
444 		if (ahost[0] == '+')
445 			switch (ahost[1]) {
446 			case '\0':
447 				hostok = 1;
448 				break;
449 			case '@':
450 				if (rhost == (char *)-1)
451 					rhost = __gethostloop(raddr);
452 				hostok = 0;
453 				if (rhost)
454 					hostok = innetgr(&ahost[2], rhost,
455 					    NULL, domain);
456 				break;
457 			default:
458 				hostok = __icheckhost(raddr, &ahost[1]);
459 				break;
460 			}
461 		else if (ahost[0] == '-')
462 			switch (ahost[1]) {
463 			case '\0':
464 				hostok = -1;
465 				break;
466 			case '@':
467 				if (rhost == (char *)-1)
468 					rhost = __gethostloop(raddr);
469 				hostok = 0;
470 				if (rhost)
471 					hostok = -innetgr(&ahost[2], rhost,
472 					    NULL, domain);
473 				break;
474 			default:
475 				hostok = -__icheckhost(raddr, &ahost[1]);
476 				break;
477 			}
478 		else
479 			hostok = __icheckhost(raddr, ahost);
480 
481 
482 		if (auser[0] == '+')
483 			switch (auser[1]) {
484 			case '\0':
485 				userok = 1;
486 				break;
487 			case '@':
488 				userok = innetgr(&auser[2], NULL, ruser,
489 				    domain);
490 				break;
491 			default:
492 				userok = strcmp(ruser, &auser[1]) ? 0 : 1;
493 				break;
494 			}
495 		else if (auser[0] == '-')
496 			switch (auser[1]) {
497 			case '\0':
498 				userok = -1;
499 				break;
500 			case '@':
501 				userok = -innetgr(&auser[2], NULL, ruser,
502 				    domain);
503 				break;
504 			default:
505 				userok = strcmp(ruser, &auser[1]) ? 0 : -1;
506 				break;
507 			}
508 		else
509 			userok = strcmp(ruser, auser) ? 0 : 1;
510 
511 		/* Check if one component did not match */
512 		if (hostok == 0 || userok == 0)
513 			continue;
514 
515 		/* Check if we got a forbidden pair */
516 		if (userok <= -1 || hostok <= -1)
517 			return (-1);
518 
519 		/* Check if we got a valid pair */
520 		if (hostok >= 1 && userok >= 1)
521 			return (0);
522 	}
523 	return (-1);
524 }
525 
526 /*
527  * Returns "true" if match, 0 if no match.  If we do not find any
528  * semblance of an A->PTR->A loop, allow a simple #.#.#.# match to work.
529  */
530 static int
531 __icheckhost(raddr, lhost)
532 	u_int32_t raddr;
533 	const char *lhost;
534 {
535 	register struct hostent *hp;
536 	register char **pp;
537 	struct in_addr in;
538 
539 	hp = gethostbyname(lhost);
540 	if (hp != NULL) {
541 		/* Spin through ip addresses. */
542 		for (pp = hp->h_addr_list; *pp; ++pp)
543 			if (!bcmp(&raddr, *pp, sizeof(raddr)))
544 				return (1);
545 	}
546 
547 	in.s_addr = raddr;
548 	if (strcmp(lhost, inet_ntoa(in)) == 0)
549 		return (1);
550 	return (0);
551 }
552 
553 /*
554  * Return the hostname associated with the supplied address.
555  * Do a reverse lookup as well for security. If a loop cannot
556  * be found, pack the result of inet_ntoa() into the string.
557  */
558 static char *
559 __gethostloop(raddr)
560 	u_int32_t raddr;
561 {
562 	static char remotehost[MAXHOSTNAMELEN];
563 	struct hostent *hp;
564 	struct in_addr in;
565 
566 	hp = gethostbyaddr((char *) &raddr, sizeof(raddr), AF_INET);
567 	if (hp == NULL)
568 		return (NULL);
569 
570 	/*
571 	 * Look up the name and check that the supplied
572 	 * address is in the list
573 	 */
574 	strncpy(remotehost, hp->h_name, sizeof(remotehost) - 1);
575 	remotehost[sizeof(remotehost) - 1] = '\0';
576 	hp = gethostbyname(remotehost);
577 	if (hp == NULL)
578 		return (NULL);
579 
580 	for (; hp->h_addr_list[0] != NULL; hp->h_addr_list++)
581 		if (!bcmp(hp->h_addr_list[0], (caddr_t)&raddr, sizeof(raddr)))
582 			return (remotehost);
583 
584 	/*
585 	 * either the DNS adminstrator has made a configuration
586 	 * mistake, or someone has attempted to spoof us
587 	 */
588 	in.s_addr = raddr;
589 	syslog(LOG_NOTICE, "rcmd: address %s not listed for host %s",
590 	    inet_ntoa(in), hp->h_name);
591 	return (NULL);
592 }
593