Home | History | Annotate | Line # | Download | only in rshd
rshd.c revision 1.50
      1 /*	$NetBSD: rshd.c,v 1.50 2012/07/14 15:06:26 darrenr 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\
     68  The Regents of the University of California.  All rights reserved.");
     69 #if 0
     70 static char sccsid[] = "@(#)rshd.c	8.2 (Berkeley) 4/6/94";
     71 #else
     72 __RCSID("$NetBSD: rshd.c,v 1.50 2012/07/14 15:06:26 darrenr 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 static int	keepalive = 1;
    136 static int	check_all;
    137 static int	log_success;		/* If TRUE, log all successful accesses */
    138 static int	sent_null;
    139 
    140 __dead static void	 doit(struct sockaddr *, struct sockaddr *);
    141 __dead static void	 rshd_errx(int, const char *, ...) __printflike(2, 3);
    142 static void	 getstr(char *, int, const char *);
    143 static int	 local_domain(char *);
    144 static char	*topdomain(char *);
    145 __dead static void	 usage(void);
    146 
    147 #define	OPTIONS	"aLln"
    148 extern int __check_rhosts_file;
    149 extern char *__rcmd_errstr;	/* syslog hook from libc/net/rcmd.c. */
    150 static const char incorrect[] = "Login incorrect.";
    151 
    152 int
    153 main(int argc, char *argv[])
    154 {
    155 	struct linger linger;
    156 	int ch, on = 1;
    157 	socklen_t fromlen;
    158 	socklen_t locallen;
    159 	struct sockaddr_storage from;
    160 	struct sockaddr_storage local;
    161 	struct protoent *proto;
    162 
    163 	openlog("rshd", LOG_PID, LOG_DAEMON);
    164 
    165 	opterr = 0;
    166 	while ((ch = getopt(argc, argv, OPTIONS)) != -1)
    167 		switch (ch) {
    168 		case 'a':
    169 			check_all = 1;
    170 			break;
    171 		case 'l':
    172 			__check_rhosts_file = 0;
    173 			break;
    174 		case 'n':
    175 			keepalive = 0;
    176 			break;
    177 		case 'L':
    178 			log_success = 1;
    179 			break;
    180 		case '?':
    181 		default:
    182 			usage();
    183 			break;
    184 		}
    185 
    186 	argc -= optind;
    187 	argv += optind;
    188 
    189 	fromlen = sizeof(from); /* xxx */
    190 	locallen = sizeof(local); /* xxx */
    191 	if (getpeername(STDIN_FILENO, (struct sockaddr *)&from, &fromlen) < 0) {
    192 		syslog(LOG_ERR, "getpeername: %m");
    193 		return EXIT_FAILURE;
    194 	}
    195 	if (getsockname(STDIN_FILENO, (struct sockaddr *)&local,
    196 	    &locallen) < 0) {
    197 		syslog(LOG_ERR, "getsockname: %m");
    198 		return EXIT_FAILURE;
    199 	}
    200 #if 0
    201 	if (((struct sockaddr *)&from)->sa_family == AF_INET6 &&
    202 	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&from)->sin6_addr) &&
    203 	    sizeof(struct sockaddr_in) <= sizeof(from)) {
    204 		struct sockaddr_in sin;
    205 		struct sockaddr_in6 *sin6;
    206 		const int off = sizeof(struct sockaddr_in6) -
    207 		    sizeof(struct sockaddr_in);
    208 
    209 		sin6 = (struct sockaddr_in6 *)&from;
    210 		(void)memset(&sin, 0, sizeof(sin));
    211 		sin.sin_family = AF_INET;
    212 		sin.sin_len = sizeof(struct sockaddr_in);
    213 		(void)memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[off],
    214 		    sizeof(sin.sin_addr));
    215 		(void)memcpy(&from, &sin, sizeof(sin));
    216 		fromlen = sin.sin_len;
    217 	}
    218 #else
    219 	if (((struct sockaddr *)&from)->sa_family == AF_INET6 &&
    220 	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&from)->sin6_addr)) {
    221 		char hbuf[NI_MAXHOST];
    222 		if (getnameinfo((struct sockaddr *)&from, fromlen, hbuf,
    223 				sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0) {
    224 			strlcpy(hbuf, "invalid", sizeof(hbuf));
    225 		}
    226 		syslog(LOG_ERR, "malformed \"from\" address (v4 mapped, %s)",
    227 		    hbuf);
    228 		return EXIT_FAILURE;
    229 	}
    230 #endif
    231 	if (keepalive &&
    232 	    setsockopt(STDIN_FILENO, SOL_SOCKET, SO_KEEPALIVE, (char *)&on,
    233 	    sizeof(on)) < 0)
    234 		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
    235 	linger.l_onoff = 1;
    236 	linger.l_linger = 60;			/* XXX */
    237 	if (setsockopt(STDIN_FILENO, SOL_SOCKET, SO_LINGER, (char *)&linger,
    238 	    sizeof (linger)) < 0)
    239 		syslog(LOG_WARNING, "setsockopt (SO_LINGER): %m");
    240 	proto = getprotobyname("tcp");
    241 	(void)setsockopt(STDIN_FILENO, proto->p_proto, TCP_NODELAY, &on,
    242 	    sizeof(on));
    243 	doit((struct sockaddr *)&from, (struct sockaddr *)&local);
    244 }
    245 
    246 extern char	**environ;
    247 
    248 static void
    249 doit(struct sockaddr *fromp, struct sockaddr *localp)
    250 {
    251 	struct passwd *pwd, pwres;
    252 	in_port_t port;
    253 	struct pollfd set[2];
    254 	int cc, pv[2], pid, s = -1;	/* XXX gcc */
    255 	int one = 1;
    256 	char *hostname, *errorhost = NULL;	/* XXX gcc */
    257 	const char *cp;
    258 	char sig, buf[BUFSIZ];
    259 	char cmdbuf[NCARGS+1], locuser[16], remuser[16];
    260 	char remotehost[2 * MAXHOSTNAMELEN + 1];
    261 	char hostnamebuf[2 * MAXHOSTNAMELEN + 1];
    262 #ifdef  LOGIN_CAP
    263 	login_cap_t *lc;
    264 #endif
    265 	char naddr[NI_MAXHOST];
    266 	char saddr[NI_MAXHOST];
    267 	char raddr[NI_MAXHOST];
    268 	char pbuf[NI_MAXSERV];
    269 	int af = fromp->sa_family;
    270 	u_int16_t *portp;
    271 	struct addrinfo hints, *res, *res0;
    272 	int gaierror;
    273 	const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
    274 	const char *errormsg = NULL, *errorstr = NULL;
    275 	char pwbuf[1024];
    276 
    277 	(void)signal(SIGINT, SIG_DFL);
    278 	(void)signal(SIGQUIT, SIG_DFL);
    279 	(void)signal(SIGTERM, SIG_DFL);
    280 #ifdef DEBUG
    281 	{
    282 		int t = open(_PATH_TTY, O_RDWR);
    283 		if (t >= 0) {
    284 			ioctl(t, TIOCNOTTY, NULL);
    285 			(void)close(t);
    286 		}
    287 	}
    288 #endif
    289 	switch (af) {
    290 	case AF_INET:
    291 		portp = &((struct sockaddr_in *)fromp)->sin_port;
    292 		break;
    293 #ifdef INET6
    294 	case AF_INET6:
    295 		portp = &((struct sockaddr_in6 *)fromp)->sin6_port;
    296 		break;
    297 #endif
    298 	default:
    299 		syslog(LOG_ERR, "malformed \"from\" address (af %d)", af);
    300 		exit(EXIT_FAILURE);
    301 	}
    302 	if (getnameinfo(fromp, fromp->sa_len, naddr, sizeof(naddr),
    303 			pbuf, sizeof(pbuf), niflags) != 0) {
    304 		syslog(LOG_ERR, "malformed \"from\" address (af %d)", af);
    305 		exit(EXIT_FAILURE);
    306 	}
    307 #ifdef IP_OPTIONS
    308 	if (af == AF_INET) {
    309 
    310 	u_char optbuf[BUFSIZ/3];
    311 	socklen_t optsize = sizeof(optbuf);
    312 	int ipproto;
    313 	unsigned int i;
    314 	struct protoent *ip;
    315 
    316 	if ((ip = getprotobyname("ip")) != NULL)
    317 		ipproto = ip->p_proto;
    318 	else
    319 		ipproto = IPPROTO_IP;
    320 	if (!getsockopt(0, ipproto, IP_OPTIONS, (char *)optbuf, &optsize) &&
    321 	    optsize != 0) {
    322 	    	for (i = 0; i < optsize;) {
    323 			u_char c = optbuf[i];
    324 			if (c == IPOPT_LSRR || c == IPOPT_SSRR) {
    325 				syslog(LOG_NOTICE,
    326 				    "Connection refused from %s "
    327 				    "with IP option %s",
    328 				    inet_ntoa((
    329 				    (struct sockaddr_in *)fromp)->sin_addr),
    330 				    c == IPOPT_LSRR ? "LSRR" : "SSRR");
    331 				exit(EXIT_FAILURE);
    332 			}
    333 			if (c == IPOPT_EOL)
    334 				break;
    335 			i += (c == IPOPT_NOP) ? 1 : optbuf[i + 1];
    336 		}
    337 	}
    338 	}
    339 #endif
    340 	if (ntohs(*portp) >= IPPORT_RESERVED
    341 	    || ntohs(*portp) < IPPORT_RESERVED / 2) {
    342 		syslog(LOG_NOTICE|LOG_AUTH,
    343 		    "Connection from %s on illegal port %u",
    344 		    naddr, ntohs(*portp));
    345 		exit(EXIT_FAILURE);
    346 	}
    347 
    348 	(void) alarm(60);
    349 	port = 0;
    350 	for (;;) {
    351 		char c;
    352 
    353 		if ((cc = read(STDIN_FILENO, &c, 1)) != 1) {
    354 			if (cc < 0)
    355 				syslog(LOG_ERR, "read: %m");
    356 			(void)shutdown(0, SHUT_RDWR);
    357 			exit(EXIT_FAILURE);
    358 		}
    359 		if (c == 0)
    360 			break;
    361 		port = port * 10 + c - '0';
    362 	}
    363 
    364 	(void) alarm(0);
    365 	if (port != 0) {
    366 		int lport = IPPORT_RESERVED - 1;
    367 		s = rresvport_af_addr(&lport, af, localp);
    368 		if (s < 0) {
    369 			syslog(LOG_ERR, "can't get stderr port: %m");
    370 			exit(EXIT_FAILURE);
    371 		}
    372 		if (port >= IPPORT_RESERVED) {
    373 			syslog(LOG_ERR, "2nd port not reserved");
    374 			exit(EXIT_FAILURE);
    375 		}
    376 		*portp = htons(port);
    377 		if (connect(s, fromp, fromp->sa_len) < 0) {
    378 			syslog(LOG_ERR, "connect second port %d: %m", port);
    379 			exit(EXIT_FAILURE);
    380 		}
    381 	}
    382 
    383 
    384 #ifdef notdef
    385 	/* from inetd, socket is already on 0, 1, 2 */
    386 	(void)dup2(f, STDIN_FILENO);
    387 	(void)dup2(f, STDOUT_FILENO);
    388 	(void)dup2(f, STDERR_FILENO);
    389 #endif
    390 	if (getnameinfo(fromp, fromp->sa_len, saddr, sizeof(saddr),
    391 			NULL, 0, NI_NAMEREQD) == 0) {
    392 		/*
    393 		 * If name returned by getnameinfo is in our domain,
    394 		 * attempt to verify that we haven't been fooled by someone
    395 		 * in a remote net; look up the name and check that this
    396 		 * address corresponds to the name.
    397 		 */
    398 		hostname = saddr;
    399 		res0 = NULL;
    400 		if (check_all || local_domain(saddr)) {
    401 			(void)strlcpy(remotehost, saddr, sizeof(remotehost));
    402 			errorhost = remotehost;
    403 			(void)memset(&hints, 0, sizeof(hints));
    404 			hints.ai_family = fromp->sa_family;
    405 			hints.ai_socktype = SOCK_STREAM;
    406 			hints.ai_flags = AI_CANONNAME;
    407 			gaierror = getaddrinfo(remotehost, pbuf, &hints, &res0);
    408 			if (gaierror) {
    409 				syslog(LOG_NOTICE,
    410 				    "Couldn't look up address for %s: %s",
    411 				    remotehost, gai_strerror(gaierror));
    412 				errorstr =
    413 				"Couldn't look up address for your host (%s)\n";
    414 				hostname = naddr;
    415 			} else {
    416 				for (res = res0; res; res = res->ai_next) {
    417 					if (res->ai_family != fromp->sa_family)
    418 						continue;
    419 					if (res->ai_addrlen != fromp->sa_len)
    420 						continue;
    421 					if (getnameinfo(res->ai_addr,
    422 						res->ai_addrlen,
    423 						raddr, sizeof(raddr), NULL, 0,
    424 						niflags) == 0
    425 					 && strcmp(naddr, raddr) == 0) {
    426 						hostname = res->ai_canonname
    427 							? res->ai_canonname
    428 							: saddr;
    429 						break;
    430 					}
    431 				}
    432 				if (res == NULL) {
    433 					syslog(LOG_NOTICE,
    434 					  "Host addr %s not listed for host %s",
    435 					    naddr, res0->ai_canonname
    436 						    ? res0->ai_canonname
    437 						    : saddr);
    438 					errorstr =
    439 					    "Host address mismatch for %s\n";
    440 					hostname = naddr;
    441 				}
    442 			}
    443 		}
    444 		(void)strlcpy(hostnamebuf, hostname, sizeof(hostnamebuf));
    445 		hostname = hostnamebuf;
    446 		if (res0)
    447 			freeaddrinfo(res0);
    448 	} else {
    449 		(void)strlcpy(hostnamebuf, naddr, sizeof(hostnamebuf));
    450 		errorhost = hostname = hostnamebuf;
    451 	}
    452 
    453 	(void)alarm(60);
    454 	getstr(remuser, sizeof(remuser), "remuser");
    455 	getstr(locuser, sizeof(locuser), "locuser");
    456 	getstr(cmdbuf, sizeof(cmdbuf), "command");
    457 	(void)alarm(0);
    458 
    459 #ifdef USE_PAM
    460 	pam_err = pam_start("rsh", locuser, &pamc, &pamh);
    461 	if (pam_err != PAM_SUCCESS) {
    462 		syslog(LOG_ERR|LOG_AUTH, "pam_start(): %s",
    463 		    pam_strerror(pamh, pam_err));
    464 		rshd_errx(EXIT_FAILURE, incorrect);
    465 	}
    466 
    467 	if ((pam_err = pam_set_item(pamh, PAM_RUSER, remuser)) != PAM_SUCCESS ||
    468 	    (pam_err = pam_set_item(pamh, PAM_RHOST, hostname)) != PAM_SUCCESS){
    469 		syslog(LOG_ERR|LOG_AUTH, "pam_set_item(): %s",
    470 		    pam_strerror(pamh, pam_err));
    471 		rshd_errx(EXIT_FAILURE, incorrect);
    472 	}
    473 
    474 	pam_err = pam_authenticate(pamh, 0);
    475 	if (pam_err == PAM_SUCCESS) {
    476 		if ((pam_err = pam_get_user(pamh, &cp, NULL)) == PAM_SUCCESS) {
    477 			(void)strlcpy(locuser, cp, sizeof(locuser));
    478 			/* XXX truncation! */
    479  		}
    480 		pam_err = pam_acct_mgmt(pamh, 0);
    481 	}
    482 	if (pam_err != PAM_SUCCESS) {
    483 		errorstr = incorrect;
    484 		errormsg = pam_strerror(pamh, pam_err);
    485 		goto badlogin;
    486  	}
    487 #endif /* USE_PAM */
    488 	setpwent();
    489 	if (getpwnam_r(locuser, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0 ||
    490 	    pwd == NULL) {
    491 		syslog(LOG_INFO|LOG_AUTH,
    492 		    "%s@%s as %s: unknown login. cmd='%.80s'",
    493 		    remuser, hostname, locuser, cmdbuf);
    494 		if (errorstr == NULL)
    495 			errorstr = "Permission denied.";
    496 		rshd_errx(EXIT_FAILURE, errorstr, errorhost);
    497 	}
    498 #ifdef LOGIN_CAP
    499 	lc = login_getclass(pwd ? pwd->pw_class : NULL);
    500 #endif
    501 
    502 	if (chdir(pwd->pw_dir) < 0) {
    503 		if (chdir("/") < 0
    504 #ifdef LOGIN_CAP
    505 		    || login_getcapbool(lc, "requirehome", pwd->pw_uid ? 1 : 0)
    506 #endif
    507 		) {
    508 			syslog(LOG_INFO|LOG_AUTH,
    509 			    "%s@%s as %s: no home directory. cmd='%.80s'",
    510 			    remuser, hostname, locuser, cmdbuf);
    511 			rshd_errx(EXIT_SUCCESS, "No remote home directory.");
    512 		}
    513 	}
    514 
    515 #ifndef USE_PAM
    516 	if (errorstr ||
    517 	    (pwd->pw_passwd != 0 && *pwd->pw_passwd != '\0' &&
    518 		iruserok_sa(fromp, fromp->sa_len, pwd->pw_uid == 0, remuser,
    519 			locuser) < 0)) {
    520 		errormsg = __rcmd_errstr ? __rcmd_errstr : "unknown error";
    521 		if (errorstr == NULL)
    522 			errorstr = "Permission denied.";
    523 		goto badlogin;
    524 	}
    525 
    526 	if (pwd->pw_uid && !access(_PATH_NOLOGIN, F_OK))
    527 		rshd_errx(EXIT_FAILURE, "Logins currently disabled.");
    528 #endif
    529 
    530 #ifdef LOGIN_CAP
    531 	/*
    532 	 * PAM modules might add supplementary groups in
    533 	 * pam_setcred(), so initialize them first.
    534 	 * But we need to open the session as root.
    535 	 */
    536 	if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) != 0) {
    537 		syslog(LOG_ERR, "setusercontext: %m");
    538 		exit(EXIT_FAILURE);
    539 	}
    540 #else
    541 	initgroups(pwd->pw_name, pwd->pw_gid);
    542 #endif
    543 
    544 #ifdef USE_PAM
    545 	if ((pam_err = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
    546 		syslog(LOG_ERR, "pam_open_session: %s",
    547 		    pam_strerror(pamh, pam_err));
    548 	} else if ((pam_err = pam_setcred(pamh, PAM_ESTABLISH_CRED))
    549 	    != PAM_SUCCESS) {
    550 		syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, pam_err));
    551 	}
    552 #endif
    553 
    554 	(void)write(STDERR_FILENO, "\0", 1);
    555 	sent_null = 1;
    556 
    557 	if (port) {
    558 		if (pipe(pv) < 0)
    559 			rshd_errx(EXIT_FAILURE, "Can't make pipe. (%s)",
    560 			    strerror(errno));
    561 		pid = fork();
    562 		if (pid == -1)
    563 			rshd_errx(EXIT_FAILURE, "Can't fork. (%s)",
    564 			    strerror(errno));
    565 		if (pid) {
    566 			(void)close(STDIN_FILENO);
    567 			(void)close(STDOUT_FILENO);
    568 			(void)close(STDERR_FILENO);
    569 			(void)close(pv[1]);
    570 
    571 			set[0].fd = s;
    572 			set[0].events = POLLIN;
    573 			set[1].fd = pv[0];
    574 			set[1].events = POLLIN;
    575 			ioctl(pv[0], FIONBIO, (char *)&one);
    576 
    577 			/* should set s nbio! */
    578 			do {
    579 				if (poll(set, 2, INFTIM) < 0)
    580 					break;
    581 				if (set[0].revents & POLLIN) {
    582 					int	ret;
    583 
    584 					ret = read(s, &sig, 1);
    585 					if (ret <= 0)
    586 						set[0].events = 0;
    587 					else
    588 						killpg(pid, sig);
    589 				}
    590 				if (set[1].revents & POLLIN) {
    591 					errno = 0;
    592 					cc = read(pv[0], buf, sizeof(buf));
    593 					if (cc <= 0) {
    594 						shutdown(s, SHUT_RDWR);
    595 						set[1].events = 0;
    596 					} else {
    597 						(void)write(s, buf, cc);
    598 					}
    599 				}
    600 
    601 			} while ((set[0].revents | set[1].revents) & POLLIN);
    602 			PAM_END;
    603 			exit(EXIT_SUCCESS);
    604 		}
    605 		(void)close(s);
    606 		(void)close(pv[0]);
    607 		(void)dup2(pv[1], STDERR_FILENO);
    608 		close(pv[1]);
    609 	}
    610 #ifdef USE_PAM
    611 	else {
    612 		pid = fork();
    613 		if (pid == -1)
    614 			rshd_errx(EXIT_FAILURE, "Can't fork. (%s)",
    615 			    strerror(errno));
    616 		if (pid) {
    617 			pid_t xpid;
    618 			int status;
    619 			if ((xpid = waitpid(pid, &status, 0)) != pid) {
    620 				pam_err = pam_close_session(pamh, 0);
    621 				if (pam_err != PAM_SUCCESS) {
    622 					syslog(LOG_ERR,
    623 					    "pam_close_session: %s",
    624 					    pam_strerror(pamh, pam_err));
    625 				}
    626 				PAM_END;
    627 				if (xpid != -1)
    628 					syslog(LOG_WARNING,
    629 					    "wrong PID: %d != %d", pid, xpid);
    630 				else
    631 					syslog(LOG_WARNING,
    632 					    "wait pid=%d failed %m", pid);
    633 				exit(EXIT_FAILURE);
    634 			}
    635 			exit(EXIT_SUCCESS);
    636 		}
    637 	}
    638 #endif
    639 
    640 #ifdef F_CLOSEM
    641 	(void)fcntl(STDERR_FILENO + 1, F_CLOSEM, 0);
    642 #else
    643 	for (fd = getdtablesize(); fd > STDERR_FILENO; fd--)
    644 		(void)close(fd);
    645 #endif
    646 	if (setsid() == -1)
    647 		syslog(LOG_ERR, "setsid() failed: %m");
    648 #ifdef USE_PAM
    649 	if (setlogin(pwd->pw_name) < 0)
    650 		syslog(LOG_ERR, "setlogin() failed: %m");
    651 
    652 	if (*pwd->pw_shell == '\0')
    653 		pwd->pw_shell = __UNCONST(_PATH_BSHELL);
    654 
    655 	(void)pam_setenv(pamh, "HOME", pwd->pw_dir, 1);
    656 	(void)pam_setenv(pamh, "SHELL", pwd->pw_shell, 1);
    657 	(void)pam_setenv(pamh, "USER", pwd->pw_name, 1);
    658 	(void)pam_setenv(pamh, "PATH", _PATH_DEFPATH, 1);
    659 	environ = pam_getenvlist(pamh);
    660 	(void)pam_end(pamh, pam_err);
    661 #else
    662 #ifdef LOGIN_CAP
    663 	{
    664 		char *sh;
    665 		if ((sh = login_getcapstr(lc, "shell", NULL, NULL))) {
    666 			if(!(sh = strdup(sh))) {
    667 				syslog(LOG_ERR, "Cannot alloc mem");
    668 				exit(EXIT_FAILURE);
    669 			}
    670 			pwd->pw_shell = sh;
    671 		}
    672 	}
    673 #endif
    674 {
    675 	static char *envinit[] = { NULL };
    676 	environ = envinit;
    677 }
    678 	setenv("PATH", _PATH_DEFPATH, 1);
    679 	setenv("HOME", pwd->pw_dir, 1);
    680 	setenv("SHELL", pwd->pw_shell, 1);
    681 	setenv("USER", pwd->pw_name, 1);
    682 #endif
    683 
    684 	cp = strrchr(pwd->pw_shell, '/');
    685 	if (cp)
    686 		cp++;
    687 	else
    688 		cp = pwd->pw_shell;
    689 
    690 #ifdef LOGIN_CAP
    691 	if (setusercontext(lc, pwd, pwd->pw_uid,
    692 		LOGIN_SETALL & ~LOGIN_SETGROUP) < 0) {
    693 		syslog(LOG_ERR, "setusercontext(): %m");
    694 		exit(EXIT_FAILURE);
    695 	}
    696 	login_close(lc);
    697 #else
    698 	(void)setgid((gid_t)pwd->pw_gid);
    699 	(void)setuid((uid_t)pwd->pw_uid);
    700 #endif
    701 	endpwent();
    702 	if (log_success || pwd->pw_uid == 0) {
    703 		syslog(LOG_INFO|LOG_AUTH, "%s@%s as %s: cmd='%.80s'",
    704 		    remuser, hostname, locuser, cmdbuf);
    705 	}
    706 	(void)execl(pwd->pw_shell, cp, "-c", cmdbuf, NULL);
    707 	rshd_errx(EXIT_FAILURE, "%s: %s", pwd->pw_shell, strerror(errno));
    708 badlogin:
    709 	syslog(LOG_INFO|LOG_AUTH,
    710 	    "%s@%s as %s: permission denied (%s). cmd='%.80s'",
    711 	    remuser, hostname, locuser, errormsg, cmdbuf);
    712 	rshd_errx(EXIT_FAILURE, errorstr, errorhost);
    713 }
    714 
    715 /*
    716  * Report error to client.  Note: can't be used until second socket has
    717  * connected to client, or older clients will hang waiting for that
    718  * connection first.
    719  */
    720 
    721 #include <stdarg.h>
    722 
    723 static void
    724 rshd_errx(int error, const char *fmt, ...)
    725 {
    726 	va_list ap;
    727 	int len, rv;
    728 	char *bp, buf[BUFSIZ];
    729 	va_start(ap, fmt);
    730 	bp = buf;
    731 	if (sent_null == 0) {
    732 		*bp++ = 1;
    733 		len = 1;
    734 	} else
    735 		len = 0;
    736 	rv = vsnprintf(bp, sizeof(buf) - 2, fmt, ap);
    737 	bp[rv++] = '\n';
    738 	(void)write(STDERR_FILENO, buf, len + rv);
    739 	va_end(ap);
    740 	exit(error);
    741 }
    742 
    743 static void
    744 getstr(char *buf, int cnt, const char *err)
    745 {
    746 	char c;
    747 
    748 	do {
    749 		if (read(STDIN_FILENO, &c, 1) != 1)
    750 			exit(EXIT_FAILURE);
    751 		*buf++ = c;
    752 		if (--cnt == 0)
    753 			rshd_errx(EXIT_FAILURE, "%s too long", err);
    754 	} while (c != 0);
    755 }
    756 
    757 /*
    758  * Check whether host h is in our local domain,
    759  * defined as sharing the last two components of the domain part,
    760  * or the entire domain part if the local domain has only one component.
    761  * If either name is unqualified (contains no '.'),
    762  * assume that the host is local, as it will be
    763  * interpreted as such.
    764  */
    765 static int
    766 local_domain(char *h)
    767 {
    768 	char localhost[MAXHOSTNAMELEN + 1];
    769 	char *p1, *p2;
    770 
    771 	localhost[0] = 0;
    772 	(void)gethostname(localhost, sizeof(localhost));
    773 	localhost[sizeof(localhost) - 1] = '\0';
    774 	p1 = topdomain(localhost);
    775 	p2 = topdomain(h);
    776 	if (p1 == NULL || p2 == NULL || !strcasecmp(p1, p2))
    777 		return (1);
    778 	return (0);
    779 }
    780 
    781 static char *
    782 topdomain(char *h)
    783 {
    784 	char *p, *maybe = NULL;
    785 	int dots = 0;
    786 
    787 	for (p = h + strlen(h); p >= h; p--) {
    788 		if (*p == '.') {
    789 			if (++dots == 2)
    790 				return (p);
    791 			maybe = p;
    792 		}
    793 	}
    794 	return (maybe);
    795 }
    796 
    797 static void
    798 usage(void)
    799 {
    800 
    801 	syslog(LOG_ERR, "Usage: %s [-%s]", getprogname(), OPTIONS);
    802 	exit(EXIT_FAILURE);
    803 }
    804