rshd.c revision 67001
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
35static const 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#if 0
42static const char sccsid[] = "@(#)rshd.c	8.2 (Berkeley) 4/6/94";
43#endif
44static const char rcsid[] =
45  "$FreeBSD: head/libexec/rshd/rshd.c 67001 2000-10-12 07:18:20Z ru $";
46#endif /* not lint */
47
48/*
49 * remote shell server:
50 *	[port]\0
51 *	remuser\0
52 *	locuser\0
53 *	command\0
54 *	data
55 */
56#include <sys/param.h>
57#include <sys/ioctl.h>
58#include <sys/time.h>
59#include <sys/socket.h>
60
61#include <netinet/in_systm.h>
62#include <netinet/in.h>
63#include <netinet/ip.h>
64#include <netinet/tcp.h>
65#include <arpa/inet.h>
66#include <netdb.h>
67
68#include <errno.h>
69#include <fcntl.h>
70#include <libutil.h>
71#include <paths.h>
72#include <pwd.h>
73#include <signal.h>
74#include <stdio.h>
75#include <stdlib.h>
76#include <string.h>
77#include <syslog.h>
78#include <unistd.h>
79#ifdef	LOGIN_CAP
80#include <login_cap.h>
81#endif
82
83/* wrapper for KAME-special getnameinfo() */
84#ifndef NI_WITHSCOPEID
85#define	NI_WITHSCOPEID	0
86#endif
87
88int	keepalive = 1;
89int	log_success;		/* If TRUE, log all successful accesses */
90int	sent_null;
91int	no_delay;
92#ifdef CRYPT
93int	doencrypt = 0;
94#endif
95
96union sockunion {
97	struct sockinet {
98		u_char si_len;
99		u_char si_family;
100		u_short si_port;
101	} su_si;
102	struct sockaddr_in  su_sin;
103	struct sockaddr_in6 su_sin6;
104};
105#define su_len		su_si.si_len
106#define su_family	su_si.si_family
107#define su_port		su_si.si_port
108
109void	 doit __P((union sockunion *));
110void	 error __P((const char *, ...));
111void	 getstr __P((char *, int, char *));
112int	 local_domain __P((char *));
113char	*topdomain __P((char *));
114void	 usage __P((void));
115
116
117#define	OPTIONS	"alnDL"
118
119int
120main(argc, argv)
121	int argc;
122	char *argv[];
123{
124	extern int __check_rhosts_file;
125	struct linger linger;
126	int ch, on = 1, fromlen;
127	struct sockaddr_storage from;
128
129	openlog("rshd", LOG_PID | LOG_ODELAY, LOG_DAEMON);
130
131	opterr = 0;
132	while ((ch = getopt(argc, argv, OPTIONS)) != -1)
133		switch (ch) {
134		case 'a':
135			/* ignored for compatability */
136			break;
137		case 'l':
138			__check_rhosts_file = 0;
139			break;
140		case 'n':
141			keepalive = 0;
142			break;
143#ifdef CRYPT
144		case 'x':
145			doencrypt = 1;
146			break;
147#endif
148		case 'D':
149			no_delay = 1;
150			break;
151		case 'L':
152			log_success = 1;
153			break;
154		case '?':
155		default:
156			usage();
157			break;
158		}
159
160	argc -= optind;
161	argv += optind;
162
163#ifdef CRYPT
164	if (doencrypt) {
165		syslog(LOG_ERR, "-k is required for -x");
166		exit(2);
167	}
168#endif
169
170	fromlen = sizeof (from);
171	if (getpeername(0, (struct sockaddr *)&from, &fromlen) < 0) {
172		syslog(LOG_ERR, "getpeername: %m");
173		exit(1);
174	}
175	if (keepalive &&
176	    setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, (char *)&on,
177	    sizeof(on)) < 0)
178		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
179	linger.l_onoff = 1;
180	linger.l_linger = 60;			/* XXX */
181	if (setsockopt(0, SOL_SOCKET, SO_LINGER, (char *)&linger,
182	    sizeof (linger)) < 0)
183		syslog(LOG_WARNING, "setsockopt (SO_LINGER): %m");
184	if (no_delay &&
185	    setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
186		syslog(LOG_WARNING, "setsockopt (TCP_NODELAY): %m");
187	doit((union sockunion *)&from);
188	/* NOTREACHED */
189	return(0);
190}
191
192char	username[20] = "USER=";
193char	homedir[64] = "HOME=";
194char	shell[64] = "SHELL=";
195char	path[100] = "PATH=";
196char	*envinit[] =
197	    {homedir, shell, path, username, 0};
198char	**environ;
199
200void
201doit(fromp)
202	union sockunion *fromp;
203{
204	extern char *__rcmd_errstr;	/* syslog hook from libc/net/rcmd.c. */
205	struct passwd *pwd;
206	u_short port;
207	fd_set ready, readfrom;
208	int cc, nfd, pv[2], pid, s;
209	int one = 1;
210	char *errorstr;
211	char *cp, sig, buf[BUFSIZ];
212	char cmdbuf[NCARGS+1], locuser[16], remuser[16];
213	char fromhost[2 * MAXHOSTNAMELEN + 1];
214	char numericname[INET6_ADDRSTRLEN];
215	int af = fromp->su_family, err;
216#ifdef	CRYPT
217	int rc;
218	int pv1[2], pv2[2];
219#endif
220#ifdef	LOGIN_CAP
221	login_cap_t *lc;
222#endif
223
224	(void) signal(SIGINT, SIG_DFL);
225	(void) signal(SIGQUIT, SIG_DFL);
226	(void) signal(SIGTERM, SIG_DFL);
227	fromp->su_port = ntohs((u_short)fromp->su_port);
228	if (af != AF_INET
229#ifdef INET6
230	    && af != AF_INET6
231#endif
232	    ) {
233		syslog(LOG_ERR, "malformed \"from\" address (af %d)\n", af);
234		exit(1);
235	}
236	err = getnameinfo((struct sockaddr *)fromp, fromp->su_len, numericname,
237			  sizeof(numericname), NULL, 0,
238			  NI_NUMERICHOST|NI_WITHSCOPEID);
239	/* XXX: do 'err' check */
240#ifdef IP_OPTIONS
241      if (af == AF_INET) {
242	u_char optbuf[BUFSIZ/3];
243	int optsize = sizeof(optbuf), ipproto, i;
244	struct protoent *ip;
245
246	if ((ip = getprotobyname("ip")) != NULL)
247		ipproto = ip->p_proto;
248	else
249		ipproto = IPPROTO_IP;
250	if (!getsockopt(0, ipproto, IP_OPTIONS, (char *)optbuf, &optsize) &&
251	    optsize != 0) {
252		for (i = 0; i < optsize; ) {
253			u_char c = optbuf[i];
254			if (c == IPOPT_LSRR || c == IPOPT_SSRR) {
255				syslog(LOG_NOTICE,
256					"connection refused from %s with IP option %s",
257					numericname,
258					c == IPOPT_LSRR ? "LSRR" : "SSRR");
259				exit(1);
260			}
261			if (c == IPOPT_EOL)
262				break;
263			i += (c == IPOPT_NOP) ? 1 : optbuf[i+1];
264		}
265	}
266      }
267#endif
268
269	if (fromp->su_port >= IPPORT_RESERVED ||
270	    fromp->su_port < IPPORT_RESERVED/2) {
271		syslog(LOG_NOTICE|LOG_AUTH,
272		    "connection from %s on illegal port %u",
273		    numericname,
274		    fromp->su_port);
275		exit(1);
276	}
277
278	(void) alarm(60);
279	port = 0;
280	s = 0;		/* not set or used if port == 0 */
281	for (;;) {
282		char c;
283		if ((cc = read(STDIN_FILENO, &c, 1)) != 1) {
284			if (cc < 0)
285				syslog(LOG_NOTICE, "read: %m");
286			shutdown(0, 1+1);
287			exit(1);
288		}
289		if (c == 0)
290			break;
291		port = port * 10 + c - '0';
292	}
293
294	(void) alarm(0);
295	if (port != 0) {
296		int lport = IPPORT_RESERVED - 1;
297		s = rresvport_af(&lport, af);
298		if (s < 0) {
299			syslog(LOG_ERR, "can't get stderr port: %m");
300			exit(1);
301		}
302		if (port >= IPPORT_RESERVED ||
303		    port < IPPORT_RESERVED/2) {
304			syslog(LOG_NOTICE|LOG_AUTH,
305			    "2nd socket from %s on unreserved port %u",
306			    numericname,
307			    port);
308			exit(1);
309		}
310		fromp->su_port = htons(port);
311		if (connect(s, (struct sockaddr *)fromp, fromp->su_len) < 0) {
312			syslog(LOG_INFO, "connect second port %d: %m", port);
313			exit(1);
314		}
315	}
316
317	errorstr = NULL;
318	realhostname_sa(fromhost, sizeof(fromhost) - 1,
319			(struct sockaddr *)fromp,
320			fromp->su_len);
321	fromhost[sizeof(fromhost) - 1] = '\0';
322
323#ifdef CRYPT
324	if (doencrypt && af == AF_INET) {
325		struct sockaddr_in local_addr;
326		rc = sizeof(local_addr);
327		if (getsockname(0, (struct sockaddr *)&local_addr,
328		    &rc) < 0) {
329			syslog(LOG_ERR, "getsockname: %m");
330			error("rlogind: getsockname: %m");
331			exit(1);
332		}
333		authopts = KOPT_DO_MUTUAL;
334		rc = krb_recvauth(authopts, 0, ticket,
335			"rcmd", instance, &fromaddr,
336			&local_addr, kdata, "", schedule,
337			version);
338		des_set_key(&kdata->session, schedule);
339	}
340#endif
341	getstr(remuser, sizeof(remuser), "remuser");
342
343	getstr(locuser, sizeof(locuser), "locuser");
344	getstr(cmdbuf, sizeof(cmdbuf), "command");
345	setpwent();
346	pwd = getpwnam(locuser);
347	if (pwd == NULL) {
348		syslog(LOG_INFO|LOG_AUTH,
349		    "%s@%s as %s: unknown login. cmd='%.80s'",
350		    remuser, fromhost, locuser, cmdbuf);
351		if (errorstr == NULL)
352			errorstr = "Login incorrect.\n";
353		goto fail;
354	}
355#ifdef	LOGIN_CAP
356	lc = login_getpwclass(pwd);
357#endif
358	if (chdir(pwd->pw_dir) < 0) {
359#ifdef	LOGIN_CAP
360		if (chdir("/") < 0 ||
361		    login_getcapbool(lc, "requirehome", !!pwd->pw_uid)) {
362			syslog(LOG_INFO|LOG_AUTH,
363			"%s@%s as %s: no home directory. cmd='%.80s'",
364			remuser, fromhost, locuser, cmdbuf);
365			error("No remote home directory.\n");
366			exit(0);
367		}
368#else
369		(void) chdir("/");
370#ifdef notdef
371		syslog(LOG_INFO|LOG_AUTH,
372		    "%s@%s as %s: no home directory. cmd='%.80s'",
373		    remuser, fromhost, locuser, cmdbuf);
374		error("No remote directory.\n");
375		exit(1);
376#endif
377#endif
378		pwd->pw_dir = "/";
379	}
380
381
382		if (errorstr ||
383		    (pwd->pw_expire && time(NULL) >= pwd->pw_expire) ||
384		    iruserok_sa(fromp, fromp->su_len, pwd->pw_uid == 0,
385				 remuser, locuser) < 0) {
386			if (__rcmd_errstr)
387				syslog(LOG_INFO|LOG_AUTH,
388			    "%s@%s as %s: permission denied (%s). cmd='%.80s'",
389				    remuser, fromhost, locuser, __rcmd_errstr,
390				    cmdbuf);
391			else
392				syslog(LOG_INFO|LOG_AUTH,
393			    "%s@%s as %s: permission denied. cmd='%.80s'",
394				    remuser, fromhost, locuser, cmdbuf);
395fail:
396			if (errorstr == NULL)
397				errorstr = "Login incorrect.\n";
398			error(errorstr, fromhost);
399			exit(1);
400		}
401
402	if (pwd->pw_uid && !access(_PATH_NOLOGIN, F_OK)) {
403		error("Logins currently disabled.\n");
404		exit(1);
405	}
406#ifdef	LOGIN_CAP
407	if (lc != NULL && fromp->su_family == AF_INET) {	/*XXX*/
408		char	remote_ip[MAXHOSTNAMELEN];
409
410		strncpy(remote_ip, numericname,
411			sizeof(remote_ip) - 1);
412		remote_ip[sizeof(remote_ip) - 1] = 0;
413		if (!auth_hostok(lc, fromhost, remote_ip)) {
414			syslog(LOG_INFO|LOG_AUTH,
415			    "%s@%s as %s: permission denied (%s). cmd='%.80s'",
416			    remuser, fromhost, locuser, __rcmd_errstr,
417			    cmdbuf);
418			error("Login incorrect.\n");
419			exit(1);
420		}
421		if (!auth_timeok(lc, time(NULL))) {
422			error("Logins not available right now\n");
423			exit(1);
424		}
425	}
426#endif	/* !LOGIN_CAP */
427#if	BSD > 43
428	/* before fork, while we're session leader */
429	if (setlogin(pwd->pw_name) < 0)
430		syslog(LOG_ERR, "setlogin() failed: %m");
431#endif
432
433	(void) write(STDERR_FILENO, "\0", 1);
434	sent_null = 1;
435
436	if (port) {
437		if (pipe(pv) < 0) {
438			error("Can't make pipe.\n");
439			exit(1);
440		}
441#ifdef CRYPT
442		if (doencrypt) {
443			if (pipe(pv1) < 0) {
444				error("Can't make 2nd pipe.\n");
445				exit(1);
446			}
447			if (pipe(pv2) < 0) {
448				error("Can't make 3rd pipe.\n");
449				exit(1);
450			}
451		}
452#endif
453		pid = fork();
454		if (pid == -1)  {
455			error("Can't fork; try again.\n");
456			exit(1);
457		}
458		if (pid) {
459#ifdef CRYPT
460			if (doencrypt) {
461				static char msg[] = SECURE_MESSAGE;
462				(void) close(pv1[1]);
463				(void) close(pv2[1]);
464				des_enc_write(s, msg, sizeof(msg) - 1,
465					schedule, &kdata->session);
466
467			} else
468#endif
469			{
470				(void) close(0);
471				(void) close(1);
472			}
473			(void) close(2);
474			(void) close(pv[1]);
475
476			FD_ZERO(&readfrom);
477			FD_SET(s, &readfrom);
478			FD_SET(pv[0], &readfrom);
479			if (pv[0] > s)
480				nfd = pv[0];
481			else
482				nfd = s;
483#ifdef CRYPT
484			if (doencrypt) {
485				FD_ZERO(&writeto);
486				FD_SET(pv2[0], &writeto);
487				FD_SET(pv1[0], &readfrom);
488
489				nfd = MAX(nfd, pv2[0]);
490				nfd = MAX(nfd, pv1[0]);
491			} else
492#endif
493				ioctl(pv[0], FIONBIO, (char *)&one);
494
495			/* should set s nbio! */
496			nfd++;
497			do {
498				ready = readfrom;
499#ifdef CRYPT
500				if (doencrypt) {
501					wready = writeto;
502					if (select(nfd, &ready,
503					    &wready, (fd_set *) 0,
504					    (struct timeval *) 0) < 0)
505						break;
506				} else
507#endif
508					if (select(nfd, &ready, (fd_set *)0,
509					  (fd_set *)0, (struct timeval *)0) < 0)
510						break;
511				if (FD_ISSET(s, &ready)) {
512					int	ret;
513#ifdef CRYPT
514					if (doencrypt)
515						ret = des_enc_read(s, &sig, 1,
516						schedule, &kdata->session);
517					else
518#endif
519						ret = read(s, &sig, 1);
520					if (ret <= 0)
521						FD_CLR(s, &readfrom);
522					else
523						killpg(pid, sig);
524				}
525				if (FD_ISSET(pv[0], &ready)) {
526					errno = 0;
527					cc = read(pv[0], buf, sizeof(buf));
528					if (cc <= 0) {
529						shutdown(s, 1+1);
530						FD_CLR(pv[0], &readfrom);
531					} else {
532#ifdef CRYPT
533						if (doencrypt)
534							(void)
535							  des_enc_write(s, buf, cc,
536								schedule, &kdata->session);
537						else
538#endif
539							(void)
540							  write(s, buf, cc);
541					}
542				}
543#ifdef CRYPT
544				if (doencrypt && FD_ISSET(pv1[0], &ready)) {
545					errno = 0;
546					cc = read(pv1[0], buf, sizeof(buf));
547					if (cc <= 0) {
548						shutdown(pv1[0], 1+1);
549						FD_CLR(pv1[0], &readfrom);
550					} else
551						(void) des_enc_write(STDOUT_FILENO,
552						    buf, cc,
553							schedule, &kdata->session);
554				}
555
556				if (doencrypt && FD_ISSET(pv2[0], &wready)) {
557					errno = 0;
558					cc = des_enc_read(STDIN_FILENO,
559					    buf, sizeof(buf),
560						schedule, &kdata->session);
561					if (cc <= 0) {
562						shutdown(pv2[0], 1+1);
563						FD_CLR(pv2[0], &writeto);
564					} else
565						(void) write(pv2[0], buf, cc);
566				}
567#endif
568
569			} while (FD_ISSET(s, &readfrom) ||
570#ifdef CRYPT
571			    (doencrypt && FD_ISSET(pv1[0], &readfrom)) ||
572#endif
573			    FD_ISSET(pv[0], &readfrom));
574			exit(0);
575		}
576		setpgrp(0, getpid());
577		(void) close(s);
578		(void) close(pv[0]);
579#ifdef CRYPT
580		if (doencrypt) {
581			close(pv1[0]); close(pv2[0]);
582			dup2(pv1[1], 1);
583			dup2(pv2[1], 0);
584			close(pv1[1]);
585			close(pv2[1]);
586		}
587#endif
588		dup2(pv[1], 2);
589		close(pv[1]);
590	}
591	if (*pwd->pw_shell == '\0')
592		pwd->pw_shell = _PATH_BSHELL;
593	environ = envinit;
594	strncat(homedir, pwd->pw_dir, sizeof(homedir)-6);
595	strcat(path, _PATH_DEFPATH);
596	strncat(shell, pwd->pw_shell, sizeof(shell)-7);
597	strncat(username, pwd->pw_name, sizeof(username)-6);
598	cp = strrchr(pwd->pw_shell, '/');
599	if (cp)
600		cp++;
601	else
602		cp = pwd->pw_shell;
603#ifdef	LOGIN_CAP
604	if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETALL) != 0) {
605                syslog(LOG_ERR, "setusercontext: %m");
606		exit(1);
607	}
608	login_close(lc);
609#else
610	(void) setgid((gid_t)pwd->pw_gid);
611	initgroups(pwd->pw_name, pwd->pw_gid);
612	(void) setuid((uid_t)pwd->pw_uid);
613#endif
614	endpwent();
615	if (log_success || pwd->pw_uid == 0) {
616		    syslog(LOG_INFO|LOG_AUTH, "%s@%s as %s: cmd='%.80s'",
617			remuser, fromhost, locuser, cmdbuf);
618	}
619	execl(pwd->pw_shell, cp, "-c", cmdbuf, 0);
620	perror(pwd->pw_shell);
621	exit(1);
622}
623
624/*
625 * Report error to client.  Note: can't be used until second socket has
626 * connected to client, or older clients will hang waiting for that
627 * connection first.
628 */
629#if __STDC__
630#include <stdarg.h>
631#else
632#include <varargs.h>
633#endif
634
635void
636#if __STDC__
637error(const char *fmt, ...)
638#else
639error(fmt, va_alist)
640	char *fmt;
641        va_dcl
642#endif
643{
644	va_list ap;
645	int len;
646	char *bp, buf[BUFSIZ];
647#if __STDC__
648	va_start(ap, fmt);
649#else
650	va_start(ap);
651#endif
652	bp = buf;
653	if (sent_null == 0) {
654		*bp++ = 1;
655		len = 1;
656	} else
657		len = 0;
658	(void)vsnprintf(bp, sizeof(buf) - 1, fmt, ap);
659	(void)write(STDERR_FILENO, buf, len + strlen(bp));
660}
661
662void
663getstr(buf, cnt, err)
664	char *buf, *err;
665	int cnt;
666{
667	char c;
668
669	do {
670		if (read(STDIN_FILENO, &c, 1) != 1)
671			exit(1);
672		*buf++ = c;
673		if (--cnt == 0) {
674			error("%s too long\n", err);
675			exit(1);
676		}
677	} while (c != 0);
678}
679
680/*
681 * Check whether host h is in our local domain,
682 * defined as sharing the last two components of the domain part,
683 * or the entire domain part if the local domain has only one component.
684 * If either name is unqualified (contains no '.'),
685 * assume that the host is local, as it will be
686 * interpreted as such.
687 */
688int
689local_domain(h)
690	char *h;
691{
692	char localhost[MAXHOSTNAMELEN];
693	char *p1, *p2;
694
695	localhost[0] = 0;
696	(void) gethostname(localhost, sizeof(localhost) - 1);
697	localhost[sizeof(localhost) - 1] = '\0';
698	p1 = topdomain(localhost);
699	p2 = topdomain(h);
700	if (p1 == NULL || p2 == NULL || !strcasecmp(p1, p2))
701		return (1);
702	return (0);
703}
704
705char *
706topdomain(h)
707	char *h;
708{
709	char *p, *maybe = NULL;
710	int dots = 0;
711
712	for (p = h + strlen(h); p >= h; p--) {
713		if (*p == '.') {
714			if (++dots == 2)
715				return (p);
716			maybe = p;
717		}
718	}
719	return (maybe);
720}
721
722void
723usage()
724{
725
726	syslog(LOG_ERR, "usage: rshd [-%s]", OPTIONS);
727	exit(2);
728}
729