Home | History | Annotate | Line # | Download | only in rshd
rshd.c revision 1.41
      1 /*	$NetBSD: rshd.c,v 1.41 2005/03/27 21:00:58 christos Exp $	*/
      2 
      3 /*
      4  * Copyright (C) 1998 WIDE Project.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *    This product includes software developed by WIDE Project and
     18  *    its contributors.
     19  * 4. Neither the name of the project nor the names of its contributors
     20  *    may be used to endorse or promote products derived from this software
     21  *    without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33  * SUCH DAMAGE.
     34  */
     35 
     36 /*-
     37  * Copyright (c) 1988, 1989, 1992, 1993, 1994
     38  *	The Regents of the University of California.  All rights reserved.
     39  *
     40  * Redistribution and use in source and binary forms, with or without
     41  * modification, are permitted provided that the following conditions
     42  * are met:
     43  * 1. Redistributions of source code must retain the above copyright
     44  *    notice, this list of conditions and the following disclaimer.
     45  * 2. Redistributions in binary form must reproduce the above copyright
     46  *    notice, this list of conditions and the following disclaimer in the
     47  *    documentation and/or other materials provided with the distribution.
     48  * 3. Neither the name of the University nor the names of its contributors
     49  *    may be used to endorse or promote products derived from this software
     50  *    without specific prior written permission.
     51  *
     52  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     53  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     54  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     55  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     56  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     57  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     58  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     59  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     60  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     61  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     62  * SUCH DAMAGE.
     63  */
     64 
     65 #include <sys/cdefs.h>
     66 #ifndef lint
     67 __COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1992, 1993, 1994\n\
     68 	The Regents of the University of California.  All rights reserved.\n");
     69 #if 0
     70 static char sccsid[] = "@(#)rshd.c	8.2 (Berkeley) 4/6/94";
     71 #else
     72 __RCSID("$NetBSD: rshd.c,v 1.41 2005/03/27 21:00:58 christos Exp $");
     73 #endif
     74 #endif /* not lint */
     75 
     76 /*
     77  * remote shell server:
     78  *	[port]\0
     79  *	remuser\0
     80  *	locuser\0
     81  *	command\0
     82  *	data
     83  */
     84 #include <sys/param.h>
     85 #include <sys/ioctl.h>
     86 #include <sys/time.h>
     87 #include <sys/socket.h>
     88 
     89 #include <netinet/in_systm.h>
     90 #include <netinet/in.h>
     91 #include <netinet/ip.h>
     92 #include <netinet/tcp.h>
     93 #include <arpa/inet.h>
     94 #include <netdb.h>
     95 
     96 #include <errno.h>
     97 #include <fcntl.h>
     98 #include <paths.h>
     99 #include <pwd.h>
    100 #include <signal.h>
    101 #include <stdio.h>
    102 #include <stdlib.h>
    103 #include <string.h>
    104 #include <syslog.h>
    105 #include <unistd.h>
    106 #include <poll.h>
    107 #ifdef  LOGIN_CAP
    108 #include <login_cap.h>
    109 #endif
    110 
    111 #ifdef USE_PAM
    112 #include <security/pam_appl.h>
    113 #include <security/openpam.h>
    114 #include <sys/wait.h>
    115 
    116 static struct pam_conv pamc = { openpam_nullconv, NULL };
    117 static pam_handle_t *pamh;
    118 static int pam_err;
    119 
    120 #define PAM_END do { \
    121 	if ((pam_err = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS) \
    122 		syslog(LOG_ERR|LOG_AUTH, "pam_setcred(): %s", \
    123 		    pam_strerror(pamh, pam_err)); \
    124 	if ((pam_err = pam_close_session(pamh,0)) != PAM_SUCCESS) \
    125 		syslog(LOG_ERR|LOG_AUTH, "pam_close_session(): %s", \
    126 		    pam_strerror(pamh, pam_err)); \
    127 	if ((pam_err = pam_end(pamh, pam_err)) != PAM_SUCCESS) \
    128 		syslog(LOG_ERR|LOG_AUTH, "pam_end(): %s", \
    129 		    pam_strerror(pamh, pam_err)); \
    130 } while (/*CONSTCOND*/0)
    131 #else
    132 #define PAM_END
    133 #endif
    134 
    135 int	keepalive = 1;
    136 int	check_all;
    137 int	log_success;		/* If TRUE, log all successful accesses */
    138 int	sent_null;
    139 
    140 void	 doit(struct sockaddr *) __attribute__((__noreturn__));
    141 void	 rshd_errx(int, const char *, ...)
    142      __attribute__((__noreturn__, __format__(__printf__, 2, 3)));
    143 void	 getstr(char *, int, const char *);
    144 int	 local_domain(char *);
    145 char	*topdomain(char *);
    146 void	 usage(void);
    147 int	 main(int, char *[]);
    148 
    149 #define	OPTIONS	"aLln"
    150 extern int __check_rhosts_file;
    151 extern char *__rcmd_errstr;	/* syslog hook from libc/net/rcmd.c. */
    152 static const char incorrect[] = "Login incorrect.";
    153 
    154 int
    155 main(int argc, char *argv[])
    156 {
    157 	struct linger linger;
    158 	int ch, on = 1, fromlen;
    159 	struct sockaddr_storage from;
    160 	struct protoent *proto;
    161 
    162 	openlog("rshd", LOG_PID, LOG_DAEMON);
    163 
    164 	opterr = 0;
    165 	while ((ch = getopt(argc, argv, OPTIONS)) != -1)
    166 		switch (ch) {
    167 		case 'a':
    168 			check_all = 1;
    169 			break;
    170 		case 'l':
    171 			__check_rhosts_file = 0;
    172 			break;
    173 		case 'n':
    174 			keepalive = 0;
    175 			break;
    176 		case 'L':
    177 			log_success = 1;
    178 			break;
    179 		case '?':
    180 		default:
    181 			usage();
    182 			break;
    183 		}
    184 
    185 	argc -= optind;
    186 	argv += optind;
    187 
    188 	fromlen = sizeof(from); /* xxx */
    189 	if (getpeername(STDIN_FILENO, (struct sockaddr *)&from, &fromlen) < 0) {
    190 		syslog(LOG_ERR, "getpeername: %m");
    191 		return EXIT_FAILURE;
    192 	}
    193 #if 0
    194 	if (((struct sockaddr *)&from)->sa_family == AF_INET6 &&
    195 	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&from)->sin6_addr) &&
    196 	    sizeof(struct sockaddr_in) <= sizeof(from)) {
    197 		struct sockaddr_in sin;
    198 		struct sockaddr_in6 *sin6;
    199 		const int off = sizeof(struct sockaddr_in6) -
    200 		    sizeof(struct sockaddr_in);
    201 
    202 		sin6 = (struct sockaddr_in6 *)&from;
    203 		(void)memset(&sin, 0, sizeof(sin));
    204 		sin.sin_family = AF_INET;
    205 		sin.sin_len = sizeof(struct sockaddr_in);
    206 		(void)memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[off],
    207 		    sizeof(sin.sin_addr));
    208 		(void)memcpy(&from, &sin, sizeof(sin));
    209 		fromlen = sin.sin_len;
    210 	}
    211 #else
    212 	if (((struct sockaddr *)&from)->sa_family == AF_INET6 &&
    213 	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&from)->sin6_addr)) {
    214 		char hbuf[NI_MAXHOST];
    215 		if (getnameinfo((struct sockaddr *)&from, fromlen, hbuf,
    216 				sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0) {
    217 			strlcpy(hbuf, "invalid", sizeof(hbuf));
    218 		}
    219 		syslog(LOG_ERR, "malformed \"from\" address (v4 mapped, %s)",
    220 		    hbuf);
    221 		return EXIT_FAILURE;
    222 	}
    223 #endif
    224 	if (keepalive &&
    225 	    setsockopt(STDIN_FILENO, SOL_SOCKET, SO_KEEPALIVE, (char *)&on,
    226 	    sizeof(on)) < 0)
    227 		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
    228 	linger.l_onoff = 1;
    229 	linger.l_linger = 60;			/* XXX */
    230 	if (setsockopt(STDIN_FILENO, SOL_SOCKET, SO_LINGER, (char *)&linger,
    231 	    sizeof (linger)) < 0)
    232 		syslog(LOG_WARNING, "setsockopt (SO_LINGER): %m");
    233 	proto = getprotobyname("tcp");
    234 	(void)setsockopt(STDIN_FILENO, proto->p_proto, TCP_NODELAY, &on,
    235 	    sizeof(on));
    236 	doit((struct sockaddr *)&from);
    237 }
    238 
    239 char	username[20] = "USER=";
    240 char	homedir[64] = "HOME=";
    241 char	shell[64] = "SHELL=";
    242 char	path[100] = "PATH=";
    243 char	*envinit[] =
    244 	    {homedir, shell, path, username, 0};
    245 char	**environ;
    246 
    247 void
    248 doit(struct sockaddr *fromp)
    249 {
    250 	struct passwd *pwd;
    251 	in_port_t port;
    252 	struct pollfd set[2];
    253 	int cc, pv[2], pid, s = -1;	/* XXX gcc */
    254 	int one = 1;
    255 	char *hostname, *errorhost = NULL;	/* XXX gcc */
    256 	const char *cp;
    257 	char sig, buf[BUFSIZ];
    258 	char cmdbuf[NCARGS+1], locuser[16], remuser[16];
    259 	char remotehost[2 * MAXHOSTNAMELEN + 1];
    260 	char hostnamebuf[2 * MAXHOSTNAMELEN + 1];
    261 #ifdef  LOGIN_CAP
    262 	login_cap_t *lc;
    263 #endif
    264 	char naddr[NI_MAXHOST];
    265 	char saddr[NI_MAXHOST];
    266 	char raddr[NI_MAXHOST];
    267 	char pbuf[NI_MAXSERV];
    268 	int af = fromp->sa_family;
    269 	u_int16_t *portp;
    270 	struct addrinfo hints, *res, *res0;
    271 	int gaierror;
    272 	const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
    273 	const char *errormsg = NULL, *errorstr = NULL;
    274 
    275 	(void)signal(SIGINT, SIG_DFL);
    276 	(void)signal(SIGQUIT, SIG_DFL);
    277 	(void)signal(SIGTERM, SIG_DFL);
    278 #ifdef DEBUG
    279 	{
    280 		int t = open(_PATH_TTY, O_RDWR);
    281 		if (t >= 0) {
    282 			ioctl(t, TIOCNOTTY, NULL);
    283 			(void)close(t);
    284 		}
    285 	}
    286 #endif
    287 	switch (af) {
    288 	case AF_INET:
    289 		portp = &((struct sockaddr_in *)fromp)->sin_port;
    290 		break;
    291 #ifdef INET6
    292 	case AF_INET6:
    293 		portp = &((struct sockaddr_in6 *)fromp)->sin6_port;
    294 		break;
    295 #endif
    296 	default:
    297 		syslog(LOG_ERR, "malformed \"from\" address (af %d)", af);
    298 		exit(EXIT_FAILURE);
    299 	}
    300 	if (getnameinfo(fromp, fromp->sa_len, naddr, sizeof(naddr),
    301 			pbuf, sizeof(pbuf), niflags) != 0) {
    302 		syslog(LOG_ERR, "malformed \"from\" address (af %d)", af);
    303 		exit(EXIT_FAILURE);
    304 	}
    305 #ifdef IP_OPTIONS
    306 	if (af == AF_INET) {
    307 
    308 	u_char optbuf[BUFSIZ/3];
    309 	int optsize = sizeof(optbuf), ipproto, i;
    310 	struct protoent *ip;
    311 
    312 	if ((ip = getprotobyname("ip")) != NULL)
    313 		ipproto = ip->p_proto;
    314 	else
    315 		ipproto = IPPROTO_IP;
    316 	if (!getsockopt(0, ipproto, IP_OPTIONS, (char *)optbuf, &optsize) &&
    317 	    optsize != 0) {
    318 	    	for (i = 0; i < optsize;) {
    319 			u_char c = optbuf[i];
    320 			if (c == IPOPT_LSRR || c == IPOPT_SSRR) {
    321 				syslog(LOG_NOTICE,
    322 				    "Connection refused from %s "
    323 				    "with IP option %s",
    324 				    inet_ntoa((
    325 				    (struct sockaddr_in *)fromp)->sin_addr),
    326 				    c == IPOPT_LSRR ? "LSRR" : "SSRR");
    327 				exit(EXIT_FAILURE);
    328 			}
    329 			if (c == IPOPT_EOL)
    330 				break;
    331 			i += (c == IPOPT_NOP) ? 1 : optbuf[i + 1];
    332 		}
    333 	}
    334 	}
    335 #endif
    336 	if (ntohs(*portp) >= IPPORT_RESERVED
    337 	    || ntohs(*portp) < IPPORT_RESERVED / 2) {
    338 		syslog(LOG_NOTICE|LOG_AUTH,
    339 		    "Connection from %s on illegal port %u",
    340 		    naddr, ntohs(*portp));
    341 		exit(EXIT_FAILURE);
    342 	}
    343 
    344 	(void) alarm(60);
    345 	port = 0;
    346 	for (;;) {
    347 		char c;
    348 
    349 		if ((cc = read(STDIN_FILENO, &c, 1)) != 1) {
    350 			if (cc < 0)
    351 				syslog(LOG_ERR, "read: %m");
    352 			(void)shutdown(0, SHUT_RDWR);
    353 			exit(EXIT_FAILURE);
    354 		}
    355 		if (c == 0)
    356 			break;
    357 		port = port * 10 + c - '0';
    358 	}
    359 
    360 	(void) alarm(0);
    361 	if (port != 0) {
    362 		int lport = IPPORT_RESERVED - 1;
    363 		s = rresvport_af(&lport, af);
    364 		if (s < 0) {
    365 			syslog(LOG_ERR, "can't get stderr port: %m");
    366 			exit(EXIT_FAILURE);
    367 		}
    368 		if (port >= IPPORT_RESERVED) {
    369 			syslog(LOG_ERR, "2nd port not reserved");
    370 			exit(EXIT_FAILURE);
    371 		}
    372 		*portp = htons(port);
    373 		if (connect(s, fromp, fromp->sa_len) < 0) {
    374 			syslog(LOG_ERR, "connect second port %d: %m", port);
    375 			exit(EXIT_FAILURE);
    376 		}
    377 	}
    378 
    379 
    380 #ifdef notdef
    381 	/* from inetd, socket is already on 0, 1, 2 */
    382 	(void)dup2(f, STDIN_FILENO);
    383 	(void)dup2(f, STDOUT_FILENO);
    384 	(void)dup2(f, STDERR_FILENO);
    385 #endif
    386 	if (getnameinfo(fromp, fromp->sa_len, saddr, sizeof(saddr),
    387 			NULL, 0, NI_NAMEREQD) == 0) {
    388 		/*
    389 		 * If name returned by getnameinfo is in our domain,
    390 		 * attempt to verify that we haven't been fooled by someone
    391 		 * in a remote net; look up the name and check that this
    392 		 * address corresponds to the name.
    393 		 */
    394 		hostname = saddr;
    395 		res0 = NULL;
    396 		if (check_all || local_domain(saddr)) {
    397 			(void)strlcpy(remotehost, saddr, sizeof(remotehost));
    398 			errorhost = remotehost;
    399 			(void)memset(&hints, 0, sizeof(hints));
    400 			hints.ai_family = fromp->sa_family;
    401 			hints.ai_socktype = SOCK_STREAM;
    402 			hints.ai_flags = AI_CANONNAME;
    403 			gaierror = getaddrinfo(remotehost, pbuf, &hints, &res0);
    404 			if (gaierror) {
    405 				syslog(LOG_NOTICE,
    406 				    "Couldn't look up address for %s: %s",
    407 				    remotehost, gai_strerror(gaierror));
    408 				errorstr =
    409 				"Couldn't look up address for your host (%s)\n";
    410 				hostname = naddr;
    411 			} else {
    412 				for (res = res0; res; res = res->ai_next) {
    413 					if (res->ai_family != fromp->sa_family)
    414 						continue;
    415 					if (res->ai_addrlen != fromp->sa_len)
    416 						continue;
    417 					if (getnameinfo(res->ai_addr,
    418 						res->ai_addrlen,
    419 						raddr, sizeof(raddr), NULL, 0,
    420 						niflags) == 0
    421 					 && strcmp(naddr, raddr) == 0) {
    422 						hostname = res->ai_canonname
    423 							? res->ai_canonname
    424 							: saddr;
    425 						break;
    426 					}
    427 				}
    428 				if (res == NULL) {
    429 					syslog(LOG_NOTICE,
    430 					  "Host addr %s not listed for host %s",
    431 					    naddr, res0->ai_canonname
    432 						    ? res0->ai_canonname
    433 						    : saddr);
    434 					errorstr =
    435 					    "Host address mismatch for %s\n";
    436 					hostname = naddr;
    437 				}
    438 			}
    439 		}
    440 		(void)strlcpy(hostnamebuf, hostname, sizeof(hostnamebuf));
    441 		hostname = hostnamebuf;
    442 		if (res0)
    443 			freeaddrinfo(res0);
    444 	} else {
    445 		(void)strlcpy(hostnamebuf, naddr, sizeof(hostnamebuf));
    446 		errorhost = hostname = hostnamebuf;
    447 	}
    448 
    449 	(void)alarm(60);
    450 	getstr(remuser, sizeof(remuser), "remuser");
    451 	getstr(locuser, sizeof(locuser), "locuser");
    452 	getstr(cmdbuf, sizeof(cmdbuf), "command");
    453 	(void)alarm(0);
    454 
    455 #ifdef USE_PAM
    456 	pam_err = pam_start("rsh", locuser, &pamc, &pamh);
    457 	if (pam_err != PAM_SUCCESS) {
    458 		syslog(LOG_ERR|LOG_AUTH, "pam_start(): %s",
    459 		    pam_strerror(pamh, pam_err));
    460 		rshd_errx(EXIT_FAILURE, incorrect);
    461 	}
    462 
    463 	if ((pam_err = pam_set_item(pamh, PAM_RUSER, remuser)) != PAM_SUCCESS ||
    464 	    (pam_err = pam_set_item(pamh, PAM_RHOST, hostname) != PAM_SUCCESS)){
    465 		syslog(LOG_ERR|LOG_AUTH, "pam_set_item(): %s",
    466 		    pam_strerror(pamh, pam_err));
    467 		rshd_errx(EXIT_FAILURE, incorrect);
    468 	}
    469 
    470 	pam_err = pam_authenticate(pamh, 0);
    471 	if (pam_err == PAM_SUCCESS) {
    472 		if ((pam_err = pam_get_user(pamh, &cp, NULL)) == PAM_SUCCESS) {
    473 			(void)strlcpy(locuser, cp, sizeof(locuser));
    474 			/* XXX truncation! */
    475  		}
    476 		pam_err = pam_acct_mgmt(pamh, 0);
    477 	}
    478 	if (pam_err != PAM_SUCCESS) {
    479 		errorstr = incorrect;
    480 		errormsg = pam_strerror(pamh, pam_err);
    481 		goto badlogin;
    482  	}
    483 #endif /* USE_PAM */
    484 	setpwent();
    485 	pwd = getpwnam(locuser);
    486 	if (pwd == NULL) {
    487 		syslog(LOG_INFO|LOG_AUTH,
    488 		    "%s@%s as %s: unknown login. cmd='%.80s'",
    489 		    remuser, hostname, locuser, cmdbuf);
    490 		if (errorstr == NULL)
    491 			errorstr = "Permission denied.";
    492 		rshd_errx(EXIT_FAILURE, errorstr, errorhost);
    493 	}
    494 #ifdef LOGIN_CAP
    495 	lc = login_getclass(pwd ? pwd->pw_class : NULL);
    496 #endif
    497 
    498 	if (chdir(pwd->pw_dir) < 0) {
    499 		if (chdir("/") < 0
    500 #ifdef LOGIN_CAP
    501 		    || login_getcapbool(lc, "requirehome", pwd->pw_uid ? 1 : 0)
    502 #endif
    503 		) {
    504 			syslog(LOG_INFO|LOG_AUTH,
    505 			    "%s@%s as %s: no home directory. cmd='%.80s'",
    506 			    remuser, hostname, locuser, cmdbuf);
    507 			rshd_errx(EXIT_SUCCESS, "No remote home directory.");
    508 		}
    509 	}
    510 
    511 #ifndef USE_PAM
    512 	if (errorstr ||
    513 	    (pwd->pw_passwd != 0 && *pwd->pw_passwd != '\0' &&
    514 		iruserok_sa(fromp, fromp->sa_len, pwd->pw_uid == 0, remuser,
    515 			locuser) < 0)) {
    516 		errormsg = __rcmd_errstr ? __rcmd_errstr : "unknown error";
    517 		if (errorstr == NULL)
    518 			errorstr = "Permission denied.";
    519 		goto badlogin;
    520 	}
    521 
    522 	if (pwd->pw_uid && !access(_PATH_NOLOGIN, F_OK))
    523 		rshd_errx(EXIT_FAILURE, "Logins currently disabled.");
    524 #endif
    525 
    526 #ifdef LOGIN_CAP
    527 	/*
    528 	 * PAM modules might add supplementary groups in
    529 	 * pam_setcred(), so initialize them first.
    530 	 * But we need to open the session as root.
    531 	 */
    532 	if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) != 0) {
    533 		syslog(LOG_ERR, "setusercontext: %m");
    534 		exit(EXIT_FAILURE);
    535 	}
    536 #else
    537 	initgroups(pwd->pw_name, pwd->pw_gid);
    538 #endif
    539 
    540 #ifdef USE_PAM
    541 	if ((pam_err = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
    542 		syslog(LOG_ERR, "pam_open_session: %s",
    543 		    pam_strerror(pamh, pam_err));
    544 	} else if ((pam_err = pam_setcred(pamh, PAM_ESTABLISH_CRED))
    545 	    != PAM_SUCCESS) {
    546 		syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, pam_err));
    547 	}
    548 #endif
    549 
    550 	(void)write(STDERR_FILENO, "\0", 1);
    551 	sent_null = 1;
    552 
    553 	if (port) {
    554 		if (pipe(pv) < 0)
    555 			rshd_errx(EXIT_FAILURE, "Can't make pipe. (%s)",
    556 			    strerror(errno));
    557 		pid = fork();
    558 		if (pid == -1)
    559 			rshd_errx(EXIT_FAILURE, "Can't fork. (%s)",
    560 			    strerror(errno));
    561 		if (pid) {
    562 			(void)close(STDIN_FILENO);
    563 			(void)close(STDOUT_FILENO);
    564 			(void)close(STDERR_FILENO);
    565 			(void)close(pv[1]);
    566 
    567 			set[0].fd = s;
    568 			set[0].events = POLLIN;
    569 			set[1].fd = pv[0];
    570 			set[1].events = POLLIN;
    571 			ioctl(pv[0], FIONBIO, (char *)&one);
    572 
    573 			/* should set s nbio! */
    574 			do {
    575 				if (poll(set, 2, INFTIM) < 0)
    576 					break;
    577 				if (set[0].revents & POLLIN) {
    578 					int	ret;
    579 
    580 					ret = read(s, &sig, 1);
    581 					if (ret <= 0)
    582 						set[0].events = 0;
    583 					else
    584 						killpg(pid, sig);
    585 				}
    586 				if (set[1].revents & POLLIN) {
    587 					errno = 0;
    588 					cc = read(pv[0], buf, sizeof(buf));
    589 					if (cc <= 0) {
    590 						shutdown(s, SHUT_RDWR);
    591 						set[1].events = 0;
    592 					} else {
    593 						(void)write(s, buf, cc);
    594 					}
    595 				}
    596 
    597 			} while ((set[0].revents | set[1].revents) & POLLIN);
    598 			PAM_END;
    599 			exit(EXIT_SUCCESS);
    600 		}
    601 		(void)close(s);
    602 		(void)close(pv[0]);
    603 		(void)dup2(pv[1], STDERR_FILENO);
    604 		close(pv[1]);
    605 	}
    606 #ifdef USE_PAM
    607 	else {
    608 		pid = fork();
    609 		if (pid == -1)
    610 			rshd_errx(EXIT_FAILURE, "Can't fork. (%s)",
    611 			    strerror(errno));
    612 		if (pid) {
    613 			pid_t xpid;
    614 			int status;
    615 			if ((xpid = waitpid(pid, &status, 0)) != pid) {
    616 				pam_err = pam_close_session(pamh, 0);
    617 				if (pam_err != PAM_SUCCESS) {
    618 					syslog(LOG_ERR,
    619 					    "pam_close_session: %s",
    620 					    pam_strerror(pamh, pam_err));
    621 				}
    622 				PAM_END;
    623 				if (xpid != -1)
    624 					syslog(LOG_WARNING,
    625 					    "wrong PID: %d != %d", pid, xpid);
    626 				else
    627 					syslog(LOG_WARNING,
    628 					    "wait pid=%d failed %m", pid);
    629 				exit(EXIT_FAILURE);
    630 			}
    631 			exit(EXIT_SUCCESS);
    632 		}
    633 	}
    634 #endif
    635 
    636 #ifdef F_CLOSEM
    637 	(void)fcntl(STDERR_FILENO + 1, F_CLOSEM, 0);
    638 #else
    639 	for (fd = getdtablesize(); fd > STDERR_FILENO; fd--)
    640 		(void)close(fd);
    641 #endif
    642 	if (setsid() == -1)
    643 		syslog(LOG_ERR, "setsid() failed: %m");
    644 #ifdef USE_PAM
    645 	if (setlogin(pwd->pw_name) < 0)
    646 		syslog(LOG_ERR, "setlogin() failed: %m");
    647 
    648 	if (*pwd->pw_shell == '\0')
    649 		pwd->pw_shell = __UNCONST(_PATH_BSHELL);
    650 
    651 	(void)pam_setenv(pamh, "HOME", pwd->pw_dir, 1);
    652 	(void)pam_setenv(pamh, "SHELL", pwd->pw_shell, 1);
    653 	(void)pam_setenv(pamh, "USER", pwd->pw_name, 1);
    654 	(void)pam_setenv(pamh, "PATH", _PATH_DEFPATH, 1);
    655 	environ = pam_getenvlist(pamh);
    656 	(void)pam_end(pamh, pam_err);
    657 #else
    658 #ifdef LOGIN_CAP
    659 	{
    660 		char *sh;
    661 		if ((sh = login_getcapstr(lc, "shell", NULL, NULL))) {
    662 			if(!(sh = strdup(sh))) {
    663 				syslog(LOG_ERR, "Cannot alloc mem");
    664 				exit(EXIT_FAILURE);
    665 			}
    666 			pwd->pw_shell = sh;
    667 		}
    668 	}
    669 #endif
    670 	environ = envinit;
    671 	(void)strlcat(homedir, pwd->pw_dir, sizeof(homedir));
    672 	(void)strlcat(path, _PATH_DEFPATH, sizeof(path));
    673 	(void)strlcat(shell, pwd->pw_shell, sizeof(shell));
    674 	(void)strlcat(username, pwd->pw_name, sizeof(username));
    675 #endif
    676 
    677 	cp = strrchr(pwd->pw_shell, '/');
    678 	if (cp)
    679 		cp++;
    680 	else
    681 		cp = pwd->pw_shell;
    682 
    683 #ifdef LOGIN_CAP
    684 	if (setusercontext(lc, pwd, pwd->pw_uid,
    685 		LOGIN_SETALL & ~LOGIN_SETGROUP) < 0) {
    686 		syslog(LOG_ERR, "setusercontext(): %m");
    687 		exit(EXIT_FAILURE);
    688 	}
    689 	login_close(lc);
    690 #else
    691 	(void)setgid((gid_t)pwd->pw_gid);
    692 	(void)setuid((uid_t)pwd->pw_uid);
    693 #endif
    694 	endpwent();
    695 	if (log_success || pwd->pw_uid == 0) {
    696 		syslog(LOG_INFO|LOG_AUTH, "%s@%s as %s: cmd='%.80s'",
    697 		    remuser, hostname, locuser, cmdbuf);
    698 	}
    699 	(void)execl(pwd->pw_shell, cp, "-c", cmdbuf, NULL);
    700 	rshd_errx(EXIT_FAILURE, "%s: %s", pwd->pw_shell, strerror(errno));
    701 badlogin:
    702 	syslog(LOG_INFO|LOG_AUTH,
    703 	    "%s@%s as %s: permission denied (%s). cmd='%.80s'",
    704 	    remuser, hostname, locuser, errormsg, cmdbuf);
    705 	rshd_errx(EXIT_FAILURE, errorstr, errorhost);
    706 }
    707 
    708 /*
    709  * Report error to client.  Note: can't be used until second socket has
    710  * connected to client, or older clients will hang waiting for that
    711  * connection first.
    712  */
    713 
    714 #include <stdarg.h>
    715 
    716 void
    717 rshd_errx(int error, const char *fmt, ...)
    718 {
    719 	va_list ap;
    720 	int len, rv;
    721 	char *bp, buf[BUFSIZ];
    722 	va_start(ap, fmt);
    723 	bp = buf;
    724 	if (sent_null == 0) {
    725 		*bp++ = 1;
    726 		len = 1;
    727 	} else
    728 		len = 0;
    729 	rv = vsnprintf(bp, sizeof(buf) - 2, fmt, ap);
    730 	bp[rv++] = '\n';
    731 	(void)write(STDERR_FILENO, buf, len + rv);
    732 	va_end(ap);
    733 	exit(error);
    734 }
    735 
    736 void
    737 getstr(char *buf, int cnt, const char *err)
    738 {
    739 	char c;
    740 
    741 	do {
    742 		if (read(STDIN_FILENO, &c, 1) != 1)
    743 			exit(EXIT_FAILURE);
    744 		*buf++ = c;
    745 		if (--cnt == 0)
    746 			rshd_errx(EXIT_FAILURE, "%s too long", err);
    747 	} while (c != 0);
    748 }
    749 
    750 /*
    751  * Check whether host h is in our local domain,
    752  * defined as sharing the last two components of the domain part,
    753  * or the entire domain part if the local domain has only one component.
    754  * If either name is unqualified (contains no '.'),
    755  * assume that the host is local, as it will be
    756  * interpreted as such.
    757  */
    758 int
    759 local_domain(char *h)
    760 {
    761 	char localhost[MAXHOSTNAMELEN + 1];
    762 	char *p1, *p2;
    763 
    764 	localhost[0] = 0;
    765 	(void)gethostname(localhost, sizeof(localhost));
    766 	localhost[sizeof(localhost) - 1] = '\0';
    767 	p1 = topdomain(localhost);
    768 	p2 = topdomain(h);
    769 	if (p1 == NULL || p2 == NULL || !strcasecmp(p1, p2))
    770 		return (1);
    771 	return (0);
    772 }
    773 
    774 char *
    775 topdomain(char *h)
    776 {
    777 	char *p, *maybe = NULL;
    778 	int dots = 0;
    779 
    780 	for (p = h + strlen(h); p >= h; p--) {
    781 		if (*p == '.') {
    782 			if (++dots == 2)
    783 				return (p);
    784 			maybe = p;
    785 		}
    786 	}
    787 	return (maybe);
    788 }
    789 
    790 void
    791 usage(void)
    792 {
    793 
    794 	syslog(LOG_ERR, "Usage: %s [-%s]", getprogname(), OPTIONS);
    795 	exit(EXIT_FAILURE);
    796 }
    797