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