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