1/*-
2 * Copyright (c) 1988, 1989, 1992, 1993, 1994
3 *	The Regents of the University of California.  All rights reserved.
4 * Copyright (c) 2002 Networks Associates Technology, Inc.
5 * All rights reserved.
6 *
7 * Portions of this software were developed for the FreeBSD Project by
8 * ThinkSec AS and NAI Labs, the Security Research Division of Network
9 * Associates, Inc.  under DARPA/SPAWAR contract N66001-01-C-8035
10 * ("CBOSS"), as part of the DARPA CHATS research program.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 *    notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 *    notice, this list of conditions and the following disclaimer in the
19 *    documentation and/or other materials provided with the distribution.
20 * 3. All advertising materials mentioning features or use of this software
21 *    must display the following acknowledgement:
22 *	This product includes software developed by the University of
23 *	California, Berkeley and its contributors.
24 * 4. Neither the name of the University nor the names of its contributors
25 *    may be used to endorse or promote products derived from this software
26 *    without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * SUCH DAMAGE.
39 */
40
41#ifndef lint
42static const char copyright[] =
43"@(#) Copyright (c) 1988, 1989, 1992, 1993, 1994\n\
44	The Regents of the University of California.  All rights reserved.\n";
45#endif /* not lint */
46
47#ifndef lint
48#if 0
49static const char sccsid[] = "@(#)rshd.c	8.2 (Berkeley) 4/6/94";
50#endif
51#endif /* not lint */
52
53#include <sys/cdefs.h>
54__FBSDID("$FreeBSD$");
55
56/*
57 * remote shell server:
58 *	[port]\0
59 *	ruser\0
60 *	luser\0
61 *	command\0
62 *	data
63 */
64#include <sys/param.h>
65#include <sys/ioctl.h>
66#include <sys/time.h>
67#include <sys/socket.h>
68
69#include <netinet/in_systm.h>
70#include <netinet/in.h>
71#include <netinet/ip.h>
72#include <netinet/tcp.h>
73#include <arpa/inet.h>
74#include <netdb.h>
75
76#include <err.h>
77#include <errno.h>
78#include <fcntl.h>
79#include <libutil.h>
80#include <paths.h>
81#include <pwd.h>
82#include <signal.h>
83#include <stdarg.h>
84#include <stdio.h>
85#include <stdlib.h>
86#include <string.h>
87#include <syslog.h>
88#include <unistd.h>
89#include <login_cap.h>
90
91#include <security/pam_appl.h>
92#include <security/openpam.h>
93#include <sys/wait.h>
94
95static struct pam_conv pamc = { openpam_nullconv, NULL };
96static pam_handle_t *pamh;
97static int pam_err;
98
99#define PAM_END { \
100	if ((pam_err = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS) \
101		syslog(LOG_ERR|LOG_AUTH, "pam_setcred(): %s", pam_strerror(pamh, pam_err)); \
102	if ((pam_err = pam_close_session(pamh,0)) != PAM_SUCCESS) \
103		syslog(LOG_ERR|LOG_AUTH, "pam_close_session(): %s", pam_strerror(pamh, pam_err)); \
104	if ((pam_err = pam_end(pamh, pam_err)) != PAM_SUCCESS) \
105		syslog(LOG_ERR|LOG_AUTH, "pam_end(): %s", pam_strerror(pamh, pam_err)); \
106}
107
108int	keepalive = 1;
109int	log_success;		/* If TRUE, log all successful accesses */
110int	sent_null;
111int	no_delay;
112
113void	 doit(struct sockaddr *);
114static void	 rshd_errx(int, const char *, ...) __printf0like(2, 3);
115void	 getstr(char *, int, const char *);
116int	 local_domain(char *);
117char	*topdomain(char *);
118void	 usage(void);
119
120char	 slash[] = "/";
121char	 bshell[] = _PATH_BSHELL;
122
123#define	OPTIONS	"aDLln"
124
125int
126main(int argc, char *argv[])
127{
128	extern int __check_rhosts_file;
129	struct linger linger;
130	socklen_t fromlen;
131	int ch, on = 1;
132	struct sockaddr_storage from;
133
134	openlog("rshd", LOG_PID | LOG_ODELAY, LOG_DAEMON);
135
136	opterr = 0;
137	while ((ch = getopt(argc, argv, OPTIONS)) != -1)
138		switch (ch) {
139		case 'a':
140			/* ignored for compatibility */
141			break;
142		case 'l':
143			__check_rhosts_file = 0;
144			break;
145		case 'n':
146			keepalive = 0;
147			break;
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	fromlen = sizeof (from);
164	if (getpeername(0, (struct sockaddr *)&from, &fromlen) < 0) {
165		syslog(LOG_ERR, "getpeername: %m");
166		exit(1);
167	}
168	if (keepalive &&
169	    setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, (char *)&on,
170	    sizeof(on)) < 0)
171		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
172	linger.l_onoff = 1;
173	linger.l_linger = 60;			/* XXX */
174	if (setsockopt(0, SOL_SOCKET, SO_LINGER, (char *)&linger,
175	    sizeof (linger)) < 0)
176		syslog(LOG_WARNING, "setsockopt (SO_LINGER): %m");
177	if (no_delay &&
178	    setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
179		syslog(LOG_WARNING, "setsockopt (TCP_NODELAY): %m");
180	doit((struct sockaddr *)&from);
181	/* NOTREACHED */
182	return(0);
183}
184
185extern char **environ;
186
187void
188doit(struct sockaddr *fromp)
189{
190	extern char *__rcmd_errstr;	/* syslog hook from libc/net/rcmd.c. */
191	struct passwd *pwd;
192	u_short port;
193	fd_set ready, readfrom;
194	int cc, fd, nfd, pv[2], pid, s;
195	int one = 1;
196	const char *cp, *errorstr;
197	char sig, buf[BUFSIZ];
198	char *cmdbuf, luser[16], ruser[16];
199	char rhost[2 * MAXHOSTNAMELEN + 1];
200	char numericname[INET6_ADDRSTRLEN];
201	int af, srcport;
202	int maxcmdlen;
203	login_cap_t *lc;
204
205	maxcmdlen = (int)sysconf(_SC_ARG_MAX);
206	if (maxcmdlen <= 0 || (cmdbuf = malloc(maxcmdlen)) == NULL)
207		exit(1);
208
209	(void) signal(SIGINT, SIG_DFL);
210	(void) signal(SIGQUIT, SIG_DFL);
211	(void) signal(SIGTERM, SIG_DFL);
212	af = fromp->sa_family;
213	srcport = ntohs(*((in_port_t *)&fromp->sa_data));
214	if (af == AF_INET) {
215		inet_ntop(af, &((struct sockaddr_in *)fromp)->sin_addr,
216		    numericname, sizeof numericname);
217	} else if (af == AF_INET6) {
218		inet_ntop(af, &((struct sockaddr_in6 *)fromp)->sin6_addr,
219		    numericname, sizeof numericname);
220	} else {
221		syslog(LOG_ERR, "malformed \"from\" address (af %d)", af);
222		exit(1);
223	}
224#ifdef IP_OPTIONS
225	if (af == AF_INET) {
226		u_char optbuf[BUFSIZ/3];
227		socklen_t optsize = sizeof(optbuf), ipproto, i;
228		struct protoent *ip;
229
230		if ((ip = getprotobyname("ip")) != NULL)
231			ipproto = ip->p_proto;
232		else
233			ipproto = IPPROTO_IP;
234		if (!getsockopt(0, ipproto, IP_OPTIONS, optbuf, &optsize) &&
235		    optsize != 0) {
236			for (i = 0; i < optsize; ) {
237				u_char c = optbuf[i];
238				if (c == IPOPT_LSRR || c == IPOPT_SSRR) {
239					syslog(LOG_NOTICE,
240					    "connection refused from %s with IP option %s",
241					    numericname,
242					    c == IPOPT_LSRR ? "LSRR" : "SSRR");
243					exit(1);
244				}
245				if (c == IPOPT_EOL)
246					break;
247				i += (c == IPOPT_NOP) ? 1 : optbuf[i+1];
248			}
249		}
250	}
251#endif
252
253	if (srcport >= IPPORT_RESERVED ||
254	    srcport < IPPORT_RESERVED/2) {
255		syslog(LOG_NOTICE|LOG_AUTH,
256		    "connection from %s on illegal port %u",
257		    numericname,
258		    srcport);
259		exit(1);
260	}
261
262	(void) alarm(60);
263	port = 0;
264	s = 0;		/* not set or used if port == 0 */
265	for (;;) {
266		char c;
267		if ((cc = read(STDIN_FILENO, &c, 1)) != 1) {
268			if (cc < 0)
269				syslog(LOG_NOTICE, "read: %m");
270			shutdown(0, SHUT_RDWR);
271			exit(1);
272		}
273		if (c == 0)
274			break;
275		port = port * 10 + c - '0';
276	}
277
278	(void) alarm(0);
279	if (port != 0) {
280		int lport = IPPORT_RESERVED - 1;
281		s = rresvport_af(&lport, af);
282		if (s < 0) {
283			syslog(LOG_ERR, "can't get stderr port: %m");
284			exit(1);
285		}
286		if (port >= IPPORT_RESERVED ||
287		    port < IPPORT_RESERVED/2) {
288			syslog(LOG_NOTICE|LOG_AUTH,
289			    "2nd socket from %s on unreserved port %u",
290			    numericname,
291			    port);
292			exit(1);
293		}
294		*((in_port_t *)&fromp->sa_data) = htons(port);
295		if (connect(s, fromp, fromp->sa_len) < 0) {
296			syslog(LOG_INFO, "connect second port %d: %m", port);
297			exit(1);
298		}
299	}
300
301	errorstr = NULL;
302	realhostname_sa(rhost, sizeof(rhost) - 1, fromp, fromp->sa_len);
303	rhost[sizeof(rhost) - 1] = '\0';
304	/* XXX truncation! */
305
306	(void) alarm(60);
307	getstr(ruser, sizeof(ruser), "ruser");
308	getstr(luser, sizeof(luser), "luser");
309	getstr(cmdbuf, maxcmdlen, "command");
310	(void) alarm(0);
311
312	pam_err = pam_start("rsh", luser, &pamc, &pamh);
313	if (pam_err != PAM_SUCCESS) {
314		syslog(LOG_ERR|LOG_AUTH, "pam_start(): %s",
315		    pam_strerror(pamh, pam_err));
316		rshd_errx(1, "Login incorrect.");
317	}
318
319	if ((pam_err = pam_set_item(pamh, PAM_RUSER, ruser)) != PAM_SUCCESS ||
320	    (pam_err = pam_set_item(pamh, PAM_RHOST, rhost)) != PAM_SUCCESS) {
321		syslog(LOG_ERR|LOG_AUTH, "pam_set_item(): %s",
322		    pam_strerror(pamh, pam_err));
323		rshd_errx(1, "Login incorrect.");
324	}
325
326	pam_err = pam_authenticate(pamh, 0);
327	if (pam_err == PAM_SUCCESS) {
328		if ((pam_err = pam_get_user(pamh, &cp, NULL)) == PAM_SUCCESS) {
329			strncpy(luser, cp, sizeof(luser));
330			luser[sizeof(luser) - 1] = '\0';
331			/* XXX truncation! */
332		}
333		pam_err = pam_acct_mgmt(pamh, 0);
334	}
335	if (pam_err != PAM_SUCCESS) {
336		syslog(LOG_INFO|LOG_AUTH,
337		    "%s@%s as %s: permission denied (%s). cmd='%.80s'",
338		    ruser, rhost, luser, pam_strerror(pamh, pam_err), cmdbuf);
339		rshd_errx(1, "Login incorrect.");
340	}
341
342	setpwent();
343	pwd = getpwnam(luser);
344	if (pwd == NULL) {
345		syslog(LOG_INFO|LOG_AUTH,
346		    "%s@%s as %s: unknown login. cmd='%.80s'",
347		    ruser, rhost, luser, cmdbuf);
348		if (errorstr == NULL)
349			errorstr = "Login incorrect.";
350		rshd_errx(1, errorstr, rhost);
351	}
352
353	lc = login_getpwclass(pwd);
354	if (pwd->pw_uid)
355		auth_checknologin(lc);
356
357	if (chdir(pwd->pw_dir) < 0) {
358		if (chdir("/") < 0 ||
359		    login_getcapbool(lc, "requirehome", !!pwd->pw_uid)) {
360			syslog(LOG_INFO|LOG_AUTH,
361			"%s@%s as %s: no home directory. cmd='%.80s'",
362			ruser, rhost, luser, cmdbuf);
363			rshd_errx(0, "No remote home directory.");
364		}
365		pwd->pw_dir = slash;
366	}
367
368	if (lc != NULL && fromp->sa_family == AF_INET) {	/*XXX*/
369		char	remote_ip[MAXHOSTNAMELEN];
370
371		strncpy(remote_ip, numericname,
372			sizeof(remote_ip) - 1);
373		remote_ip[sizeof(remote_ip) - 1] = 0;
374		/* XXX truncation! */
375		if (!auth_hostok(lc, rhost, remote_ip)) {
376			syslog(LOG_INFO|LOG_AUTH,
377			    "%s@%s as %s: permission denied (%s). cmd='%.80s'",
378			    ruser, rhost, luser, __rcmd_errstr,
379			    cmdbuf);
380			rshd_errx(1, "Login incorrect.");
381		}
382		if (!auth_timeok(lc, time(NULL)))
383			rshd_errx(1, "Logins not available right now");
384	}
385
386	/*
387	 * PAM modules might add supplementary groups in
388	 * pam_setcred(), so initialize them first.
389	 * But we need to open the session as root.
390	 */
391	if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) != 0) {
392		syslog(LOG_ERR, "setusercontext: %m");
393		exit(1);
394	}
395
396	if ((pam_err = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
397		syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, pam_err));
398	} else if ((pam_err = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
399		syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, pam_err));
400	}
401
402	(void) write(STDERR_FILENO, "\0", 1);
403	sent_null = 1;
404
405	if (port) {
406		if (pipe(pv) < 0)
407			rshd_errx(1, "Can't make pipe.");
408		pid = fork();
409		if (pid == -1)
410			rshd_errx(1, "Can't fork; try again.");
411		if (pid) {
412			(void) close(0);
413			(void) close(1);
414			(void) close(2);
415			(void) close(pv[1]);
416
417			FD_ZERO(&readfrom);
418			FD_SET(s, &readfrom);
419			FD_SET(pv[0], &readfrom);
420			if (pv[0] > s)
421				nfd = pv[0];
422			else
423				nfd = s;
424				ioctl(pv[0], FIONBIO, (char *)&one);
425
426			/* should set s nbio! */
427			nfd++;
428			do {
429				ready = readfrom;
430				if (select(nfd, &ready, (fd_set *)0,
431				  (fd_set *)0, (struct timeval *)0) < 0)
432					break;
433				if (FD_ISSET(s, &ready)) {
434					int	ret;
435						ret = read(s, &sig, 1);
436				if (ret <= 0)
437					FD_CLR(s, &readfrom);
438				else
439					killpg(pid, sig);
440				}
441				if (FD_ISSET(pv[0], &ready)) {
442					errno = 0;
443					cc = read(pv[0], buf, sizeof(buf));
444					if (cc <= 0) {
445						shutdown(s, SHUT_RDWR);
446						FD_CLR(pv[0], &readfrom);
447					} else {
448						(void)write(s, buf, cc);
449					}
450				}
451
452			} while (FD_ISSET(s, &readfrom) ||
453			    FD_ISSET(pv[0], &readfrom));
454			PAM_END;
455			exit(0);
456		}
457		(void) close(s);
458		(void) close(pv[0]);
459		dup2(pv[1], 2);
460		close(pv[1]);
461	}
462	else {
463		pid = fork();
464		if (pid == -1)
465			rshd_errx(1, "Can't fork; try again.");
466		if (pid) {
467			/* Parent. */
468			while (wait(NULL) > 0 || errno == EINTR)
469				/* nothing */ ;
470			PAM_END;
471			exit(0);
472		}
473	}
474
475	for (fd = getdtablesize(); fd > 2; fd--)
476		(void) close(fd);
477	if (setsid() == -1)
478		syslog(LOG_ERR, "setsid() failed: %m");
479	if (setlogin(pwd->pw_name) < 0)
480		syslog(LOG_ERR, "setlogin() failed: %m");
481
482	if (*pwd->pw_shell == '\0')
483		pwd->pw_shell = bshell;
484	(void) pam_setenv(pamh, "HOME", pwd->pw_dir, 1);
485	(void) pam_setenv(pamh, "SHELL", pwd->pw_shell, 1);
486	(void) pam_setenv(pamh, "USER", pwd->pw_name, 1);
487	(void) pam_setenv(pamh, "PATH", _PATH_DEFPATH, 1);
488	environ = pam_getenvlist(pamh);
489	(void) pam_end(pamh, pam_err);
490	cp = strrchr(pwd->pw_shell, '/');
491	if (cp)
492		cp++;
493	else
494		cp = pwd->pw_shell;
495
496	if (setusercontext(lc, pwd, pwd->pw_uid,
497		LOGIN_SETALL & ~LOGIN_SETGROUP) < 0) {
498		syslog(LOG_ERR, "setusercontext(): %m");
499		exit(1);
500	}
501	login_close(lc);
502	endpwent();
503	if (log_success || pwd->pw_uid == 0) {
504		    syslog(LOG_INFO|LOG_AUTH, "%s@%s as %s: cmd='%.80s'",
505			ruser, rhost, luser, cmdbuf);
506	}
507	execl(pwd->pw_shell, cp, "-c", cmdbuf, (char *)NULL);
508	err(1, "%s", pwd->pw_shell);
509	exit(1);
510}
511
512/*
513 * Report error to client.  Note: can't be used until second socket has
514 * connected to client, or older clients will hang waiting for that
515 * connection first.
516 */
517
518static void
519rshd_errx(int errcode, const char *fmt, ...)
520{
521	va_list ap;
522
523	va_start(ap, fmt);
524
525	if (sent_null == 0)
526		write(STDERR_FILENO, "\1", 1);
527
528	verrx(errcode, fmt, ap);
529	/* NOTREACHED */
530}
531
532void
533getstr(char *buf, int cnt, const char *error)
534{
535	char c;
536
537	do {
538		if (read(STDIN_FILENO, &c, 1) != 1)
539			exit(1);
540		*buf++ = c;
541		if (--cnt == 0)
542			rshd_errx(1, "%s too long", error);
543	} while (c != 0);
544}
545
546/*
547 * Check whether host h is in our local domain,
548 * defined as sharing the last two components of the domain part,
549 * or the entire domain part if the local domain has only one component.
550 * If either name is unqualified (contains no '.'),
551 * assume that the host is local, as it will be
552 * interpreted as such.
553 */
554int
555local_domain(char *h)
556{
557	char localhost[MAXHOSTNAMELEN];
558	char *p1, *p2;
559
560	localhost[0] = 0;
561	(void) gethostname(localhost, sizeof(localhost) - 1);
562	localhost[sizeof(localhost) - 1] = '\0';
563	/* XXX truncation! */
564	p1 = topdomain(localhost);
565	p2 = topdomain(h);
566	if (p1 == NULL || p2 == NULL || !strcasecmp(p1, p2))
567		return (1);
568	return (0);
569}
570
571char *
572topdomain(char *h)
573{
574	char *p, *maybe = NULL;
575	int dots = 0;
576
577	for (p = h + strlen(h); p >= h; p--) {
578		if (*p == '.') {
579			if (++dots == 2)
580				return (p);
581			maybe = p;
582		}
583	}
584	return (maybe);
585}
586
587void
588usage(void)
589{
590
591	syslog(LOG_ERR, "usage: rshd [-%s]", OPTIONS);
592	exit(2);
593}
594