rshd.c revision 98885
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: head/libexec/rshd/rshd.c 98885 2002-06-26 17:09:08Z markm $");
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	"alnDL"
124
125int
126main(int argc, char *argv[])
127{
128	extern int __check_rhosts_file;
129	struct linger linger;
130	int ch, on = 1, fromlen;
131	struct sockaddr_storage from;
132
133	openlog("rshd", LOG_PID | LOG_ODELAY, LOG_DAEMON);
134
135	opterr = 0;
136	while ((ch = getopt(argc, argv, OPTIONS)) != -1)
137		switch (ch) {
138		case 'a':
139			/* ignored for compatibility */
140			break;
141		case 'l':
142			__check_rhosts_file = 0;
143			break;
144		case 'n':
145			keepalive = 0;
146			break;
147		case 'D':
148			no_delay = 1;
149			break;
150		case 'L':
151			log_success = 1;
152			break;
153		case '?':
154		default:
155			usage();
156			break;
157		}
158
159	argc -= optind;
160	argv += optind;
161
162	fromlen = sizeof (from);
163	if (getpeername(0, (struct sockaddr *)&from, &fromlen) < 0) {
164		syslog(LOG_ERR, "getpeername: %m");
165		exit(1);
166	}
167	if (keepalive &&
168	    setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, (char *)&on,
169	    sizeof(on)) < 0)
170		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
171	linger.l_onoff = 1;
172	linger.l_linger = 60;			/* XXX */
173	if (setsockopt(0, SOL_SOCKET, SO_LINGER, (char *)&linger,
174	    sizeof (linger)) < 0)
175		syslog(LOG_WARNING, "setsockopt (SO_LINGER): %m");
176	if (no_delay &&
177	    setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
178		syslog(LOG_WARNING, "setsockopt (TCP_NODELAY): %m");
179	doit((struct sockaddr *)&from);
180	/* NOTREACHED */
181	return(0);
182}
183
184extern char **environ;
185
186void
187doit(struct sockaddr *fromp)
188{
189	extern char *__rcmd_errstr;	/* syslog hook from libc/net/rcmd.c. */
190	struct passwd *pwd;
191	u_short port;
192	fd_set ready, readfrom;
193	int cc, fd, nfd, pv[2], pid, s;
194	int one = 1;
195	const char *cp, *errorstr;
196	char sig, buf[BUFSIZ];
197	char cmdbuf[NCARGS+1], luser[16], ruser[16];
198	char rhost[2 * MAXHOSTNAMELEN + 1];
199	char numericname[INET6_ADDRSTRLEN];
200	int af, srcport;
201	login_cap_t *lc;
202
203	(void) signal(SIGINT, SIG_DFL);
204	(void) signal(SIGQUIT, SIG_DFL);
205	(void) signal(SIGTERM, SIG_DFL);
206	af = fromp->sa_family;
207	srcport = ntohs(*((in_port_t *)&fromp->sa_data));
208	if (af == AF_INET) {
209		inet_ntop(af, &((struct sockaddr_in *)fromp)->sin_addr,
210		    numericname, sizeof numericname);
211	} else if (af == AF_INET6) {
212		inet_ntop(af, &((struct sockaddr_in6 *)fromp)->sin6_addr,
213		    numericname, sizeof numericname);
214	} else {
215		syslog(LOG_ERR, "malformed \"from\" address (af %d)", af);
216		exit(1);
217	}
218#ifdef IP_OPTIONS
219	if (af == AF_INET) {
220		u_char optbuf[BUFSIZ/3];
221		int optsize = sizeof(optbuf), ipproto, i;
222		struct protoent *ip;
223
224		if ((ip = getprotobyname("ip")) != NULL)
225			ipproto = ip->p_proto;
226		else
227			ipproto = IPPROTO_IP;
228		if (!getsockopt(0, ipproto, IP_OPTIONS, optbuf, &optsize) &&
229		    optsize != 0) {
230			for (i = 0; i < optsize; ) {
231				u_char c = optbuf[i];
232				if (c == IPOPT_LSRR || c == IPOPT_SSRR) {
233					syslog(LOG_NOTICE,
234					    "connection refused from %s with IP option %s",
235					    numericname,
236					    c == IPOPT_LSRR ? "LSRR" : "SSRR");
237					exit(1);
238				}
239				if (c == IPOPT_EOL)
240					break;
241				i += (c == IPOPT_NOP) ? 1 : optbuf[i+1];
242			}
243		}
244	}
245#endif
246
247	if (srcport >= IPPORT_RESERVED ||
248	    srcport < IPPORT_RESERVED/2) {
249		syslog(LOG_NOTICE|LOG_AUTH,
250		    "connection from %s on illegal port %u",
251		    numericname,
252		    srcport);
253		exit(1);
254	}
255
256	(void) alarm(60);
257	port = 0;
258	s = 0;		/* not set or used if port == 0 */
259	for (;;) {
260		char c;
261		if ((cc = read(STDIN_FILENO, &c, 1)) != 1) {
262			if (cc < 0)
263				syslog(LOG_NOTICE, "read: %m");
264			shutdown(0, 1+1);
265			exit(1);
266		}
267		if (c == 0)
268			break;
269		port = port * 10 + c - '0';
270	}
271
272	(void) alarm(0);
273	if (port != 0) {
274		int lport = IPPORT_RESERVED - 1;
275		s = rresvport_af(&lport, af);
276		if (s < 0) {
277			syslog(LOG_ERR, "can't get stderr port: %m");
278			exit(1);
279		}
280		if (port >= IPPORT_RESERVED ||
281		    port < IPPORT_RESERVED/2) {
282			syslog(LOG_NOTICE|LOG_AUTH,
283			    "2nd socket from %s on unreserved port %u",
284			    numericname,
285			    port);
286			exit(1);
287		}
288		*((in_port_t *)&fromp->sa_data) = htons(port);
289		if (connect(s, fromp, fromp->sa_len) < 0) {
290			syslog(LOG_INFO, "connect second port %d: %m", port);
291			exit(1);
292		}
293	}
294
295	errorstr = NULL;
296	realhostname_sa(rhost, sizeof(rhost) - 1, fromp, fromp->sa_len);
297	rhost[sizeof(rhost) - 1] = '\0';
298	/* XXX truncation! */
299
300	(void) alarm(60);
301	getstr(ruser, sizeof(ruser), "ruser");
302	getstr(luser, sizeof(luser), "luser");
303	getstr(cmdbuf, sizeof(cmdbuf), "command");
304	(void) alarm(0);
305
306	pam_err = pam_start("rsh", luser, &pamc, &pamh);
307	if (pam_err != PAM_SUCCESS) {
308		syslog(LOG_ERR|LOG_AUTH, "pam_start(): %s",
309		    pam_strerror(pamh, pam_err));
310		rshd_errx(1, "Login incorrect.");
311	}
312
313	if ((pam_err = pam_set_item(pamh, PAM_RUSER, ruser)) != PAM_SUCCESS ||
314	    (pam_err = pam_set_item(pamh, PAM_RHOST, rhost) != PAM_SUCCESS)) {
315		syslog(LOG_ERR|LOG_AUTH, "pam_set_item(): %s",
316		    pam_strerror(pamh, pam_err));
317		rshd_errx(1, "Login incorrect.");
318	}
319
320	pam_err = pam_authenticate(pamh, 0);
321	if (pam_err == PAM_SUCCESS) {
322		if ((pam_err = pam_get_user(pamh, &cp, NULL)) == PAM_SUCCESS) {
323			strncpy(luser, cp, sizeof(luser));
324			luser[sizeof(luser) - 1] = '\0';
325			/* XXX truncation! */
326		}
327		pam_err = pam_acct_mgmt(pamh, 0);
328	}
329	if (pam_err != PAM_SUCCESS) {
330		syslog(LOG_INFO|LOG_AUTH,
331		    "%s@%s as %s: permission denied (%s). cmd='%.80s'",
332		    ruser, rhost, luser, pam_strerror(pamh, pam_err), cmdbuf);
333		rshd_errx(1, "Login incorrect.");
334	}
335
336	setpwent();
337	pwd = getpwnam(luser);
338	if (pwd == NULL) {
339		syslog(LOG_INFO|LOG_AUTH,
340		    "%s@%s as %s: unknown login. cmd='%.80s'",
341		    ruser, rhost, luser, cmdbuf);
342		if (errorstr == NULL)
343			errorstr = "Login incorrect.";
344		rshd_errx(1, errorstr, rhost);
345	}
346
347	lc = login_getpwclass(pwd);
348	if (pwd->pw_uid)
349		auth_checknologin(lc);
350
351	if (chdir(pwd->pw_dir) < 0) {
352		if (chdir("/") < 0 ||
353		    login_getcapbool(lc, "requirehome", !!pwd->pw_uid)) {
354			syslog(LOG_INFO|LOG_AUTH,
355			"%s@%s as %s: no home directory. cmd='%.80s'",
356			ruser, rhost, luser, cmdbuf);
357			rshd_errx(0, "No remote home directory.");
358		}
359		pwd->pw_dir = slash;
360	}
361
362	if (lc != NULL && fromp->sa_family == AF_INET) {	/*XXX*/
363		char	remote_ip[MAXHOSTNAMELEN];
364
365		strncpy(remote_ip, numericname,
366			sizeof(remote_ip) - 1);
367		remote_ip[sizeof(remote_ip) - 1] = 0;
368		/* XXX truncation! */
369		if (!auth_hostok(lc, rhost, remote_ip)) {
370			syslog(LOG_INFO|LOG_AUTH,
371			    "%s@%s as %s: permission denied (%s). cmd='%.80s'",
372			    ruser, rhost, luser, __rcmd_errstr,
373			    cmdbuf);
374			rshd_errx(1, "Login incorrect.");
375		}
376		if (!auth_timeok(lc, time(NULL)))
377			rshd_errx(1, "Logins not available right now");
378	}
379
380	/*
381	 * PAM modules might add supplementary groups in
382	 * pam_setcred(), so initialize them first.
383	 * But we need to open the session as root.
384	 */
385	if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) != 0) {
386		syslog(LOG_ERR, "setusercontext: %m");
387		exit(1);
388	}
389
390	if ((pam_err = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
391		syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, pam_err));
392	} else if ((pam_err = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
393		syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, pam_err));
394	}
395
396	(void) write(STDERR_FILENO, "\0", 1);
397	sent_null = 1;
398
399	if (port) {
400		if (pipe(pv) < 0)
401			rshd_errx(1, "Can't make pipe.");
402		pid = fork();
403		if (pid == -1)
404			rshd_errx(1, "Can't fork; try again.");
405		if (pid) {
406			(void) close(0);
407			(void) close(1);
408			(void) close(2);
409			(void) close(pv[1]);
410
411			FD_ZERO(&readfrom);
412			FD_SET(s, &readfrom);
413			FD_SET(pv[0], &readfrom);
414			if (pv[0] > s)
415				nfd = pv[0];
416			else
417				nfd = s;
418				ioctl(pv[0], FIONBIO, (char *)&one);
419
420			/* should set s nbio! */
421			nfd++;
422			do {
423				ready = readfrom;
424				if (select(nfd, &ready, (fd_set *)0,
425				  (fd_set *)0, (struct timeval *)0) < 0)
426					break;
427				if (FD_ISSET(s, &ready)) {
428					int	ret;
429						ret = read(s, &sig, 1);
430				if (ret <= 0)
431					FD_CLR(s, &readfrom);
432				else
433					killpg(pid, sig);
434				}
435				if (FD_ISSET(pv[0], &ready)) {
436					errno = 0;
437					cc = read(pv[0], buf, sizeof(buf));
438					if (cc <= 0) {
439						shutdown(s, 1+1);
440						FD_CLR(pv[0], &readfrom);
441					} else {
442						(void)write(s, buf, cc);
443					}
444				}
445
446			} while (FD_ISSET(s, &readfrom) ||
447			    FD_ISSET(pv[0], &readfrom));
448			PAM_END;
449			exit(0);
450		}
451		(void) close(s);
452		(void) close(pv[0]);
453		dup2(pv[1], 2);
454		close(pv[1]);
455	}
456	else {
457		pid = fork();
458		if (pid == -1)
459			rshd_errx(1, "Can't fork; try again.");
460		if (pid) {
461			/* Parent. */
462			while (wait(NULL) > 0 || errno == EINTR)
463				/* nothing */ ;
464			PAM_END;
465			exit(0);
466		}
467	}
468
469	for (fd = getdtablesize(); fd > 2; fd--)
470		(void) close(fd);
471	if (setsid() == -1)
472		syslog(LOG_ERR, "setsid() failed: %m");
473	if (setlogin(pwd->pw_name) < 0)
474		syslog(LOG_ERR, "setlogin() failed: %m");
475
476	if (*pwd->pw_shell == '\0')
477		pwd->pw_shell = bshell;
478	(void) pam_setenv(pamh, "HOME", pwd->pw_dir, 1);
479	(void) pam_setenv(pamh, "SHELL", pwd->pw_shell, 1);
480	(void) pam_setenv(pamh, "USER", pwd->pw_name, 1);
481	(void) pam_setenv(pamh, "PATH", _PATH_DEFPATH, 1);
482	environ = pam_getenvlist(pamh);
483	(void) pam_end(pamh, pam_err);
484	cp = strrchr(pwd->pw_shell, '/');
485	if (cp)
486		cp++;
487	else
488		cp = pwd->pw_shell;
489
490	if (setusercontext(lc, pwd, pwd->pw_uid,
491		LOGIN_SETALL & ~LOGIN_SETGROUP) < 0) {
492		syslog(LOG_ERR, "setusercontext(): %m");
493		exit(1);
494	}
495	login_close(lc);
496	endpwent();
497	if (log_success || pwd->pw_uid == 0) {
498		    syslog(LOG_INFO|LOG_AUTH, "%s@%s as %s: cmd='%.80s'",
499			ruser, rhost, luser, cmdbuf);
500	}
501	execl(pwd->pw_shell, cp, "-c", cmdbuf, NULL);
502	err(1, "%s", pwd->pw_shell);
503	exit(1);
504}
505
506/*
507 * Report error to client.  Note: can't be used until second socket has
508 * connected to client, or older clients will hang waiting for that
509 * connection first.
510 */
511
512static void
513rshd_errx(int errcode, const char *fmt, ...)
514{
515	va_list ap;
516
517	va_start(ap, fmt);
518
519	if (sent_null == 0)
520		write(STDERR_FILENO, "\1", 1);
521
522	verrx(errcode, fmt, ap);
523	/* NOTREACHED */
524}
525
526void
527getstr(char *buf, int cnt, const char *error)
528{
529	char c;
530
531	do {
532		if (read(STDIN_FILENO, &c, 1) != 1)
533			exit(1);
534		*buf++ = c;
535		if (--cnt == 0)
536			rshd_errx(1, "%s too long", error);
537	} while (c != 0);
538}
539
540/*
541 * Check whether host h is in our local domain,
542 * defined as sharing the last two components of the domain part,
543 * or the entire domain part if the local domain has only one component.
544 * If either name is unqualified (contains no '.'),
545 * assume that the host is local, as it will be
546 * interpreted as such.
547 */
548int
549local_domain(char *h)
550{
551	char localhost[MAXHOSTNAMELEN];
552	char *p1, *p2;
553
554	localhost[0] = 0;
555	(void) gethostname(localhost, sizeof(localhost) - 1);
556	localhost[sizeof(localhost) - 1] = '\0';
557	/* XXX truncation! */
558	p1 = topdomain(localhost);
559	p2 = topdomain(h);
560	if (p1 == NULL || p2 == NULL || !strcasecmp(p1, p2))
561		return (1);
562	return (0);
563}
564
565char *
566topdomain(char *h)
567{
568	char *p, *maybe = NULL;
569	int dots = 0;
570
571	for (p = h + strlen(h); p >= h; p--) {
572		if (*p == '.') {
573			if (++dots == 2)
574				return (p);
575			maybe = p;
576		}
577	}
578	return (maybe);
579}
580
581void
582usage(void)
583{
584
585	syslog(LOG_ERR, "usage: rshd [-%s]", OPTIONS);
586	exit(2);
587}
588