xref: /freebsd/lib/libc/net/rcmd.c (revision 8e6b01171e30297084bb0b4457c4183c2746aacc)
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 sccsid[] = "@(#)rcmd.c	8.3 (Berkeley) 3/26/94";
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 #ifdef YP
55 #include <rpc/rpc.h>
56 #include <rpcsvc/yp_prot.h>
57 #include <rpcsvc/ypclnt.h>
58 #endif
59 
60 #define max(a, b)	((a > b) ? a : b)
61 
62 int	__ivaliduser __P((FILE *, u_long, const char *, const char *));
63 static int __icheckhost __P((u_long, char *));
64 
65 int
66 rcmd(ahost, rport, locuser, remuser, cmd, fd2p)
67 	char **ahost;
68 	u_short rport;
69 	const char *locuser, *remuser, *cmd;
70 	int *fd2p;
71 {
72 	struct hostent *hp;
73 	struct sockaddr_in sin, from;
74 	fd_set reads;
75 	long oldmask;
76 	pid_t pid;
77 	int s, lport, timo;
78 	char c;
79 
80 	pid = getpid();
81 	hp = gethostbyname(*ahost);
82 	if (hp == NULL) {
83 		herror(*ahost);
84 		return (-1);
85 	}
86 	*ahost = hp->h_name;
87 	oldmask = sigblock(sigmask(SIGURG));
88 	for (timo = 1, lport = IPPORT_RESERVED - 1;;) {
89 		s = rresvport(&lport);
90 		if (s < 0) {
91 			if (errno == EAGAIN)
92 				(void)fprintf(stderr,
93 				    "rcmd: socket: All ports in use\n");
94 			else
95 				(void)fprintf(stderr, "rcmd: socket: %s\n",
96 				    strerror(errno));
97 			sigsetmask(oldmask);
98 			return (-1);
99 		}
100 		fcntl(s, F_SETOWN, pid);
101 		sin.sin_family = hp->h_addrtype;
102 		bcopy(hp->h_addr_list[0], &sin.sin_addr, hp->h_length);
103 		sin.sin_port = rport;
104 		if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) >= 0)
105 			break;
106 		(void)close(s);
107 		if (errno == EADDRINUSE) {
108 			lport--;
109 			continue;
110 		}
111 		if (errno == ECONNREFUSED && timo <= 16) {
112 			(void)sleep(timo);
113 			timo *= 2;
114 			continue;
115 		}
116 		if (hp->h_addr_list[1] != NULL) {
117 			int oerrno = errno;
118 
119 			(void)fprintf(stderr, "connect to address %s: ",
120 			    inet_ntoa(sin.sin_addr));
121 			errno = oerrno;
122 			perror(0);
123 			hp->h_addr_list++;
124 			bcopy(hp->h_addr_list[0], &sin.sin_addr, hp->h_length);
125 			(void)fprintf(stderr, "Trying %s...\n",
126 			    inet_ntoa(sin.sin_addr));
127 			continue;
128 		}
129 		(void)fprintf(stderr, "%s: %s\n", hp->h_name, strerror(errno));
130 		sigsetmask(oldmask);
131 		return (-1);
132 	}
133 	lport--;
134 	if (fd2p == 0) {
135 		write(s, "", 1);
136 		lport = 0;
137 	} else {
138 		char num[8];
139 		int s2 = rresvport(&lport), s3;
140 		int len = sizeof(from);
141 		int nfds;
142 
143 		if (s2 < 0)
144 			goto bad;
145 		listen(s2, 1);
146 		(void)snprintf(num, sizeof(num), "%d", lport);
147 		if (write(s, num, strlen(num)+1) != strlen(num)+1) {
148 			(void)fprintf(stderr,
149 			    "rcmd: write (setting up stderr): %s\n",
150 			    strerror(errno));
151 			(void)close(s2);
152 			goto bad;
153 		}
154 		nfds = max(s, s2)+1;
155 		if(nfds > FD_SETSIZE) {
156 			fprintf(stderr, "rcmd: too many files\n");
157 			(void)close(s2);
158 			goto bad;
159 		}
160 		FD_ZERO(&reads);
161 		FD_SET(s, &reads);
162 		FD_SET(s2, &reads);
163 		errno = 0;
164 		if (select(nfds, &reads, 0, 0, 0) < 1 || !FD_ISSET(s2, &reads)){
165 			if (errno != 0)
166 				(void)fprintf(stderr,
167 				    "rcmd: select (setting up stderr): %s\n",
168 				    strerror(errno));
169 			else
170 				(void)fprintf(stderr,
171 				"select: protocol failure in circuit setup\n");
172 			(void)close(s2);
173 			goto bad;
174 		}
175 		s3 = accept(s2, (struct sockaddr *)&from, &len);
176 		(void)close(s2);
177 		if (s3 < 0) {
178 			(void)fprintf(stderr,
179 			    "rcmd: accept: %s\n", strerror(errno));
180 			lport = 0;
181 			goto bad;
182 		}
183 		*fd2p = s3;
184 		from.sin_port = ntohs((u_short)from.sin_port);
185 		if (from.sin_family != AF_INET ||
186 		    from.sin_port >= IPPORT_RESERVED ||
187 		    from.sin_port < IPPORT_RESERVED / 2) {
188 			(void)fprintf(stderr,
189 			    "socket: protocol failure in circuit setup.\n");
190 			goto bad2;
191 		}
192 	}
193 	(void)write(s, locuser, strlen(locuser)+1);
194 	(void)write(s, remuser, strlen(remuser)+1);
195 	(void)write(s, cmd, strlen(cmd)+1);
196 	if (read(s, &c, 1) != 1) {
197 		(void)fprintf(stderr,
198 		    "rcmd: %s: %s\n", *ahost, strerror(errno));
199 		goto bad2;
200 	}
201 	if (c != 0) {
202 		while (read(s, &c, 1) == 1) {
203 			(void)write(STDERR_FILENO, &c, 1);
204 			if (c == '\n')
205 				break;
206 		}
207 		goto bad2;
208 	}
209 	sigsetmask(oldmask);
210 	return (s);
211 bad2:
212 	if (lport)
213 		(void)close(*fd2p);
214 bad:
215 	(void)close(s);
216 	sigsetmask(oldmask);
217 	return (-1);
218 }
219 
220 int
221 rresvport(alport)
222 	int *alport;
223 {
224 	struct sockaddr_in sin;
225 	int s;
226 
227 	sin.sin_family = AF_INET;
228 	sin.sin_addr.s_addr = INADDR_ANY;
229 	s = socket(AF_INET, SOCK_STREAM, 0);
230 	if (s < 0)
231 		return (-1);
232 	for (;;) {
233 		sin.sin_port = htons((u_short)*alport);
234 		if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) >= 0)
235 			return (s);
236 		if (errno != EADDRINUSE) {
237 			(void)close(s);
238 			return (-1);
239 		}
240 		(*alport)--;
241 		if (*alport == IPPORT_RESERVED/2) {
242 			(void)close(s);
243 			errno = EAGAIN;		/* close */
244 			return (-1);
245 		}
246 	}
247 }
248 
249 int	__check_rhosts_file = 1;
250 char	*__rcmd_errstr;
251 
252 int
253 ruserok(rhost, superuser, ruser, luser)
254 	const char *rhost, *ruser, *luser;
255 	int superuser;
256 {
257 	struct hostent *hp;
258 	u_long addr;
259 	char **ap;
260 
261 	if ((hp = gethostbyname(rhost)) == NULL)
262 		return (-1);
263 	for (ap = hp->h_addr_list; *ap; ++ap) {
264 		bcopy(*ap, &addr, sizeof(addr));
265 		if (iruserok(addr, superuser, ruser, luser) == 0)
266 			return (0);
267 	}
268 	return (-1);
269 }
270 
271 /*
272  * New .rhosts strategy: We are passed an ip address. We spin through
273  * hosts.equiv and .rhosts looking for a match. When the .rhosts only
274  * has ip addresses, we don't have to trust a nameserver.  When it
275  * contains hostnames, we spin through the list of addresses the nameserver
276  * gives us and look for a match.
277  *
278  * Returns 0 if ok, -1 if not ok.
279  */
280 int
281 iruserok(raddr, superuser, ruser, luser)
282 	u_long raddr;
283 	int superuser;
284 	const char *ruser, *luser;
285 {
286 	register char *cp;
287 	struct stat sbuf;
288 	struct passwd *pwd;
289 	FILE *hostf;
290 	uid_t uid;
291 	int first;
292 	char pbuf[MAXPATHLEN];
293 
294 	first = 1;
295 	hostf = superuser ? NULL : fopen(_PATH_HEQUIV, "r");
296 again:
297 	if (hostf) {
298 		if (__ivaliduser(hostf, raddr, luser, ruser) == 0) {
299 			(void)fclose(hostf);
300 			return (0);
301 		}
302 		(void)fclose(hostf);
303 	}
304 	if (first == 1 && (__check_rhosts_file || superuser)) {
305 		first = 0;
306 		if ((pwd = getpwnam(luser)) == NULL)
307 			return (-1);
308 		(void)strcpy(pbuf, pwd->pw_dir);
309 		(void)strcat(pbuf, "/.rhosts");
310 
311 		/*
312 		 * Change effective uid while opening .rhosts.  If root and
313 		 * reading an NFS mounted file system, can't read files that
314 		 * are protected read/write owner only.
315 		 */
316 		uid = geteuid();
317 		(void)seteuid(pwd->pw_uid);
318 		hostf = fopen(pbuf, "r");
319 		(void)seteuid(uid);
320 
321 		if (hostf == NULL)
322 			return (-1);
323 		/*
324 		 * If not a regular file, or is owned by someone other than
325 		 * user or root or if writeable by anyone but the owner, quit.
326 		 */
327 		cp = NULL;
328 		if (lstat(pbuf, &sbuf) < 0)
329 			cp = ".rhosts lstat failed";
330 		else if (!S_ISREG(sbuf.st_mode))
331 			cp = ".rhosts not regular file";
332 		else if (fstat(fileno(hostf), &sbuf) < 0)
333 			cp = ".rhosts fstat failed";
334 		else if (sbuf.st_uid && sbuf.st_uid != pwd->pw_uid)
335 			cp = "bad .rhosts owner";
336 		else if (sbuf.st_mode & (S_IWGRP|S_IWOTH))
337 			cp = ".rhosts writeable by other than owner";
338 		/* If there were any problems, quit. */
339 		if (cp) {
340 			__rcmd_errstr = cp;
341 			(void)fclose(hostf);
342 			return (-1);
343 		}
344 		goto again;
345 	}
346 	return (-1);
347 }
348 
349 /*
350  * XXX
351  * Don't make static, used by lpd(8).
352  *
353  * Returns 0 if ok, -1 if not ok.
354  */
355 int
356 __ivaliduser(hostf, raddr, luser, ruser)
357 	FILE *hostf;
358 	u_long raddr;
359 	const char *luser, *ruser;
360 {
361 	register char *user, *p;
362 	int ch;
363 	char buf[MAXHOSTNAMELEN + 128];		/* host + login */
364 	char hname[MAXHOSTNAMELEN];
365 	struct hostent *hp;
366 	/* Presumed guilty until proven innocent. */
367 	int userok = 0, hostok = 0;
368 #ifdef YP
369 	char *ypdomain;
370 
371 	if (yp_get_default_domain(&ypdomain))
372 		ypdomain = NULL;
373 #else
374 #define	ypdomain NULL
375 #endif
376 	/* We need to get the damn hostname back for netgroup matching. */
377 	if ((hp = gethostbyaddr((char *)&raddr, sizeof(u_long),
378 							AF_INET)) == NULL)
379 		return (-1);
380 	strcpy(hname, hp->h_name);
381 
382 	while (fgets(buf, sizeof(buf), hostf)) {
383 		p = buf;
384 		/* Skip lines that are too long. */
385 		if (strchr(p, '\n') == NULL) {
386 			while ((ch = getc(hostf)) != '\n' && ch != EOF);
387 			continue;
388 		}
389 		if (*p == '\n' || *p == '#') {
390 			/* comment... */
391 			continue;
392 		}
393 		while (*p != '\n' && *p != ' ' && *p != '\t' && *p != '\0') {
394 			*p = isupper(*p) ? tolower(*p) : *p;
395 			p++;
396 		}
397 		if (*p == ' ' || *p == '\t') {
398 			*p++ = '\0';
399 			while (*p == ' ' || *p == '\t')
400 				p++;
401 			user = p;
402 			while (*p != '\n' && *p != ' ' &&
403 			    *p != '\t' && *p != '\0')
404 				p++;
405 		} else
406 			user = p;
407 		*p = '\0';
408 		/*
409 		 * Do +/- and +@/-@ checking. This looks really nasty,
410 		 * but it matches SunOS's behavior so far as I can tell.
411 		 */
412 		switch(buf[0]) {
413 		case '+':
414 			if (!buf[1]) {     /* '+' matches all hosts */
415 				hostok = 1;
416 				break;
417 			}
418 			if (buf[1] == '@')  /* match a host by netgroup */
419 				hostok = innetgr((char *)&buf[2],
420 					(char *)&hname, NULL, ypdomain);
421 			else		/* match a host by addr */
422 				hostok = __icheckhost(raddr,(char *)&buf[1]);
423 			break;
424 		case '-':     /* reject '-' hosts and all their users */
425 			if (buf[1] == '@') {
426 				if (innetgr((char *)&buf[2],
427 					      (char *)&hname, NULL, ypdomain))
428 					return(-1);
429 			} else {
430 				if (__icheckhost(raddr,(char *)&buf[1]))
431 					return(-1);
432 			}
433 			break;
434 		default:  /* if no '+' or '-', do a simple match */
435 			hostok = __icheckhost(raddr, buf);
436 			break;
437 		}
438 		switch(*user) {
439 		case '+':
440 			if (!*(user+1)) {      /* '+' matches all users */
441 				userok = 1;
442 				break;
443 			}
444 			if (*(user+1) == '@')  /* match a user by netgroup */
445 				userok = innetgr(user+2, NULL, ruser, ypdomain);
446 			else	   /* match a user by direct specification */
447 				userok = !(strcmp(ruser, user+1));
448 			break;
449 		case '-': 		/* if we matched a hostname, */
450 			if (hostok) {   /* check for user field rejections */
451 				if (!*(user+1))
452 					return(-1);
453 				if (*(user+1) == '@') {
454 					if (innetgr(user+2, NULL,
455 							ruser, ypdomain))
456 						return(-1);
457 				} else {
458 					if (!strcmp(ruser, user+1))
459 						return(-1);
460 				}
461 			}
462 			break;
463 		default:	/* no rejections: try to match the user */
464 			if (hostok)
465 				userok = !(strcmp(ruser,*user ? user : luser));
466 			break;
467 		}
468 		if (hostok && userok)
469 			return(0);
470 	}
471 	return (-1);
472 }
473 
474 /*
475  * Returns "true" if match, 0 if no match.
476  */
477 static int
478 __icheckhost(raddr, lhost)
479 	u_long raddr;
480 	register char *lhost;
481 {
482 	register struct hostent *hp;
483 	register u_long laddr;
484 	register char **pp;
485 
486 	/* Try for raw ip address first. */
487 	if (isdigit(*lhost) && (long)(laddr = inet_addr(lhost)) != -1)
488 		return (raddr == laddr);
489 
490 	/* Better be a hostname. */
491 	if ((hp = gethostbyname(lhost)) == NULL)
492 		return (0);
493 
494 	/* Spin through ip addresses. */
495 	for (pp = hp->h_addr_list; *pp; ++pp)
496 		if (!bcmp(&raddr, *pp, sizeof(u_long)))
497 			return (1);
498 
499 	/* No match. */
500 	return (0);
501 }
502