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. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37#ifndef lint
38static const char copyright[] =
39"@(#) Copyright (c) 1988, 1989, 1992, 1993, 1994\n\
40	The Regents of the University of California.  All rights reserved.\n";
41#endif /* not lint */
42
43#ifndef lint
44#if 0
45static const char sccsid[] = "@(#)rshd.c	8.2 (Berkeley) 4/6/94";
46#endif
47#endif /* not lint */
48
49#include <sys/cdefs.h>
50__FBSDID("$FreeBSD: stable/11/libexec/rshd/rshd.c 360673 2020-05-05 20:53:45Z dim $");
51
52/*
53 * remote shell server:
54 *	[port]\0
55 *	ruser\0
56 *	luser\0
57 *	command\0
58 *	data
59 */
60#include <sys/param.h>
61#include <sys/ioctl.h>
62#include <sys/time.h>
63#include <sys/socket.h>
64
65#include <netinet/in_systm.h>
66#include <netinet/in.h>
67#include <netinet/ip.h>
68#include <netinet/tcp.h>
69#include <arpa/inet.h>
70#include <netdb.h>
71
72#include <err.h>
73#include <errno.h>
74#include <fcntl.h>
75#include <libutil.h>
76#include <paths.h>
77#include <pwd.h>
78#include <signal.h>
79#include <stdarg.h>
80#include <stdio.h>
81#include <stdlib.h>
82#include <string.h>
83#include <syslog.h>
84#include <unistd.h>
85#include <login_cap.h>
86
87#include <security/pam_appl.h>
88#include <security/openpam.h>
89#include <sys/wait.h>
90
91#ifdef USE_BLACKLIST
92#include <blacklist.h>
93#endif
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_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, 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#ifdef USE_BLACKLIST
260		blacklist(1, STDIN_FILENO, "illegal port");
261#endif
262		exit(1);
263	}
264
265	(void) alarm(60);
266	port = 0;
267	s = 0;		/* not set or used if port == 0 */
268	for (;;) {
269		char c;
270		if ((cc = read(STDIN_FILENO, &c, 1)) != 1) {
271			if (cc < 0)
272				syslog(LOG_NOTICE, "read: %m");
273			shutdown(0, SHUT_RDWR);
274			exit(1);
275		}
276		if (c == 0)
277			break;
278		port = port * 10 + c - '0';
279	}
280
281	(void) alarm(0);
282	if (port != 0) {
283		int lport = IPPORT_RESERVED - 1;
284		s = rresvport_af(&lport, af);
285		if (s < 0) {
286			syslog(LOG_ERR, "can't get stderr port: %m");
287			exit(1);
288		}
289		if (port >= IPPORT_RESERVED ||
290		    port < IPPORT_RESERVED/2) {
291			syslog(LOG_NOTICE|LOG_AUTH,
292			    "2nd socket from %s on unreserved port %u",
293			    numericname,
294			    port);
295#ifdef USE_BLACKLIST
296			blacklist(1, STDIN_FILENO, "unreserved port");
297#endif
298			exit(1);
299		}
300		*((in_port_t *)&fromp->sa_data) = htons(port);
301		if (connect(s, fromp, fromp->sa_len) < 0) {
302			syslog(LOG_INFO, "connect second port %d: %m", port);
303			exit(1);
304		}
305	}
306
307	errorstr = NULL;
308	realhostname_sa(rhost, sizeof(rhost) - 1, fromp, fromp->sa_len);
309	rhost[sizeof(rhost) - 1] = '\0';
310	/* XXX truncation! */
311
312	(void) alarm(60);
313	getstr(ruser, sizeof(ruser), "ruser");
314	getstr(luser, sizeof(luser), "luser");
315	getstr(cmdbuf, maxcmdlen, "command");
316	(void) alarm(0);
317
318	pam_err = pam_start("rsh", luser, &pamc, &pamh);
319	if (pam_err != PAM_SUCCESS) {
320		syslog(LOG_ERR|LOG_AUTH, "pam_start(): %s",
321		    pam_strerror(pamh, pam_err));
322#ifdef USE_BLACKLIST
323		blacklist(1, STDIN_FILENO, "login incorrect");
324#endif
325		rshd_errx(1, "Login incorrect.");
326	}
327
328	if ((pam_err = pam_set_item(pamh, PAM_RUSER, ruser)) != PAM_SUCCESS ||
329	    (pam_err = pam_set_item(pamh, PAM_RHOST, rhost)) != PAM_SUCCESS) {
330		syslog(LOG_ERR|LOG_AUTH, "pam_set_item(): %s",
331		    pam_strerror(pamh, pam_err));
332#ifdef USE_BLACKLIST
333		blacklist(1, STDIN_FILENO, "login incorrect");
334#endif
335		rshd_errx(1, "Login incorrect.");
336	}
337
338	pam_err = pam_authenticate(pamh, 0);
339	if (pam_err == PAM_SUCCESS) {
340		if ((pam_err = pam_get_user(pamh, &cp, NULL)) == PAM_SUCCESS) {
341			strlcpy(luser, cp, sizeof(luser));
342			/* XXX truncation! */
343		}
344		pam_err = pam_acct_mgmt(pamh, 0);
345	}
346	if (pam_err != PAM_SUCCESS) {
347		syslog(LOG_INFO|LOG_AUTH,
348		    "%s@%s as %s: permission denied (%s). cmd='%.80s'",
349		    ruser, rhost, luser, pam_strerror(pamh, pam_err), cmdbuf);
350#ifdef USE_BLACKLIST
351		blacklist(1, STDIN_FILENO, "permission denied");
352#endif
353		rshd_errx(1, "Login incorrect.");
354	}
355
356	setpwent();
357	pwd = getpwnam(luser);
358	if (pwd == NULL) {
359		syslog(LOG_INFO|LOG_AUTH,
360		    "%s@%s as %s: unknown login. cmd='%.80s'",
361		    ruser, rhost, luser, cmdbuf);
362#ifdef USE_BLACKLIST
363		blacklist(1, STDIN_FILENO, "unknown login");
364#endif
365		if (errorstr == NULL)
366			errorstr = "Login incorrect.";
367		rshd_errx(1, errorstr, rhost);
368	}
369
370	lc = login_getpwclass(pwd);
371	if (pwd->pw_uid)
372		auth_checknologin(lc);
373
374	if (chdir(pwd->pw_dir) < 0) {
375		if (chdir("/") < 0 ||
376		    login_getcapbool(lc, "requirehome", !!pwd->pw_uid)) {
377			syslog(LOG_INFO|LOG_AUTH,
378			"%s@%s as %s: no home directory. cmd='%.80s'",
379			ruser, rhost, luser, cmdbuf);
380			rshd_errx(0, "No remote home directory.");
381		}
382		pwd->pw_dir = slash;
383	}
384
385	if (lc != NULL && fromp->sa_family == AF_INET) {	/*XXX*/
386		char	remote_ip[MAXHOSTNAMELEN];
387
388		strlcpy(remote_ip, numericname, sizeof(remote_ip));
389		/* XXX truncation! */
390		if (!auth_hostok(lc, rhost, remote_ip)) {
391			syslog(LOG_INFO|LOG_AUTH,
392			    "%s@%s as %s: permission denied (%s). cmd='%.80s'",
393			    ruser, rhost, luser, __rcmd_errstr,
394			    cmdbuf);
395#ifdef USE_BLACKLIST
396			blacklist(1, STDIN_FILENO, "permission denied");
397#endif
398			rshd_errx(1, "Login incorrect.");
399		}
400		if (!auth_timeok(lc, time(NULL)))
401			rshd_errx(1, "Logins not available right now");
402	}
403
404	/*
405	 * PAM modules might add supplementary groups in
406	 * pam_setcred(), so initialize them first.
407	 * But we need to open the session as root.
408	 */
409	if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) != 0) {
410		syslog(LOG_ERR, "setusercontext: %m");
411		exit(1);
412	}
413
414	if ((pam_err = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
415		syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, pam_err));
416	} else if ((pam_err = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
417		syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, pam_err));
418	}
419
420	(void) write(STDERR_FILENO, "\0", 1);
421	sent_null = 1;
422
423	if (port) {
424		if (pipe(pv) < 0)
425			rshd_errx(1, "Can't make pipe.");
426		pid = fork();
427		if (pid == -1)
428			rshd_errx(1, "Can't fork; try again.");
429		if (pid) {
430			(void) close(0);
431			(void) close(1);
432			(void) close(2);
433			(void) close(pv[1]);
434
435			FD_ZERO(&readfrom);
436			FD_SET(s, &readfrom);
437			FD_SET(pv[0], &readfrom);
438			if (pv[0] > s)
439				nfd = pv[0];
440			else
441				nfd = s;
442			ioctl(pv[0], FIONBIO, (char *)&one);
443
444			/* should set s nbio! */
445			nfd++;
446			do {
447				ready = readfrom;
448				if (select(nfd, &ready, (fd_set *)0,
449				  (fd_set *)0, (struct timeval *)0) < 0)
450					break;
451				if (FD_ISSET(s, &ready)) {
452					int	ret;
453						ret = read(s, &sig, 1);
454				if (ret <= 0)
455					FD_CLR(s, &readfrom);
456				else
457					killpg(pid, sig);
458				}
459				if (FD_ISSET(pv[0], &ready)) {
460					errno = 0;
461					cc = read(pv[0], buf, sizeof(buf));
462					if (cc <= 0) {
463						shutdown(s, SHUT_RDWR);
464						FD_CLR(pv[0], &readfrom);
465					} else {
466						(void)write(s, buf, cc);
467					}
468				}
469
470			} while (FD_ISSET(s, &readfrom) ||
471			    FD_ISSET(pv[0], &readfrom));
472			PAM_END;
473			exit(0);
474		}
475		(void) close(s);
476		(void) close(pv[0]);
477		dup2(pv[1], 2);
478		close(pv[1]);
479	}
480	else {
481		pid = fork();
482		if (pid == -1)
483			rshd_errx(1, "Can't fork; try again.");
484		if (pid) {
485			/* Parent. */
486			while (wait(NULL) > 0 || errno == EINTR)
487				/* nothing */ ;
488			PAM_END;
489			exit(0);
490		}
491	}
492
493#ifdef USE_BLACKLIST
494	blacklist(0, STDIN_FILENO, "success");
495#endif
496	closefrom(3);
497	if (setsid() == -1)
498		syslog(LOG_ERR, "setsid() failed: %m");
499	if (setlogin(pwd->pw_name) < 0)
500		syslog(LOG_ERR, "setlogin() failed: %m");
501
502	if (*pwd->pw_shell == '\0')
503		pwd->pw_shell = bshell;
504	(void) pam_setenv(pamh, "HOME", pwd->pw_dir, 1);
505	(void) pam_setenv(pamh, "SHELL", pwd->pw_shell, 1);
506	(void) pam_setenv(pamh, "USER", pwd->pw_name, 1);
507	(void) pam_setenv(pamh, "PATH", _PATH_DEFPATH, 1);
508	environ = pam_getenvlist(pamh);
509	(void) pam_end(pamh, pam_err);
510	cp = strrchr(pwd->pw_shell, '/');
511	if (cp)
512		cp++;
513	else
514		cp = pwd->pw_shell;
515
516	if (setusercontext(lc, pwd, pwd->pw_uid,
517		LOGIN_SETALL & ~LOGIN_SETGROUP) < 0) {
518		syslog(LOG_ERR, "setusercontext(): %m");
519		exit(1);
520	}
521	login_close(lc);
522	endpwent();
523	if (log_success || pwd->pw_uid == 0) {
524		    syslog(LOG_INFO|LOG_AUTH, "%s@%s as %s: cmd='%.80s'",
525			ruser, rhost, luser, cmdbuf);
526	}
527	execl(pwd->pw_shell, cp, "-c", cmdbuf, (char *)NULL);
528	err(1, "%s", pwd->pw_shell);
529	exit(1);
530}
531
532/*
533 * Report error to client.  Note: can't be used until second socket has
534 * connected to client, or older clients will hang waiting for that
535 * connection first.
536 */
537
538static void
539rshd_errx(int errcode, const char *fmt, ...)
540{
541	va_list ap;
542
543	va_start(ap, fmt);
544
545	if (sent_null == 0)
546		write(STDERR_FILENO, "\1", 1);
547
548	verrx(errcode, fmt, ap);
549	/* NOTREACHED */
550}
551
552void
553getstr(char *buf, int cnt, const char *error)
554{
555	char c;
556
557	do {
558		if (read(STDIN_FILENO, &c, 1) != 1)
559			exit(1);
560		*buf++ = c;
561		if (--cnt == 0) {
562#ifdef USE_BLACKLIST
563			blacklist(1, STDIN_FILENO, "buffer overflow");
564#endif
565			rshd_errx(1, "%s too long", error);
566		}
567	} while (c != 0);
568}
569
570/*
571 * Check whether host h is in our local domain,
572 * defined as sharing the last two components of the domain part,
573 * or the entire domain part if the local domain has only one component.
574 * If either name is unqualified (contains no '.'),
575 * assume that the host is local, as it will be
576 * interpreted as such.
577 */
578int
579local_domain(char *h)
580{
581	char localhost[MAXHOSTNAMELEN];
582	char *p1, *p2;
583
584	localhost[0] = 0;
585	(void) gethostname(localhost, sizeof(localhost) - 1);
586	localhost[sizeof(localhost) - 1] = '\0';
587	/* XXX truncation! */
588	p1 = topdomain(localhost);
589	p2 = topdomain(h);
590	if (p1 == NULL || p2 == NULL || !strcasecmp(p1, p2))
591		return (1);
592	return (0);
593}
594
595char *
596topdomain(char *h)
597{
598	char *p, *maybe = NULL;
599	int dots = 0;
600
601	for (p = h + strlen(h); p >= h; p--) {
602		if (*p == '.') {
603			if (++dots == 2)
604				return (p);
605			maybe = p;
606		}
607	}
608	return (maybe);
609}
610
611void
612usage(void)
613{
614
615	syslog(LOG_ERR, "usage: rshd [-%s]", OPTIONS);
616	exit(2);
617}
618