xref: /netbsd-src/libexec/rshd/rshd.c (revision ae9172d6cd9432a6a1a56760d86b32c57a66c39c)
1 /*-
2  * Copyright (c) 1988, 1989, 1992, 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 #ifndef lint
35 static char copyright[] =
36 "@(#) Copyright (c) 1988, 1989, 1992, 1993, 1994\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 
40 #ifndef lint
41 /* from: static char sccsid[] = "@(#)rshd.c	8.2 (Berkeley) 4/6/94"; */
42 static char *rcsid = "$Id: rshd.c,v 1.8 1994/06/05 15:35:55 cgd Exp $";
43 #endif /* not lint */
44 
45 /*
46  * remote shell server:
47  *	[port]\0
48  *	remuser\0
49  *	locuser\0
50  *	command\0
51  *	data
52  */
53 #include <sys/param.h>
54 #include <sys/ioctl.h>
55 #include <sys/time.h>
56 #include <sys/socket.h>
57 
58 #include <netinet/in.h>
59 #include <arpa/inet.h>
60 #include <netdb.h>
61 
62 #include <errno.h>
63 #include <fcntl.h>
64 #include <paths.h>
65 #include <pwd.h>
66 #include <signal.h>
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <syslog.h>
71 #include <unistd.h>
72 
73 int	keepalive = 1;
74 int	check_all;
75 int	log_success;		/* If TRUE, log all successful accesses */
76 int	sent_null;
77 
78 void	 doit __P((struct sockaddr_in *));
79 void	 error __P((const char *, ...));
80 void	 getstr __P((char *, int, char *));
81 int	 local_domain __P((char *));
82 char	*topdomain __P((char *));
83 void	 usage __P((void));
84 
85 #define	OPTIONS	"alnL"
86 
87 int
88 main(argc, argv)
89 	int argc;
90 	char *argv[];
91 {
92 	extern int __check_rhosts_file;
93 	struct linger linger;
94 	int ch, on = 1, fromlen;
95 	struct sockaddr_in from;
96 
97 	openlog("rshd", LOG_PID | LOG_ODELAY, LOG_DAEMON);
98 
99 	opterr = 0;
100 	while ((ch = getopt(argc, argv, OPTIONS)) != EOF)
101 		switch (ch) {
102 		case 'a':
103 			check_all = 1;
104 			break;
105 		case 'l':
106 			__check_rhosts_file = 0;
107 			break;
108 		case 'n':
109 			keepalive = 0;
110 			break;
111 		case 'L':
112 			log_success = 1;
113 			break;
114 		case '?':
115 		default:
116 			usage();
117 			break;
118 		}
119 
120 	argc -= optind;
121 	argv += optind;
122 
123 
124 	fromlen = sizeof (from);
125 	if (getpeername(0, (struct sockaddr *)&from, &fromlen) < 0) {
126 		syslog(LOG_ERR, "getpeername: %m");
127 		_exit(1);
128 	}
129 	if (keepalive &&
130 	    setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, (char *)&on,
131 	    sizeof(on)) < 0)
132 		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
133 	linger.l_onoff = 1;
134 	linger.l_linger = 60;			/* XXX */
135 	if (setsockopt(0, SOL_SOCKET, SO_LINGER, (char *)&linger,
136 	    sizeof (linger)) < 0)
137 		syslog(LOG_WARNING, "setsockopt (SO_LINGER): %m");
138 	doit(&from);
139 	/* NOTREACHED */
140 }
141 
142 char	username[20] = "USER=";
143 char	homedir[64] = "HOME=";
144 char	shell[64] = "SHELL=";
145 char	path[100] = "PATH=";
146 char	*envinit[] =
147 	    {homedir, shell, path, username, 0};
148 char	**environ;
149 
150 void
151 doit(fromp)
152 	struct sockaddr_in *fromp;
153 {
154 	extern char *__rcmd_errstr;	/* syslog hook from libc/net/rcmd.c. */
155 	struct hostent *hp;
156 	struct passwd *pwd;
157 	u_short port;
158 	fd_set ready, readfrom;
159 	int cc, nfd, pv[2], pid, s;
160 	int one = 1;
161 	char *hostname, *errorstr, *errorhost;
162 	char *cp, sig, buf[BUFSIZ];
163 	char cmdbuf[NCARGS+1], locuser[16], remuser[16];
164 	char remotehost[2 * MAXHOSTNAMELEN + 1];
165 
166 
167 	(void) signal(SIGINT, SIG_DFL);
168 	(void) signal(SIGQUIT, SIG_DFL);
169 	(void) signal(SIGTERM, SIG_DFL);
170 #ifdef DEBUG
171 	{ int t = open(_PATH_TTY, 2);
172 	  if (t >= 0) {
173 		ioctl(t, TIOCNOTTY, (char *)0);
174 		(void) close(t);
175 	  }
176 	}
177 #endif
178 	fromp->sin_port = ntohs((u_short)fromp->sin_port);
179 	if (fromp->sin_family != AF_INET) {
180 		syslog(LOG_ERR, "malformed \"from\" address (af %d)\n",
181 		    fromp->sin_family);
182 		exit(1);
183 	}
184 #ifdef IP_OPTIONS
185       {
186 	u_char optbuf[BUFSIZ/3], *cp;
187 	char lbuf[BUFSIZ], *lp;
188 	int optsize = sizeof(optbuf), ipproto;
189 	struct protoent *ip;
190 
191 	if ((ip = getprotobyname("ip")) != NULL)
192 		ipproto = ip->p_proto;
193 	else
194 		ipproto = IPPROTO_IP;
195 	if (!getsockopt(0, ipproto, IP_OPTIONS, (char *)optbuf, &optsize) &&
196 	    optsize != 0) {
197 		lp = lbuf;
198 		for (cp = optbuf; optsize > 0; cp++, optsize--, lp += 3)
199 			sprintf(lp, " %2.2x", *cp);
200 		syslog(LOG_NOTICE,
201 		    "Connection received from %s using IP options (ignored):%s",
202 		    inet_ntoa(fromp->sin_addr), lbuf);
203 		if (setsockopt(0, ipproto, IP_OPTIONS,
204 		    (char *)NULL, optsize) != 0) {
205 			syslog(LOG_ERR, "setsockopt IP_OPTIONS NULL: %m");
206 			exit(1);
207 		}
208 	}
209       }
210 #endif
211 
212 		if (fromp->sin_port >= IPPORT_RESERVED ||
213 		    fromp->sin_port < IPPORT_RESERVED/2) {
214 			syslog(LOG_NOTICE|LOG_AUTH,
215 			    "Connection from %s on illegal port %u",
216 			    inet_ntoa(fromp->sin_addr),
217 			    fromp->sin_port);
218 			exit(1);
219 		}
220 
221 	(void) alarm(60);
222 	port = 0;
223 	for (;;) {
224 		char c;
225 		if ((cc = read(STDIN_FILENO, &c, 1)) != 1) {
226 			if (cc < 0)
227 				syslog(LOG_NOTICE, "read: %m");
228 			shutdown(0, 1+1);
229 			exit(1);
230 		}
231 		if (c== 0)
232 			break;
233 		port = port * 10 + c - '0';
234 	}
235 
236 	(void) alarm(0);
237 	if (port != 0) {
238 		int lport = IPPORT_RESERVED - 1;
239 		s = rresvport(&lport);
240 		if (s < 0) {
241 			syslog(LOG_ERR, "can't get stderr port: %m");
242 			exit(1);
243 		}
244 			if (port >= IPPORT_RESERVED) {
245 				syslog(LOG_ERR, "2nd port not reserved\n");
246 				exit(1);
247 			}
248 		fromp->sin_port = htons(port);
249 		if (connect(s, (struct sockaddr *)fromp, sizeof (*fromp)) < 0) {
250 			syslog(LOG_INFO, "connect second port %d: %m", port);
251 			exit(1);
252 		}
253 	}
254 
255 
256 #ifdef notdef
257 	/* from inetd, socket is already on 0, 1, 2 */
258 	dup2(f, 0);
259 	dup2(f, 1);
260 	dup2(f, 2);
261 #endif
262 	errorstr = NULL;
263 	hp = gethostbyaddr((char *)&fromp->sin_addr, sizeof (struct in_addr),
264 		fromp->sin_family);
265 	if (hp) {
266 		/*
267 		 * If name returned by gethostbyaddr is in our domain,
268 		 * attempt to verify that we haven't been fooled by someone
269 		 * in a remote net; look up the name and check that this
270 		 * address corresponds to the name.
271 		 */
272 		hostname = hp->h_name;
273 		if (check_all || local_domain(hp->h_name)) {
274 			strncpy(remotehost, hp->h_name, sizeof(remotehost) - 1);
275 			remotehost[sizeof(remotehost) - 1] = 0;
276 			errorhost = remotehost;
277 			hp = gethostbyname(remotehost);
278 			if (hp == NULL) {
279 				syslog(LOG_INFO,
280 				    "Couldn't look up address for %s",
281 				    remotehost);
282 				errorstr =
283 				"Couldn't look up address for your host (%s)\n";
284 				hostname = inet_ntoa(fromp->sin_addr);
285 			} else for (; ; hp->h_addr_list++) {
286 				if (hp->h_addr_list[0] == NULL) {
287 					syslog(LOG_NOTICE,
288 					  "Host addr %s not listed for host %s",
289 					    inet_ntoa(fromp->sin_addr),
290 					    hp->h_name);
291 					errorstr =
292 					    "Host address mismatch for %s\n";
293 					hostname = inet_ntoa(fromp->sin_addr);
294 					break;
295 				}
296 				if (!bcmp(hp->h_addr_list[0],
297 				    (caddr_t)&fromp->sin_addr,
298 				    sizeof(fromp->sin_addr))) {
299 					hostname = hp->h_name;
300 					break;
301 				}
302 			}
303 		}
304 	} else
305 		errorhost = hostname = inet_ntoa(fromp->sin_addr);
306 
307 		getstr(remuser, sizeof(remuser), "remuser");
308 
309 	getstr(locuser, sizeof(locuser), "locuser");
310 	getstr(cmdbuf, sizeof(cmdbuf), "command");
311 	setpwent();
312 	pwd = getpwnam(locuser);
313 	if (pwd == NULL) {
314 		syslog(LOG_INFO|LOG_AUTH,
315 		    "%s@%s as %s: unknown login. cmd='%.80s'",
316 		    remuser, hostname, locuser, cmdbuf);
317 		if (errorstr == NULL)
318 			errorstr = "Login incorrect.\n";
319 		goto fail;
320 	}
321 	if (chdir(pwd->pw_dir) < 0) {
322 		(void) chdir("/");
323 #ifdef notdef
324 		syslog(LOG_INFO|LOG_AUTH,
325 		    "%s@%s as %s: no home directory. cmd='%.80s'",
326 		    remuser, hostname, locuser, cmdbuf);
327 		error("No remote directory.\n");
328 		exit(1);
329 #endif
330 	}
331 
332 
333 		if (errorstr ||
334 		    pwd->pw_passwd != 0 && *pwd->pw_passwd != '\0' &&
335 		    iruserok(fromp->sin_addr.s_addr, pwd->pw_uid == 0,
336 		    remuser, locuser) < 0) {
337 			if (__rcmd_errstr)
338 				syslog(LOG_INFO|LOG_AUTH,
339 			    "%s@%s as %s: permission denied (%s). cmd='%.80s'",
340 				    remuser, hostname, locuser, __rcmd_errstr,
341 				    cmdbuf);
342 			else
343 				syslog(LOG_INFO|LOG_AUTH,
344 			    "%s@%s as %s: permission denied. cmd='%.80s'",
345 				    remuser, hostname, locuser, cmdbuf);
346 fail:
347 			if (errorstr == NULL)
348 				errorstr = "Permission denied.\n";
349 			error(errorstr, errorhost);
350 			exit(1);
351 		}
352 
353 	if (pwd->pw_uid && !access(_PATH_NOLOGIN, F_OK)) {
354 		error("Logins currently disabled.\n");
355 		exit(1);
356 	}
357 
358 	(void) write(STDERR_FILENO, "\0", 1);
359 	sent_null = 1;
360 
361 	if (port) {
362 		if (pipe(pv) < 0) {
363 			error("Can't make pipe.\n");
364 			exit(1);
365 		}
366 		pid = fork();
367 		if (pid == -1)  {
368 			error("Can't fork; try again.\n");
369 			exit(1);
370 		}
371 		if (pid) {
372 			{
373 				(void) close(0);
374 				(void) close(1);
375 			}
376 			(void) close(2);
377 			(void) close(pv[1]);
378 
379 			FD_ZERO(&readfrom);
380 			FD_SET(s, &readfrom);
381 			FD_SET(pv[0], &readfrom);
382 			if (pv[0] > s)
383 				nfd = pv[0];
384 			else
385 				nfd = s;
386 				ioctl(pv[0], FIONBIO, (char *)&one);
387 
388 			/* should set s nbio! */
389 			nfd++;
390 			do {
391 				ready = readfrom;
392 					if (select(nfd, &ready, (fd_set *)0,
393 					  (fd_set *)0, (struct timeval *)0) < 0)
394 						break;
395 				if (FD_ISSET(s, &ready)) {
396 					int	ret;
397 						ret = read(s, &sig, 1);
398 					if (ret <= 0)
399 						FD_CLR(s, &readfrom);
400 					else
401 						killpg(pid, sig);
402 				}
403 				if (FD_ISSET(pv[0], &ready)) {
404 					errno = 0;
405 					cc = read(pv[0], buf, sizeof(buf));
406 					if (cc <= 0) {
407 						shutdown(s, 1+1);
408 						FD_CLR(pv[0], &readfrom);
409 					} else {
410 							(void)
411 							  write(s, buf, cc);
412 					}
413 				}
414 
415 			} while (FD_ISSET(s, &readfrom) ||
416 			    FD_ISSET(pv[0], &readfrom));
417 			exit(0);
418 		}
419 		setpgrp(0, getpid());
420 		(void) close(s);
421 		(void) close(pv[0]);
422 		dup2(pv[1], 2);
423 		close(pv[1]);
424 	}
425 	if (*pwd->pw_shell == '\0')
426 		pwd->pw_shell = _PATH_BSHELL;
427 #if	BSD > 43
428 	if (setlogin(pwd->pw_name) < 0)
429 		syslog(LOG_ERR, "setlogin() failed: %m");
430 #endif
431 	(void) setgid((gid_t)pwd->pw_gid);
432 	initgroups(pwd->pw_name, pwd->pw_gid);
433 	(void) setuid((uid_t)pwd->pw_uid);
434 	environ = envinit;
435 	strncat(homedir, pwd->pw_dir, sizeof(homedir)-6);
436 	strcat(path, _PATH_DEFPATH);
437 	strncat(shell, pwd->pw_shell, sizeof(shell)-7);
438 	strncat(username, pwd->pw_name, sizeof(username)-6);
439 	cp = strrchr(pwd->pw_shell, '/');
440 	if (cp)
441 		cp++;
442 	else
443 		cp = pwd->pw_shell;
444 	endpwent();
445 	if (log_success || pwd->pw_uid == 0) {
446 		    syslog(LOG_INFO|LOG_AUTH, "%s@%s as %s: cmd='%.80s'",
447 			remuser, hostname, locuser, cmdbuf);
448 	}
449 	execl(pwd->pw_shell, cp, "-c", cmdbuf, 0);
450 	perror(pwd->pw_shell);
451 	exit(1);
452 }
453 
454 /*
455  * Report error to client.  Note: can't be used until second socket has
456  * connected to client, or older clients will hang waiting for that
457  * connection first.
458  */
459 #if __STDC__
460 #include <stdarg.h>
461 #else
462 #include <varargs.h>
463 #endif
464 
465 void
466 #if __STDC__
467 error(const char *fmt, ...)
468 #else
469 error(fmt, va_alist)
470 	char *fmt;
471         va_dcl
472 #endif
473 {
474 	va_list ap;
475 	int len;
476 	char *bp, buf[BUFSIZ];
477 #if __STDC__
478 	va_start(ap, fmt);
479 #else
480 	va_start(ap);
481 #endif
482 	bp = buf;
483 	if (sent_null == 0) {
484 		*bp++ = 1;
485 		len = 1;
486 	} else
487 		len = 0;
488 	(void)vsnprintf(bp, sizeof(buf) - 1, fmt, ap);
489 	(void)write(STDERR_FILENO, buf, len + strlen(bp));
490 }
491 
492 void
493 getstr(buf, cnt, err)
494 	char *buf, *err;
495 	int cnt;
496 {
497 	char c;
498 
499 	do {
500 		if (read(STDIN_FILENO, &c, 1) != 1)
501 			exit(1);
502 		*buf++ = c;
503 		if (--cnt == 0) {
504 			error("%s too long\n", err);
505 			exit(1);
506 		}
507 	} while (c != 0);
508 }
509 
510 /*
511  * Check whether host h is in our local domain,
512  * defined as sharing the last two components of the domain part,
513  * or the entire domain part if the local domain has only one component.
514  * If either name is unqualified (contains no '.'),
515  * assume that the host is local, as it will be
516  * interpreted as such.
517  */
518 int
519 local_domain(h)
520 	char *h;
521 {
522 	char localhost[MAXHOSTNAMELEN];
523 	char *p1, *p2;
524 
525 	localhost[0] = 0;
526 	(void) gethostname(localhost, sizeof(localhost));
527 	p1 = topdomain(localhost);
528 	p2 = topdomain(h);
529 	if (p1 == NULL || p2 == NULL || !strcasecmp(p1, p2))
530 		return (1);
531 	return (0);
532 }
533 
534 char *
535 topdomain(h)
536 	char *h;
537 {
538 	char *p, *maybe = NULL;
539 	int dots = 0;
540 
541 	for (p = h + strlen(h); p >= h; p--) {
542 		if (*p == '.') {
543 			if (++dots == 2)
544 				return (p);
545 			maybe = p;
546 		}
547 	}
548 	return (maybe);
549 }
550 
551 void
552 usage()
553 {
554 
555 	syslog(LOG_ERR, "usage: rshd [-%s]", OPTIONS);
556 	exit(2);
557 }
558