Home | History | Annotate | Line # | Download | only in dist
session.c revision 1.8.10.1
      1 /*	$NetBSD: session.c,v 1.8.10.1 2017/08/15 04:40:16 snj Exp $	*/
      2 /* $OpenBSD: session.c,v 1.286 2016/11/30 03:00:05 djm Exp $ */
      3 
      4 /*
      5  * Copyright (c) 1995 Tatu Ylonen <ylo (at) cs.hut.fi>, Espoo, Finland
      6  *                    All rights reserved
      7  *
      8  * As far as I am concerned, the code I have written for this software
      9  * can be used freely for any purpose.  Any derived versions of this
     10  * software must be clearly marked as such, and if the derived work is
     11  * incompatible with the protocol description in the RFC file, it must be
     12  * called by a name other than "ssh" or "Secure Shell".
     13  *
     14  * SSH2 support by Markus Friedl.
     15  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
     16  *
     17  * Redistribution and use in source and binary forms, with or without
     18  * modification, are permitted provided that the following conditions
     19  * are met:
     20  * 1. Redistributions of source code must retain the above copyright
     21  *    notice, this list of conditions and the following disclaimer.
     22  * 2. Redistributions in binary form must reproduce the above copyright
     23  *    notice, this list of conditions and the following disclaimer in the
     24  *    documentation and/or other materials provided with the distribution.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     27  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     28  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     29  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     30  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     31  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     32  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     35  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     36  */
     37 
     38 #include "includes.h"
     39 __RCSID("$NetBSD: session.c,v 1.8.10.1 2017/08/15 04:40:16 snj Exp $");
     40 #include <sys/types.h>
     41 #include <sys/wait.h>
     42 #include <sys/un.h>
     43 #include <sys/stat.h>
     44 #include <sys/socket.h>
     45 #include <sys/queue.h>
     46 
     47 #include <ctype.h>
     48 #include <errno.h>
     49 #include <fcntl.h>
     50 #include <grp.h>
     51 #include <login_cap.h>
     52 #include <netdb.h>
     53 #include <paths.h>
     54 #include <pwd.h>
     55 #include <signal.h>
     56 #include <stdio.h>
     57 #include <stdlib.h>
     58 #include <string.h>
     59 #include <unistd.h>
     60 #include <limits.h>
     61 
     62 #include "xmalloc.h"
     63 #include "ssh.h"
     64 #include "ssh2.h"
     65 #include "sshpty.h"
     66 #include "packet.h"
     67 #include "buffer.h"
     68 #include "match.h"
     69 #include "uidswap.h"
     70 #include "compat.h"
     71 #include "channels.h"
     72 #include "key.h"
     73 #include "cipher.h"
     74 #include "kex.h"
     75 #include "hostfile.h"
     76 #include "auth.h"
     77 #include "auth-options.h"
     78 #include "authfd.h"
     79 #include "pathnames.h"
     80 #include "log.h"
     81 #include "misc.h"
     82 #include "servconf.h"
     83 #include "sshlogin.h"
     84 #include "serverloop.h"
     85 #include "canohost.h"
     86 #include "session.h"
     87 #ifdef GSSAPI
     88 #include "ssh-gss.h"
     89 #endif
     90 #include "monitor_wrap.h"
     91 #include "sftp.h"
     92 
     93 #ifdef KRB5
     94 #include <krb5/kafs.h>
     95 #endif
     96 
     97 #define IS_INTERNAL_SFTP(c) \
     98 	(!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \
     99 	 (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \
    100 	  c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \
    101 	  c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t'))
    102 
    103 /* func */
    104 
    105 Session *session_new(void);
    106 void	session_set_fds(Session *, int, int, int, int, int);
    107 void	session_pty_cleanup(Session *);
    108 void	session_proctitle(Session *);
    109 int	session_setup_x11fwd(Session *);
    110 int	do_exec_pty(Session *, const char *);
    111 int	do_exec_no_pty(Session *, const char *);
    112 int	do_exec(Session *, const char *);
    113 void	do_login(Session *, const char *);
    114 __dead void	do_child(Session *, const char *);
    115 void	do_motd(void);
    116 int	check_quietlogin(Session *, const char *);
    117 
    118 static void do_authenticated2(Authctxt *);
    119 
    120 static int session_pty_req(Session *);
    121 
    122 /* import */
    123 extern ServerOptions options;
    124 extern char *__progname;
    125 extern int log_stderr;
    126 extern int debug_flag;
    127 extern u_int utmp_len;
    128 extern int startup_pipe;
    129 extern void destroy_sensitive_data(void);
    130 extern Buffer loginmsg;
    131 
    132 /* original command from peer. */
    133 const char *original_command = NULL;
    134 
    135 /* data */
    136 static int sessions_first_unused = -1;
    137 static int sessions_nalloc = 0;
    138 static Session *sessions = NULL;
    139 
    140 #define SUBSYSTEM_NONE			0
    141 #define SUBSYSTEM_EXT			1
    142 #define SUBSYSTEM_INT_SFTP		2
    143 #define SUBSYSTEM_INT_SFTP_ERROR	3
    144 
    145 #ifdef HAVE_LOGIN_CAP
    146 login_cap_t *lc;
    147 #endif
    148 
    149 static int is_child = 0;
    150 static int in_chroot = 0;
    151 
    152 /* Name and directory of socket for authentication agent forwarding. */
    153 static char *auth_sock_name = NULL;
    154 static char *auth_sock_dir = NULL;
    155 
    156 /* removes the agent forwarding socket */
    157 
    158 static void
    159 auth_sock_cleanup_proc(struct passwd *pw)
    160 {
    161 	if (auth_sock_name != NULL) {
    162 		temporarily_use_uid(pw);
    163 		unlink(auth_sock_name);
    164 		rmdir(auth_sock_dir);
    165 		auth_sock_name = NULL;
    166 		restore_uid();
    167 	}
    168 }
    169 
    170 static int
    171 auth_input_request_forwarding(struct passwd * pw)
    172 {
    173 	Channel *nc;
    174 	int sock = -1;
    175 
    176 	if (auth_sock_name != NULL) {
    177 		error("authentication forwarding requested twice.");
    178 		return 0;
    179 	}
    180 
    181 	/* Temporarily drop privileged uid for mkdir/bind. */
    182 	temporarily_use_uid(pw);
    183 
    184 	/* Allocate a buffer for the socket name, and format the name. */
    185 	auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX");
    186 
    187 	/* Create private directory for socket */
    188 	if (mkdtemp(auth_sock_dir) == NULL) {
    189 		packet_send_debug("Agent forwarding disabled: "
    190 		    "mkdtemp() failed: %.100s", strerror(errno));
    191 		restore_uid();
    192 		free(auth_sock_dir);
    193 		auth_sock_dir = NULL;
    194 		goto authsock_err;
    195 	}
    196 
    197 	xasprintf(&auth_sock_name, "%s/agent.%ld",
    198 	    auth_sock_dir, (long) getpid());
    199 
    200 	/* Start a Unix listener on auth_sock_name. */
    201 	sock = unix_listener(auth_sock_name, SSH_LISTEN_BACKLOG, 0);
    202 
    203 	/* Restore the privileged uid. */
    204 	restore_uid();
    205 
    206 	/* Check for socket/bind/listen failure. */
    207 	if (sock < 0)
    208 		goto authsock_err;
    209 
    210 	/* Allocate a channel for the authentication agent socket. */
    211 	/* this shouldn't matter if its hpn or not - cjr */
    212 	nc = channel_new("auth socket",
    213 	    SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
    214 	    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
    215 	    0, "auth socket", 1);
    216 	nc->path = xstrdup(auth_sock_name);
    217 	return 1;
    218 
    219  authsock_err:
    220 	free(auth_sock_name);
    221 	if (auth_sock_dir != NULL) {
    222 		rmdir(auth_sock_dir);
    223 		free(auth_sock_dir);
    224 	}
    225 	if (sock != -1)
    226 		close(sock);
    227 	auth_sock_name = NULL;
    228 	auth_sock_dir = NULL;
    229 	return 0;
    230 }
    231 
    232 static void
    233 display_loginmsg(void)
    234 {
    235 	if (buffer_len(&loginmsg) > 0) {
    236 		buffer_append(&loginmsg, "\0", 1);
    237 		printf("%s", (char *)buffer_ptr(&loginmsg));
    238 		buffer_clear(&loginmsg);
    239 	}
    240 }
    241 
    242 void
    243 do_authenticated(Authctxt *authctxt)
    244 {
    245 	setproctitle("%s", authctxt->pw->pw_name);
    246 
    247 	/* setup the channel layer */
    248 	/* XXX - streamlocal? */
    249 	if (no_port_forwarding_flag || options.disable_forwarding ||
    250 	    (options.allow_tcp_forwarding & FORWARD_LOCAL) == 0)
    251 		channel_disable_adm_local_opens();
    252 	else
    253 		channel_permit_all_opens();
    254 
    255 	auth_debug_send();
    256 
    257 	do_authenticated2(authctxt);
    258 	do_cleanup(authctxt);
    259 }
    260 
    261 /* Check untrusted xauth strings for metacharacters */
    262 static int
    263 xauth_valid_string(const char *s)
    264 {
    265 	size_t i;
    266 
    267 	for (i = 0; s[i] != '\0'; i++) {
    268 		if (!isalnum((u_char)s[i]) &&
    269 		    s[i] != '.' && s[i] != ':' && s[i] != '/' &&
    270 		    s[i] != '-' && s[i] != '_')
    271 		return 0;
    272 	}
    273 	return 1;
    274 }
    275 
    276 #define USE_PIPES 1
    277 /*
    278  * This is called to fork and execute a command when we have no tty.  This
    279  * will call do_child from the child, and server_loop from the parent after
    280  * setting up file descriptors and such.
    281  */
    282 int
    283 do_exec_no_pty(Session *s, const char *command)
    284 {
    285 	pid_t pid;
    286 #ifdef USE_PIPES
    287 	int pin[2], pout[2], perr[2];
    288 
    289 	if (s == NULL)
    290 		fatal("do_exec_no_pty: no session");
    291 
    292 	/* Allocate pipes for communicating with the program. */
    293 	if (pipe(pin) < 0) {
    294 		error("%s: pipe in: %.100s", __func__, strerror(errno));
    295 		return -1;
    296 	}
    297 	if (pipe(pout) < 0) {
    298 		error("%s: pipe out: %.100s", __func__, strerror(errno));
    299 		close(pin[0]);
    300 		close(pin[1]);
    301 		return -1;
    302 	}
    303 	if (pipe(perr) < 0) {
    304 		error("%s: pipe err: %.100s", __func__,
    305 		    strerror(errno));
    306 		close(pin[0]);
    307 		close(pin[1]);
    308 		close(pout[0]);
    309 		close(pout[1]);
    310 		return -1;
    311 	}
    312 #else
    313 	int inout[2], err[2];
    314 
    315 	if (s == NULL)
    316 		fatal("do_exec_no_pty: no session");
    317 
    318 	/* Uses socket pairs to communicate with the program. */
    319 	if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0) {
    320 		error("%s: socketpair #1: %.100s", __func__, strerror(errno));
    321 		return -1;
    322 	}
    323 	if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) {
    324 		error("%s: socketpair #2: %.100s", __func__,
    325 		    strerror(errno));
    326 		close(inout[0]);
    327 		close(inout[1]);
    328 		return -1;
    329 	}
    330 #endif
    331 
    332 	session_proctitle(s);
    333 
    334 #ifdef notdef
    335 #if defined(USE_PAM)
    336 	if (options.use_pam && !use_privsep)
    337 		do_pam_setcred(1);
    338 #endif /* USE_PAM */
    339 #endif
    340 
    341 	/* Fork the child. */
    342 	switch ((pid = fork())) {
    343 	case -1:
    344 		error("%s: fork: %.100s", __func__, strerror(errno));
    345 #ifdef USE_PIPES
    346 		close(pin[0]);
    347 		close(pin[1]);
    348 		close(pout[0]);
    349 		close(pout[1]);
    350 		close(perr[0]);
    351 		close(perr[1]);
    352 #else
    353 		close(inout[0]);
    354 		close(inout[1]);
    355 		close(err[0]);
    356 		close(err[1]);
    357 #endif
    358 		return -1;
    359 	case 0:
    360 		is_child = 1;
    361 
    362 		/* Child.  Reinitialize the log since the pid has changed. */
    363 		log_init(__progname, options.log_level,
    364 		    options.log_facility, log_stderr);
    365 
    366 		/*
    367 		 * Create a new session and process group since the 4.4BSD
    368 		 * setlogin() affects the entire process group.
    369 		 */
    370 		if (setsid() < 0)
    371 			error("setsid failed: %.100s", strerror(errno));
    372 
    373 #ifdef USE_PIPES
    374 		/*
    375 		 * Redirect stdin.  We close the parent side of the socket
    376 		 * pair, and make the child side the standard input.
    377 		 */
    378 		close(pin[1]);
    379 		if (dup2(pin[0], 0) < 0)
    380 			perror("dup2 stdin");
    381 		close(pin[0]);
    382 
    383 		/* Redirect stdout. */
    384 		close(pout[0]);
    385 		if (dup2(pout[1], 1) < 0)
    386 			perror("dup2 stdout");
    387 		close(pout[1]);
    388 
    389 		/* Redirect stderr. */
    390 		close(perr[0]);
    391 		if (dup2(perr[1], 2) < 0)
    392 			perror("dup2 stderr");
    393 		close(perr[1]);
    394 #else
    395 		/*
    396 		 * Redirect stdin, stdout, and stderr.  Stdin and stdout will
    397 		 * use the same socket, as some programs (particularly rdist)
    398 		 * seem to depend on it.
    399 		 */
    400 		close(inout[1]);
    401 		close(err[1]);
    402 		if (dup2(inout[0], 0) < 0)	/* stdin */
    403 			perror("dup2 stdin");
    404 		if (dup2(inout[0], 1) < 0)	/* stdout (same as stdin) */
    405 			perror("dup2 stdout");
    406 		close(inout[0]);
    407 		if (dup2(err[0], 2) < 0)	/* stderr */
    408 			perror("dup2 stderr");
    409 		close(err[0]);
    410 #endif
    411 
    412 		/* Do processing for the child (exec command etc). */
    413 		do_child(s, command);
    414 		/* NOTREACHED */
    415 	default:
    416 		break;
    417 	}
    418 
    419 	s->pid = pid;
    420 	/* Set interactive/non-interactive mode. */
    421 	packet_set_interactive(s->display != NULL,
    422 	    options.ip_qos_interactive, options.ip_qos_bulk);
    423 
    424 #ifdef USE_PIPES
    425 	/* We are the parent.  Close the child sides of the pipes. */
    426 	close(pin[0]);
    427 	close(pout[1]);
    428 	close(perr[1]);
    429 
    430 	session_set_fds(s, pin[1], pout[0], perr[0],
    431 	    s->is_subsystem, 0);
    432 #else
    433 	/* We are the parent.  Close the child sides of the socket pairs. */
    434 	close(inout[0]);
    435 	close(err[0]);
    436 
    437 	/*
    438 	 * Enter the interactive session.  Note: server_loop must be able to
    439 	 * handle the case that fdin and fdout are the same.
    440 	 */
    441 	session_set_fds(s, inout[1], inout[1], err[1],
    442 	    s->is_subsystem, 0);
    443 #endif
    444 	return 0;
    445 }
    446 
    447 /*
    448  * This is called to fork and execute a command when we have a tty.  This
    449  * will call do_child from the child, and server_loop from the parent after
    450  * setting up file descriptors, controlling tty, updating wtmp, utmp,
    451  * lastlog, and other such operations.
    452  */
    453 int
    454 do_exec_pty(Session *s, const char *command)
    455 {
    456 	int fdout, ptyfd, ttyfd, ptymaster;
    457 	pid_t pid;
    458 
    459 	if (s == NULL)
    460 		fatal("do_exec_pty: no session");
    461 	ptyfd = s->ptyfd;
    462 	ttyfd = s->ttyfd;
    463 
    464 #if defined(USE_PAM)
    465 	if (options.use_pam) {
    466 		do_pam_set_tty(s->tty);
    467 		if (!use_privsep)
    468 			do_pam_setcred(1);
    469 	}
    470 #endif
    471 
    472 	/*
    473 	 * Create another descriptor of the pty master side for use as the
    474 	 * standard input.  We could use the original descriptor, but this
    475 	 * simplifies code in server_loop.  The descriptor is bidirectional.
    476 	 * Do this before forking (and cleanup in the child) so as to
    477 	 * detect and gracefully fail out-of-fd conditions.
    478 	 */
    479 	if ((fdout = dup(ptyfd)) < 0) {
    480 		error("%s: dup #1: %s", __func__, strerror(errno));
    481 		close(ttyfd);
    482 		close(ptyfd);
    483 		return -1;
    484 	}
    485 	/* we keep a reference to the pty master */
    486 	if ((ptymaster = dup(ptyfd)) < 0) {
    487 		error("%s: dup #2: %s", __func__, strerror(errno));
    488 		close(ttyfd);
    489 		close(ptyfd);
    490 		close(fdout);
    491 		return -1;
    492 	}
    493 
    494 	/* Fork the child. */
    495 	switch ((pid = fork())) {
    496 	case -1:
    497 		error("%s: fork: %.100s", __func__, strerror(errno));
    498 		close(fdout);
    499 		close(ptymaster);
    500 		close(ttyfd);
    501 		close(ptyfd);
    502 		return -1;
    503 	case 0:
    504 		is_child = 1;
    505 
    506 		close(fdout);
    507 		close(ptymaster);
    508 
    509 		/* Child.  Reinitialize the log because the pid has changed. */
    510 		log_init(__progname, options.log_level,
    511 		    options.log_facility, log_stderr);
    512 		/* Close the master side of the pseudo tty. */
    513 		close(ptyfd);
    514 
    515 		/* Make the pseudo tty our controlling tty. */
    516 		pty_make_controlling_tty(&ttyfd, s->tty);
    517 
    518 		/* Redirect stdin/stdout/stderr from the pseudo tty. */
    519 		if (dup2(ttyfd, 0) < 0)
    520 			error("dup2 stdin: %s", strerror(errno));
    521 		if (dup2(ttyfd, 1) < 0)
    522 			error("dup2 stdout: %s", strerror(errno));
    523 		if (dup2(ttyfd, 2) < 0)
    524 			error("dup2 stderr: %s", strerror(errno));
    525 
    526 		/* Close the extra descriptor for the pseudo tty. */
    527 		close(ttyfd);
    528 
    529 		/* record login, etc. similar to login(1) */
    530 		do_login(s, command);
    531 
    532 		/*
    533 		 * Do common processing for the child, such as execing
    534 		 * the command.
    535 		 */
    536 		do_child(s, command);
    537 		/* NOTREACHED */
    538 	default:
    539 		break;
    540 	}
    541 	s->pid = pid;
    542 
    543 	/* Parent.  Close the slave side of the pseudo tty. */
    544 	close(ttyfd);
    545 
    546 	/* Enter interactive session. */
    547 	s->ptymaster = ptymaster;
    548 	packet_set_interactive(1,
    549 	    options.ip_qos_interactive, options.ip_qos_bulk);
    550 	session_set_fds(s, ptyfd, fdout, -1, 1, 1);
    551 	return 0;
    552 }
    553 
    554 /*
    555  * This is called to fork and execute a command.  If another command is
    556  * to be forced, execute that instead.
    557  */
    558 int
    559 do_exec(Session *s, const char *command)
    560 {
    561 	struct ssh *ssh = active_state; /* XXX */
    562 	int ret;
    563 	const char *forced = NULL, *tty = NULL;
    564 	char session_type[1024];
    565 
    566 	if (options.adm_forced_command) {
    567 		original_command = command;
    568 		command = options.adm_forced_command;
    569 		forced = "(config)";
    570 	} else if (forced_command) {
    571 		original_command = command;
    572 		command = forced_command;
    573 		forced = "(key-option)";
    574 	}
    575 	if (forced != NULL) {
    576 		if (IS_INTERNAL_SFTP(command)) {
    577 			s->is_subsystem = s->is_subsystem ?
    578 			    SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
    579 		} else if (s->is_subsystem)
    580 			s->is_subsystem = SUBSYSTEM_EXT;
    581 		snprintf(session_type, sizeof(session_type),
    582 		    "forced-command %s '%.900s'", forced, command);
    583 	} else if (s->is_subsystem) {
    584 		snprintf(session_type, sizeof(session_type),
    585 		    "subsystem '%.900s'", s->subsys);
    586 	} else if (command == NULL) {
    587 		snprintf(session_type, sizeof(session_type), "shell");
    588 	} else {
    589 		/* NB. we don't log unforced commands to preserve privacy */
    590 		snprintf(session_type, sizeof(session_type), "command");
    591 	}
    592 
    593 	if (s->ttyfd != -1) {
    594 		tty = s->tty;
    595 		if (strncmp(tty, "/dev/", 5) == 0)
    596 			tty += 5;
    597 	}
    598 
    599 	verbose("Starting session: %s%s%s for %s from %.200s port %d id %d",
    600 	    session_type,
    601 	    tty == NULL ? "" : " on ",
    602 	    tty == NULL ? "" : tty,
    603 	    s->pw->pw_name,
    604 	    ssh_remote_ipaddr(ssh),
    605 	    ssh_remote_port(ssh),
    606 	    s->self);
    607 
    608 #ifdef GSSAPI
    609 	if (options.gss_authentication) {
    610 		temporarily_use_uid(s->pw);
    611 		ssh_gssapi_storecreds();
    612 		restore_uid();
    613 	}
    614 #endif
    615 	if (s->ttyfd != -1)
    616 		ret = do_exec_pty(s, command);
    617 	else
    618 		ret = do_exec_no_pty(s, command);
    619 
    620 	original_command = NULL;
    621 
    622 	/*
    623 	 * Clear loginmsg: it's the child's responsibility to display
    624 	 * it to the user, otherwise multiple sessions may accumulate
    625 	 * multiple copies of the login messages.
    626 	 */
    627 	buffer_clear(&loginmsg);
    628 
    629 	return ret;
    630 }
    631 
    632 
    633 /* administrative, login(1)-like work */
    634 void
    635 do_login(Session *s, const char *command)
    636 {
    637 	struct ssh *ssh = active_state;	/* XXX */
    638 	socklen_t fromlen;
    639 	struct sockaddr_storage from;
    640 	struct passwd * pw = s->pw;
    641 	pid_t pid = getpid();
    642 
    643 	/*
    644 	 * Get IP address of client. If the connection is not a socket, let
    645 	 * the address be 0.0.0.0.
    646 	 */
    647 	memset(&from, 0, sizeof(from));
    648 	fromlen = sizeof(from);
    649 	if (packet_connection_is_on_socket()) {
    650 		if (getpeername(packet_get_connection_in(),
    651 		    (struct sockaddr *)&from, &fromlen) < 0) {
    652 			debug("getpeername: %.100s", strerror(errno));
    653 			cleanup_exit(255);
    654 		}
    655 	}
    656 
    657 	/* Record that there was a login on that tty from the remote host. */
    658 	if (!use_privsep)
    659 		record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
    660 		    session_get_remote_name_or_ip(ssh, utmp_len,
    661 		    options.use_dns),
    662 		    (struct sockaddr *)&from, fromlen);
    663 
    664 #ifdef USE_PAM
    665 	/*
    666 	 * If password change is needed, do it now.
    667 	 * This needs to occur before the ~/.hushlogin check.
    668 	 */
    669 	if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
    670 		display_loginmsg();
    671 		do_pam_chauthtok();
    672 		s->authctxt->force_pwchange = 0;
    673 		/* XXX - signal [net] parent to enable forwardings */
    674 	}
    675 #endif
    676 
    677 	if (check_quietlogin(s, command))
    678 		return;
    679 
    680 	display_loginmsg();
    681 
    682 	do_motd();
    683 }
    684 
    685 /*
    686  * Display the message of the day.
    687  */
    688 void
    689 do_motd(void)
    690 {
    691 	FILE *f;
    692 	char buf[256];
    693 
    694 	if (options.print_motd) {
    695 #ifdef HAVE_LOGIN_CAP
    696 		f = fopen(login_getcapstr(lc, "welcome", __UNCONST("/etc/motd"),
    697 		    __UNCONST("/etc/motd")), "r");
    698 #else
    699 		f = fopen("/etc/motd", "r");
    700 #endif
    701 		if (f) {
    702 			while (fgets(buf, sizeof(buf), f))
    703 				fputs(buf, stdout);
    704 			fclose(f);
    705 		}
    706 	}
    707 }
    708 
    709 
    710 /*
    711  * Check for quiet login, either .hushlogin or command given.
    712  */
    713 int
    714 check_quietlogin(Session *s, const char *command)
    715 {
    716 	char buf[256];
    717 	struct passwd *pw = s->pw;
    718 	struct stat st;
    719 
    720 	/* Return 1 if .hushlogin exists or a command given. */
    721 	if (command != NULL)
    722 		return 1;
    723 	snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
    724 #ifdef HAVE_LOGIN_CAP
    725 	if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
    726 		return 1;
    727 #else
    728 	if (stat(buf, &st) >= 0)
    729 		return 1;
    730 #endif
    731 	return 0;
    732 }
    733 
    734 /*
    735  * Sets the value of the given variable in the environment.  If the variable
    736  * already exists, its value is overridden.
    737  */
    738 void
    739 child_set_env(char ***envp, u_int *envsizep, const char *name,
    740 	const char *value)
    741 {
    742 	char **env;
    743 	u_int envsize;
    744 	u_int i, namelen;
    745 
    746 	if (strchr(name, '=') != NULL) {
    747 		error("Invalid environment variable \"%.100s\"", name);
    748 		return;
    749 	}
    750 
    751 	/*
    752 	 * Find the slot where the value should be stored.  If the variable
    753 	 * already exists, we reuse the slot; otherwise we append a new slot
    754 	 * at the end of the array, expanding if necessary.
    755 	 */
    756 	env = *envp;
    757 	namelen = strlen(name);
    758 	for (i = 0; env[i]; i++)
    759 		if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
    760 			break;
    761 	if (env[i]) {
    762 		/* Reuse the slot. */
    763 		free(env[i]);
    764 	} else {
    765 		/* New variable.  Expand if necessary. */
    766 		envsize = *envsizep;
    767 		if (i >= envsize - 1) {
    768 			if (envsize >= 1000)
    769 				fatal("child_set_env: too many env vars");
    770 			envsize += 50;
    771 			env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
    772 			*envsizep = envsize;
    773 		}
    774 		/* Need to set the NULL pointer at end of array beyond the new slot. */
    775 		env[i + 1] = NULL;
    776 	}
    777 
    778 	/* Allocate space and format the variable in the appropriate slot. */
    779 	env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
    780 	snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
    781 }
    782 
    783 /*
    784  * Reads environment variables from the given file and adds/overrides them
    785  * into the environment.  If the file does not exist, this does nothing.
    786  * Otherwise, it must consist of empty lines, comments (line starts with '#')
    787  * and assignments of the form name=value.  No other forms are allowed.
    788  */
    789 static void
    790 read_environment_file(char ***env, u_int *envsize,
    791 	const char *filename)
    792 {
    793 	FILE *f;
    794 	char buf[4096];
    795 	char *cp, *value;
    796 	u_int lineno = 0;
    797 
    798 	f = fopen(filename, "r");
    799 	if (!f)
    800 		return;
    801 
    802 	while (fgets(buf, sizeof(buf), f)) {
    803 		if (++lineno > 1000)
    804 			fatal("Too many lines in environment file %s", filename);
    805 		for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
    806 			;
    807 		if (!*cp || *cp == '#' || *cp == '\n')
    808 			continue;
    809 
    810 		cp[strcspn(cp, "\n")] = '\0';
    811 
    812 		value = strchr(cp, '=');
    813 		if (value == NULL) {
    814 			fprintf(stderr, "Bad line %u in %.100s\n", lineno,
    815 			    filename);
    816 			continue;
    817 		}
    818 		/*
    819 		 * Replace the equals sign by nul, and advance value to
    820 		 * the value string.
    821 		 */
    822 		*value = '\0';
    823 		value++;
    824 		child_set_env(env, envsize, cp, value);
    825 	}
    826 	fclose(f);
    827 }
    828 
    829 #ifdef USE_PAM
    830 void copy_environment(char **, char ***, u_int *);
    831 void copy_environment(char **source, char ***env, u_int *envsize)
    832 {
    833 	char *var_name, *var_val;
    834 	int i;
    835 
    836 	if (source == NULL)
    837 		return;
    838 
    839 	for (i = 0; source[i] != NULL; i++) {
    840 		var_name = xstrdup(source[i]);
    841 		if ((var_val = strstr(var_name, "=")) == NULL) {
    842 			free(var_name);
    843 			continue;
    844 		}
    845 		*var_val++ = '\0';
    846 
    847 		debug3("Copy environment: %s=%s", var_name, var_val);
    848 		child_set_env(env, envsize, var_name, var_val);
    849 
    850 		free(var_name);
    851 	}
    852 }
    853 #endif
    854 
    855 static char **
    856 do_setup_env(Session *s, const char *shell)
    857 {
    858 	struct ssh *ssh = active_state; /* XXX */
    859 	char buf[256];
    860 	u_int i, envsize;
    861 	char **env, *laddr;
    862 	struct passwd *pw = s->pw;
    863 
    864 	/* Initialize the environment. */
    865 	envsize = 100;
    866 	env = xcalloc(envsize, sizeof(char *));
    867 	env[0] = NULL;
    868 
    869 #ifdef GSSAPI
    870 	/* Allow any GSSAPI methods that we've used to alter
    871 	 * the childs environment as they see fit
    872 	 */
    873 	ssh_gssapi_do_child(&env, &envsize);
    874 #endif
    875 
    876 	/* Set basic environment. */
    877 	for (i = 0; i < s->num_env; i++)
    878 		child_set_env(&env, &envsize, s->env[i].name, s->env[i].val);
    879 
    880 	child_set_env(&env, &envsize, "USER", pw->pw_name);
    881 	child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
    882 	child_set_env(&env, &envsize, "HOME", pw->pw_dir);
    883 	if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
    884 		child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
    885 	else
    886 		child_set_env(&env, &envsize, "PATH", getenv("PATH"));
    887 
    888 	snprintf(buf, sizeof buf, "%.200s/%.50s", _PATH_MAILDIR, pw->pw_name);
    889 	child_set_env(&env, &envsize, "MAIL", buf);
    890 
    891 	/* Normal systems set SHELL by default. */
    892 	child_set_env(&env, &envsize, "SHELL", shell);
    893 
    894 	if (getenv("TZ"))
    895 		child_set_env(&env, &envsize, "TZ", getenv("TZ"));
    896 
    897 	/* Set custom environment options from RSA authentication. */
    898 	while (custom_environment) {
    899 		struct envstring *ce = custom_environment;
    900 		char *str = ce->s;
    901 
    902 		for (i = 0; str[i] != '=' && str[i]; i++)
    903 			;
    904 		if (str[i] == '=') {
    905 			str[i] = 0;
    906 			child_set_env(&env, &envsize, str, str + i + 1);
    907 		}
    908 		custom_environment = ce->next;
    909 		free(ce->s);
    910 		free(ce);
    911 	}
    912 
    913 	/* SSH_CLIENT deprecated */
    914 	snprintf(buf, sizeof buf, "%.50s %d %d",
    915 	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
    916 	    ssh_local_port(ssh));
    917 	child_set_env(&env, &envsize, "SSH_CLIENT", buf);
    918 
    919 	laddr = get_local_ipaddr(packet_get_connection_in());
    920 	snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
    921 	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
    922 	    laddr, ssh_local_port(ssh));
    923 	free(laddr);
    924 	child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
    925 
    926 	if (s->ttyfd != -1)
    927 		child_set_env(&env, &envsize, "SSH_TTY", s->tty);
    928 	if (s->term)
    929 		child_set_env(&env, &envsize, "TERM", s->term);
    930 	if (s->display)
    931 		child_set_env(&env, &envsize, "DISPLAY", s->display);
    932 	if (original_command)
    933 		child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
    934 		    original_command);
    935 #ifdef KRB4
    936 	if (s->authctxt->krb4_ticket_file)
    937 		child_set_env(&env, &envsize, "KRBTKFILE",
    938 		    s->authctxt->krb4_ticket_file);
    939 #endif
    940 #ifdef KRB5
    941 	if (s->authctxt->krb5_ticket_file)
    942 		child_set_env(&env, &envsize, "KRB5CCNAME",
    943 		    s->authctxt->krb5_ticket_file);
    944 #endif
    945 #ifdef USE_PAM
    946 	/*
    947 	 * Pull in any environment variables that may have
    948 	 * been set by PAM.
    949 	 */
    950 	if (options.use_pam) {
    951 		char **p;
    952 
    953 		p = fetch_pam_child_environment();
    954 		copy_environment(p, &env, &envsize);
    955 		free_pam_environment(p);
    956 
    957 		p = fetch_pam_environment();
    958 		copy_environment(p, &env, &envsize);
    959 		free_pam_environment(p);
    960 	}
    961 #endif /* USE_PAM */
    962 
    963 	if (auth_sock_name != NULL)
    964 		child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
    965 		    auth_sock_name);
    966 
    967 	/* read $HOME/.ssh/environment. */
    968 	if (options.permit_user_env) {
    969 		snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
    970 		    pw->pw_dir);
    971 		read_environment_file(&env, &envsize, buf);
    972 	}
    973 	if (debug_flag) {
    974 		/* dump the environment */
    975 		fprintf(stderr, "Environment:\n");
    976 		for (i = 0; env[i]; i++)
    977 			fprintf(stderr, "  %.200s\n", env[i]);
    978 	}
    979 	return env;
    980 }
    981 
    982 /*
    983  * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
    984  * first in this order).
    985  */
    986 static void
    987 do_rc_files(Session *s, const char *shell)
    988 {
    989 	FILE *f = NULL;
    990 	char cmd[1024];
    991 	int do_xauth;
    992 	struct stat st;
    993 
    994 	do_xauth =
    995 	    s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
    996 
    997 	/* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
    998 	if (!s->is_subsystem && options.adm_forced_command == NULL &&
    999 	    !no_user_rc && options.permit_user_rc &&
   1000 	    stat(_PATH_SSH_USER_RC, &st) >= 0) {
   1001 		snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
   1002 		    shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
   1003 		if (debug_flag)
   1004 			fprintf(stderr, "Running %s\n", cmd);
   1005 		f = popen(cmd, "w");
   1006 		if (f) {
   1007 			if (do_xauth)
   1008 				fprintf(f, "%s %s\n", s->auth_proto,
   1009 				    s->auth_data);
   1010 			pclose(f);
   1011 		} else
   1012 			fprintf(stderr, "Could not run %s\n",
   1013 			    _PATH_SSH_USER_RC);
   1014 	} else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
   1015 		if (debug_flag)
   1016 			fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
   1017 			    _PATH_SSH_SYSTEM_RC);
   1018 		f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
   1019 		if (f) {
   1020 			if (do_xauth)
   1021 				fprintf(f, "%s %s\n", s->auth_proto,
   1022 				    s->auth_data);
   1023 			pclose(f);
   1024 		} else
   1025 			fprintf(stderr, "Could not run %s\n",
   1026 			    _PATH_SSH_SYSTEM_RC);
   1027 	} else if (do_xauth && options.xauth_location != NULL) {
   1028 		/* Add authority data to .Xauthority if appropriate. */
   1029 		if (debug_flag) {
   1030 			fprintf(stderr,
   1031 			    "Running %.500s remove %.100s\n",
   1032 			    options.xauth_location, s->auth_display);
   1033 			fprintf(stderr,
   1034 			    "%.500s add %.100s %.100s %.100s\n",
   1035 			    options.xauth_location, s->auth_display,
   1036 			    s->auth_proto, s->auth_data);
   1037 		}
   1038 		snprintf(cmd, sizeof cmd, "%s -q -",
   1039 		    options.xauth_location);
   1040 		f = popen(cmd, "w");
   1041 		if (f) {
   1042 			fprintf(f, "remove %s\n",
   1043 			    s->auth_display);
   1044 			fprintf(f, "add %s %s %s\n",
   1045 			    s->auth_display, s->auth_proto,
   1046 			    s->auth_data);
   1047 			pclose(f);
   1048 		} else {
   1049 			fprintf(stderr, "Could not run %s\n",
   1050 			    cmd);
   1051 		}
   1052 	}
   1053 }
   1054 
   1055 static void
   1056 do_nologin(struct passwd *pw)
   1057 {
   1058 	FILE *f = NULL;
   1059 	char buf[1024], *nl, *def_nl = __UNCONST(_PATH_NOLOGIN);
   1060 	struct stat sb;
   1061 
   1062 #ifdef HAVE_LOGIN_CAP
   1063 	if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0)
   1064 		return;
   1065 	nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
   1066 #else
   1067 	if (pw->pw_uid == 0)
   1068 		return;
   1069 	nl = def_nl;
   1070 #endif
   1071 	if (stat(nl, &sb) == -1) {
   1072 		if (nl != def_nl)
   1073 			free(nl);
   1074 		return;
   1075 	}
   1076 
   1077 	/* /etc/nologin exists.  Print its contents if we can and exit. */
   1078 	logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
   1079 	if ((f = fopen(nl, "r")) != NULL) {
   1080 		while (fgets(buf, sizeof(buf), f))
   1081 			fputs(buf, stderr);
   1082 		fclose(f);
   1083 	}
   1084 	exit(254);
   1085 }
   1086 
   1087 /*
   1088  * Chroot into a directory after checking it for safety: all path components
   1089  * must be root-owned directories with strict permissions.
   1090  */
   1091 static void
   1092 safely_chroot(const char *path, uid_t uid)
   1093 {
   1094 	const char *cp;
   1095 	char component[PATH_MAX];
   1096 	struct stat st;
   1097 
   1098 	if (*path != '/')
   1099 		fatal("chroot path does not begin at root");
   1100 	if (strlen(path) >= sizeof(component))
   1101 		fatal("chroot path too long");
   1102 
   1103 	/*
   1104 	 * Descend the path, checking that each component is a
   1105 	 * root-owned directory with strict permissions.
   1106 	 */
   1107 	for (cp = path; cp != NULL;) {
   1108 		if ((cp = strchr(cp, '/')) == NULL)
   1109 			strlcpy(component, path, sizeof(component));
   1110 		else {
   1111 			cp++;
   1112 			memcpy(component, path, cp - path);
   1113 			component[cp - path] = '\0';
   1114 		}
   1115 
   1116 		debug3("%s: checking '%s'", __func__, component);
   1117 
   1118 		if (stat(component, &st) != 0)
   1119 			fatal("%s: stat(\"%s\"): %s", __func__,
   1120 			    component, strerror(errno));
   1121 		if (st.st_uid != 0 || (st.st_mode & 022) != 0)
   1122 			fatal("bad ownership or modes for chroot "
   1123 			    "directory %s\"%s\"",
   1124 			    cp == NULL ? "" : "component ", component);
   1125 		if (!S_ISDIR(st.st_mode))
   1126 			fatal("chroot path %s\"%s\" is not a directory",
   1127 			    cp == NULL ? "" : "component ", component);
   1128 
   1129 	}
   1130 
   1131 	if (chdir(path) == -1)
   1132 		fatal("Unable to chdir to chroot path \"%s\": "
   1133 		    "%s", path, strerror(errno));
   1134 	if (chroot(path) == -1)
   1135 		fatal("chroot(\"%s\"): %s", path, strerror(errno));
   1136 	if (chdir("/") == -1)
   1137 		fatal("%s: chdir(/) after chroot: %s",
   1138 		    __func__, strerror(errno));
   1139 	verbose("Changed root directory to \"%s\"", path);
   1140 }
   1141 
   1142 /* Set login name, uid, gid, and groups. */
   1143 void
   1144 do_setusercontext(struct passwd *pw)
   1145 {
   1146 	char *chroot_path, *tmp;
   1147 
   1148 	if (getuid() == 0 || geteuid() == 0) {
   1149 #ifdef HAVE_LOGIN_CAP
   1150 # ifdef USE_PAM
   1151 		if (options.use_pam) {
   1152 			do_pam_setcred(use_privsep);
   1153 		}
   1154 # endif /* USE_PAM */
   1155 		/* Prepare groups */
   1156 		if (setusercontext(lc, pw, pw->pw_uid,
   1157 		    (LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
   1158 			perror("unable to set user context");
   1159 			exit(1);
   1160 		}
   1161 #else
   1162 
   1163 		if (setlogin(pw->pw_name) < 0)
   1164 			error("setlogin failed: %s", strerror(errno));
   1165 		if (setgid(pw->pw_gid) < 0) {
   1166 			perror("setgid");
   1167 			exit(1);
   1168 		}
   1169 		/* Initialize the group list. */
   1170 		if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
   1171 			perror("initgroups");
   1172 			exit(1);
   1173 		}
   1174 		endgrent();
   1175 # ifdef USE_PAM
   1176 		/*
   1177 		 * PAM credentials may take the form of supplementary groups.
   1178 		 * These will have been wiped by the above initgroups() call.
   1179 		 * Reestablish them here.
   1180 		 */
   1181 		if (options.use_pam) {
   1182 			do_pam_setcred(use_privsep);
   1183 		}
   1184 # endif /* USE_PAM */
   1185 #endif
   1186 		if (!in_chroot && options.chroot_directory != NULL &&
   1187 		    strcasecmp(options.chroot_directory, "none") != 0) {
   1188                         tmp = tilde_expand_filename(options.chroot_directory,
   1189 			    pw->pw_uid);
   1190 			chroot_path = percent_expand(tmp, "h", pw->pw_dir,
   1191 			    "u", pw->pw_name, (char *)NULL);
   1192 			safely_chroot(chroot_path, pw->pw_uid);
   1193 			free(tmp);
   1194 			free(chroot_path);
   1195 			/* Make sure we don't attempt to chroot again */
   1196 			free(options.chroot_directory);
   1197 			options.chroot_directory = NULL;
   1198 			in_chroot = 1;
   1199 		}
   1200 
   1201 #ifdef HAVE_LOGIN_CAP
   1202 		/* Set UID */
   1203 		if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
   1204 			perror("unable to set user context (setuser)");
   1205 			exit(1);
   1206 		}
   1207 #else
   1208 		/* Permanently switch to the desired uid. */
   1209 		permanently_set_uid(pw);
   1210 #endif
   1211 	} else if (options.chroot_directory != NULL &&
   1212 	    strcasecmp(options.chroot_directory, "none") != 0) {
   1213 		fatal("server lacks privileges to chroot to ChrootDirectory");
   1214 	}
   1215 
   1216 	if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
   1217 		fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
   1218 }
   1219 
   1220 __dead static void
   1221 do_pwchange(Session *s)
   1222 {
   1223 	fflush(NULL);
   1224 	fprintf(stderr, "WARNING: Your password has expired.\n");
   1225 	if (s->ttyfd != -1) {
   1226 		fprintf(stderr,
   1227 		    "You must change your password now and login again!\n");
   1228 		execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
   1229 		perror("passwd");
   1230 	} else {
   1231 		fprintf(stderr,
   1232 		    "Password change required but no TTY available.\n");
   1233 	}
   1234 	exit(1);
   1235 }
   1236 
   1237 static void
   1238 child_close_fds(void)
   1239 {
   1240 	extern int auth_sock;
   1241 
   1242 	if (auth_sock != -1) {
   1243 		close(auth_sock);
   1244 		auth_sock = -1;
   1245 	}
   1246 
   1247 	if (packet_get_connection_in() == packet_get_connection_out())
   1248 		close(packet_get_connection_in());
   1249 	else {
   1250 		close(packet_get_connection_in());
   1251 		close(packet_get_connection_out());
   1252 	}
   1253 	/*
   1254 	 * Close all descriptors related to channels.  They will still remain
   1255 	 * open in the parent.
   1256 	 */
   1257 	/* XXX better use close-on-exec? -markus */
   1258 	channel_close_all();
   1259 
   1260 	/*
   1261 	 * Close any extra file descriptors.  Note that there may still be
   1262 	 * descriptors left by system functions.  They will be closed later.
   1263 	 */
   1264 	endpwent();
   1265 
   1266 	/*
   1267 	 * Close any extra open file descriptors so that we don't have them
   1268 	 * hanging around in clients.  Note that we want to do this after
   1269 	 * initgroups, because at least on Solaris 2.3 it leaves file
   1270 	 * descriptors open.
   1271 	 */
   1272 	(void)closefrom(STDERR_FILENO + 1);
   1273 }
   1274 
   1275 /*
   1276  * Performs common processing for the child, such as setting up the
   1277  * environment, closing extra file descriptors, setting the user and group
   1278  * ids, and executing the command or shell.
   1279  */
   1280 #define ARGV_MAX 10
   1281 void
   1282 do_child(Session *s, const char *command)
   1283 {
   1284 	extern char **environ;
   1285 	char **env;
   1286 	char *argv[ARGV_MAX];
   1287 	const char *shell, *shell0;
   1288 	struct passwd *pw = s->pw;
   1289 	int r = 0;
   1290 
   1291 	/* remove hostkey from the child's memory */
   1292 	destroy_sensitive_data();
   1293 
   1294 	/* Force a password change */
   1295 	if (s->authctxt->force_pwchange) {
   1296 		do_setusercontext(pw);
   1297 		child_close_fds();
   1298 		do_pwchange(s);
   1299 	}
   1300 
   1301 	/*
   1302 	 * Login(1) does this as well, and it needs uid 0 for the "-h"
   1303 	 * switch, so we let login(1) to this for us.
   1304 	 */
   1305 #ifdef USE_PAM
   1306 	if (options.use_pam && !is_pam_session_open()) {
   1307 		debug3("PAM session not opened, exiting");
   1308 		display_loginmsg();
   1309 		exit(254);
   1310 	}
   1311 #endif
   1312 	do_nologin(pw);
   1313 	do_setusercontext(pw);
   1314 
   1315 	/*
   1316 	 * Get the shell from the password data.  An empty shell field is
   1317 	 * legal, and means /bin/sh.
   1318 	 */
   1319 	shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
   1320 
   1321 	/*
   1322 	 * Make sure $SHELL points to the shell from the password file,
   1323 	 * even if shell is overridden from login.conf
   1324 	 */
   1325 	env = do_setup_env(s, shell);
   1326 
   1327 #ifdef HAVE_LOGIN_CAP
   1328 	shell = login_getcapstr(lc, "shell", __UNCONST(shell),
   1329 	    __UNCONST(shell));
   1330 #endif
   1331 
   1332 	/*
   1333 	 * Close the connection descriptors; note that this is the child, and
   1334 	 * the server will still have the socket open, and it is important
   1335 	 * that we do not shutdown it.  Note that the descriptors cannot be
   1336 	 * closed before building the environment, as we call
   1337 	 * ssh_remote_ipaddr there.
   1338 	 */
   1339 	child_close_fds();
   1340 
   1341 	/*
   1342 	 * Must take new environment into use so that .ssh/rc,
   1343 	 * /etc/ssh/sshrc and xauth are run in the proper environment.
   1344 	 */
   1345 	environ = env;
   1346 
   1347 #ifdef KRB5
   1348 	/*
   1349 	 * At this point, we check to see if AFS is active and if we have
   1350 	 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
   1351 	 * if we can (and need to) extend the ticket into an AFS token. If
   1352 	 * we don't do this, we run into potential problems if the user's
   1353 	 * home directory is in AFS and it's not world-readable.
   1354 	 */
   1355 
   1356 	if (options.kerberos_get_afs_token && k_hasafs() &&
   1357 	    (s->authctxt->krb5_ctx != NULL)) {
   1358 		char cell[64];
   1359 
   1360 		debug("Getting AFS token");
   1361 
   1362 		k_setpag();
   1363 
   1364 		if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
   1365 			krb5_afslog(s->authctxt->krb5_ctx,
   1366 			    s->authctxt->krb5_fwd_ccache, cell, NULL);
   1367 
   1368 		krb5_afslog_home(s->authctxt->krb5_ctx,
   1369 		    s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
   1370 	}
   1371 #endif
   1372 
   1373 	/* Change current directory to the user's home directory. */
   1374 	if (chdir(pw->pw_dir) < 0) {
   1375 		/* Suppress missing homedir warning for chroot case */
   1376 		r = login_getcapbool(lc, "requirehome", 0);
   1377 		if (r || !in_chroot) {
   1378 			fprintf(stderr, "Could not chdir to home "
   1379 			    "directory %s: %s\n", pw->pw_dir,
   1380 			    strerror(errno));
   1381 		}
   1382 		if (r)
   1383 			exit(1);
   1384 	}
   1385 
   1386 	(void)closefrom(STDERR_FILENO + 1);
   1387 
   1388 	do_rc_files(s, shell);
   1389 
   1390 	/* restore SIGPIPE for child */
   1391 	signal(SIGPIPE, SIG_DFL);
   1392 
   1393 	if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
   1394 		printf("This service allows sftp connections only.\n");
   1395 		fflush(NULL);
   1396 		exit(1);
   1397 	} else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
   1398 		extern int optind, optreset;
   1399 		int i;
   1400 		char *p, *args;
   1401 
   1402 		setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
   1403 		args = xstrdup(command ? command : "sftp-server");
   1404 		for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
   1405 			if (i < ARGV_MAX - 1)
   1406 				argv[i++] = p;
   1407 		argv[i] = NULL;
   1408 		optind = optreset = 1;
   1409 		__progname = argv[0];
   1410 		exit(sftp_server_main(i, argv, s->pw));
   1411 	}
   1412 
   1413 	fflush(NULL);
   1414 
   1415 	/* Get the last component of the shell name. */
   1416 	if ((shell0 = strrchr(shell, '/')) != NULL)
   1417 		shell0++;
   1418 	else
   1419 		shell0 = shell;
   1420 
   1421 	/*
   1422 	 * If we have no command, execute the shell.  In this case, the shell
   1423 	 * name to be passed in argv[0] is preceded by '-' to indicate that
   1424 	 * this is a login shell.
   1425 	 */
   1426 	if (!command) {
   1427 		char argv0[256];
   1428 
   1429 		/* Start the shell.  Set initial character to '-'. */
   1430 		argv0[0] = '-';
   1431 
   1432 		if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
   1433 		    >= sizeof(argv0) - 1) {
   1434 			errno = EINVAL;
   1435 			perror(shell);
   1436 			exit(1);
   1437 		}
   1438 
   1439 		/* Execute the shell. */
   1440 		argv[0] = argv0;
   1441 		argv[1] = NULL;
   1442 		execve(shell, argv, env);
   1443 
   1444 		/* Executing the shell failed. */
   1445 		perror(shell);
   1446 		exit(1);
   1447 	}
   1448 	/*
   1449 	 * Execute the command using the user's shell.  This uses the -c
   1450 	 * option to execute the command.
   1451 	 */
   1452 	argv[0] = __UNCONST(shell0);
   1453 	argv[1] = __UNCONST("-c");
   1454 	argv[2] = __UNCONST(command);
   1455 	argv[3] = NULL;
   1456 	execve(shell, argv, env);
   1457 	perror(shell);
   1458 	exit(1);
   1459 }
   1460 
   1461 void
   1462 session_unused(int id)
   1463 {
   1464 	debug3("%s: session id %d unused", __func__, id);
   1465 	if (id >= options.max_sessions ||
   1466 	    id >= sessions_nalloc) {
   1467 		fatal("%s: insane session id %d (max %d nalloc %d)",
   1468 		    __func__, id, options.max_sessions, sessions_nalloc);
   1469 	}
   1470 	memset(&sessions[id], 0, sizeof(*sessions));
   1471 	sessions[id].self = id;
   1472 	sessions[id].used = 0;
   1473 	sessions[id].chanid = -1;
   1474 	sessions[id].ptyfd = -1;
   1475 	sessions[id].ttyfd = -1;
   1476 	sessions[id].ptymaster = -1;
   1477 	sessions[id].x11_chanids = NULL;
   1478 	sessions[id].next_unused = sessions_first_unused;
   1479 	sessions_first_unused = id;
   1480 }
   1481 
   1482 Session *
   1483 session_new(void)
   1484 {
   1485 	Session *s, *tmp;
   1486 
   1487 	if (sessions_first_unused == -1) {
   1488 		if (sessions_nalloc >= options.max_sessions)
   1489 			return NULL;
   1490 		debug2("%s: allocate (allocated %d max %d)",
   1491 		    __func__, sessions_nalloc, options.max_sessions);
   1492 		tmp = xreallocarray(sessions, sessions_nalloc + 1,
   1493 		    sizeof(*sessions));
   1494 		if (tmp == NULL) {
   1495 			error("%s: cannot allocate %d sessions",
   1496 			    __func__, sessions_nalloc + 1);
   1497 			return NULL;
   1498 		}
   1499 		sessions = tmp;
   1500 		session_unused(sessions_nalloc++);
   1501 	}
   1502 
   1503 	if (sessions_first_unused >= sessions_nalloc ||
   1504 	    sessions_first_unused < 0) {
   1505 		fatal("%s: insane first_unused %d max %d nalloc %d",
   1506 		    __func__, sessions_first_unused, options.max_sessions,
   1507 		    sessions_nalloc);
   1508 	}
   1509 
   1510 	s = &sessions[sessions_first_unused];
   1511 	if (s->used) {
   1512 		fatal("%s: session %d already used",
   1513 		    __func__, sessions_first_unused);
   1514 	}
   1515 	sessions_first_unused = s->next_unused;
   1516 	s->used = 1;
   1517 	s->next_unused = -1;
   1518 	debug("session_new: session %d", s->self);
   1519 
   1520 	return s;
   1521 }
   1522 
   1523 static void
   1524 session_dump(void)
   1525 {
   1526 	int i;
   1527 	for (i = 0; i < sessions_nalloc; i++) {
   1528 		Session *s = &sessions[i];
   1529 
   1530 		debug("dump: used %d next_unused %d session %d %p "
   1531 		    "channel %d pid %ld",
   1532 		    s->used,
   1533 		    s->next_unused,
   1534 		    s->self,
   1535 		    s,
   1536 		    s->chanid,
   1537 		    (long)s->pid);
   1538 	}
   1539 }
   1540 
   1541 int
   1542 session_open(Authctxt *authctxt, int chanid)
   1543 {
   1544 	Session *s = session_new();
   1545 	debug("session_open: channel %d", chanid);
   1546 	if (s == NULL) {
   1547 		error("no more sessions");
   1548 		return 0;
   1549 	}
   1550 	s->authctxt = authctxt;
   1551 	s->pw = authctxt->pw;
   1552 	if (s->pw == NULL || !authctxt->valid)
   1553 		fatal("no user for session %d", s->self);
   1554 	debug("session_open: session %d: link with channel %d", s->self, chanid);
   1555 	s->chanid = chanid;
   1556 	return 1;
   1557 }
   1558 
   1559 Session *
   1560 session_by_tty(char *tty)
   1561 {
   1562 	int i;
   1563 	for (i = 0; i < sessions_nalloc; i++) {
   1564 		Session *s = &sessions[i];
   1565 		if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
   1566 			debug("session_by_tty: session %d tty %s", i, tty);
   1567 			return s;
   1568 		}
   1569 	}
   1570 	debug("session_by_tty: unknown tty %.100s", tty);
   1571 	session_dump();
   1572 	return NULL;
   1573 }
   1574 
   1575 static Session *
   1576 session_by_channel(int id)
   1577 {
   1578 	int i;
   1579 	for (i = 0; i < sessions_nalloc; i++) {
   1580 		Session *s = &sessions[i];
   1581 		if (s->used && s->chanid == id) {
   1582 			debug("session_by_channel: session %d channel %d",
   1583 			    i, id);
   1584 			return s;
   1585 		}
   1586 	}
   1587 	debug("session_by_channel: unknown channel %d", id);
   1588 	session_dump();
   1589 	return NULL;
   1590 }
   1591 
   1592 static Session *
   1593 session_by_x11_channel(int id)
   1594 {
   1595 	int i, j;
   1596 
   1597 	for (i = 0; i < sessions_nalloc; i++) {
   1598 		Session *s = &sessions[i];
   1599 
   1600 		if (s->x11_chanids == NULL || !s->used)
   1601 			continue;
   1602 		for (j = 0; s->x11_chanids[j] != -1; j++) {
   1603 			if (s->x11_chanids[j] == id) {
   1604 				debug("session_by_x11_channel: session %d "
   1605 				    "channel %d", s->self, id);
   1606 				return s;
   1607 			}
   1608 		}
   1609 	}
   1610 	debug("session_by_x11_channel: unknown channel %d", id);
   1611 	session_dump();
   1612 	return NULL;
   1613 }
   1614 
   1615 static Session *
   1616 session_by_pid(pid_t pid)
   1617 {
   1618 	int i;
   1619 	debug("session_by_pid: pid %ld", (long)pid);
   1620 	for (i = 0; i < sessions_nalloc; i++) {
   1621 		Session *s = &sessions[i];
   1622 		if (s->used && s->pid == pid)
   1623 			return s;
   1624 	}
   1625 	error("session_by_pid: unknown pid %ld", (long)pid);
   1626 	session_dump();
   1627 	return NULL;
   1628 }
   1629 
   1630 static int
   1631 session_window_change_req(Session *s)
   1632 {
   1633 	s->col = packet_get_int();
   1634 	s->row = packet_get_int();
   1635 	s->xpixel = packet_get_int();
   1636 	s->ypixel = packet_get_int();
   1637 	packet_check_eom();
   1638 	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
   1639 	return 1;
   1640 }
   1641 
   1642 static int
   1643 session_pty_req(Session *s)
   1644 {
   1645 	u_int len;
   1646 	int n_bytes;
   1647 
   1648 	if (no_pty_flag || !options.permit_tty) {
   1649 		debug("Allocating a pty not permitted for this authentication.");
   1650 		return 0;
   1651 	}
   1652 	if (s->ttyfd != -1) {
   1653 		packet_disconnect("Protocol error: you already have a pty.");
   1654 		return 0;
   1655 	}
   1656 
   1657 	s->term = packet_get_string(&len);
   1658 	s->col = packet_get_int();
   1659 	s->row = packet_get_int();
   1660 	s->xpixel = packet_get_int();
   1661 	s->ypixel = packet_get_int();
   1662 
   1663 	if (strcmp(s->term, "") == 0) {
   1664 		free(s->term);
   1665 		s->term = NULL;
   1666 	}
   1667 
   1668 	/* Allocate a pty and open it. */
   1669 	debug("Allocating pty.");
   1670 	if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
   1671 	    sizeof(s->tty)))) {
   1672 		free(s->term);
   1673 		s->term = NULL;
   1674 		s->ptyfd = -1;
   1675 		s->ttyfd = -1;
   1676 		error("session_pty_req: session %d alloc failed", s->self);
   1677 		return 0;
   1678 	}
   1679 	debug("session_pty_req: session %d alloc %s", s->self, s->tty);
   1680 
   1681 	n_bytes = packet_remaining();
   1682 	tty_parse_modes(s->ttyfd, &n_bytes);
   1683 
   1684 	if (!use_privsep)
   1685 		pty_setowner(s->pw, s->tty);
   1686 
   1687 	/* Set window size from the packet. */
   1688 	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
   1689 
   1690 	packet_check_eom();
   1691 	session_proctitle(s);
   1692 	return 1;
   1693 }
   1694 
   1695 static int
   1696 session_subsystem_req(Session *s)
   1697 {
   1698 	struct stat st;
   1699 	u_int len;
   1700 	int success = 0;
   1701 	char *prog, *cmd;
   1702 	u_int i;
   1703 
   1704 	s->subsys = packet_get_string(&len);
   1705 	packet_check_eom();
   1706 	debug2("subsystem request for %.100s by user %s", s->subsys,
   1707 	    s->pw->pw_name);
   1708 
   1709 	for (i = 0; i < options.num_subsystems; i++) {
   1710 		if (strcmp(s->subsys, options.subsystem_name[i]) == 0) {
   1711 			prog = options.subsystem_command[i];
   1712 			cmd = options.subsystem_args[i];
   1713 			if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
   1714 				s->is_subsystem = SUBSYSTEM_INT_SFTP;
   1715 				debug("subsystem: %s", prog);
   1716 			} else {
   1717 				if (stat(prog, &st) < 0)
   1718 					debug("subsystem: cannot stat %s: %s",
   1719 					    prog, strerror(errno));
   1720 				s->is_subsystem = SUBSYSTEM_EXT;
   1721 				debug("subsystem: exec() %s", cmd);
   1722 			}
   1723 			success = do_exec(s, cmd) == 0;
   1724 			break;
   1725 		}
   1726 	}
   1727 
   1728 	if (!success)
   1729 		logit("subsystem request for %.100s by user %s failed, "
   1730 		    "subsystem not found", s->subsys, s->pw->pw_name);
   1731 
   1732 	return success;
   1733 }
   1734 
   1735 static int
   1736 session_x11_req(Session *s)
   1737 {
   1738 	int success;
   1739 
   1740 	if (s->auth_proto != NULL || s->auth_data != NULL) {
   1741 		error("session_x11_req: session %d: "
   1742 		    "x11 forwarding already active", s->self);
   1743 		return 0;
   1744 	}
   1745 	s->single_connection = packet_get_char();
   1746 	s->auth_proto = packet_get_string(NULL);
   1747 	s->auth_data = packet_get_string(NULL);
   1748 	s->screen = packet_get_int();
   1749 	packet_check_eom();
   1750 
   1751 	if (xauth_valid_string(s->auth_proto) &&
   1752 	    xauth_valid_string(s->auth_data))
   1753 		success = session_setup_x11fwd(s);
   1754 	else {
   1755 		success = 0;
   1756 		error("Invalid X11 forwarding data");
   1757 	}
   1758 	if (!success) {
   1759 		free(s->auth_proto);
   1760 		free(s->auth_data);
   1761 		s->auth_proto = NULL;
   1762 		s->auth_data = NULL;
   1763 	}
   1764 	return success;
   1765 }
   1766 
   1767 static int
   1768 session_shell_req(Session *s)
   1769 {
   1770 	packet_check_eom();
   1771 	return do_exec(s, NULL) == 0;
   1772 }
   1773 
   1774 static int
   1775 session_exec_req(Session *s)
   1776 {
   1777 	u_int len, success;
   1778 
   1779 	char *command = packet_get_string(&len);
   1780 	packet_check_eom();
   1781 	success = do_exec(s, command) == 0;
   1782 	free(command);
   1783 	return success;
   1784 }
   1785 
   1786 static int
   1787 session_break_req(Session *s)
   1788 {
   1789 
   1790 	packet_get_int();	/* ignored */
   1791 	packet_check_eom();
   1792 
   1793 	if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) < 0)
   1794 		return 0;
   1795 	return 1;
   1796 }
   1797 
   1798 static int
   1799 session_env_req(Session *s)
   1800 {
   1801 	char *name, *val;
   1802 	u_int name_len, val_len, i;
   1803 
   1804 	name = packet_get_cstring(&name_len);
   1805 	val = packet_get_cstring(&val_len);
   1806 	packet_check_eom();
   1807 
   1808 	/* Don't set too many environment variables */
   1809 	if (s->num_env > 128) {
   1810 		debug2("Ignoring env request %s: too many env vars", name);
   1811 		goto fail;
   1812 	}
   1813 
   1814 	for (i = 0; i < options.num_accept_env; i++) {
   1815 		if (match_pattern(name, options.accept_env[i])) {
   1816 			debug2("Setting env %d: %s=%s", s->num_env, name, val);
   1817 			s->env = xreallocarray(s->env, s->num_env + 1,
   1818 			    sizeof(*s->env));
   1819 			s->env[s->num_env].name = name;
   1820 			s->env[s->num_env].val = val;
   1821 			s->num_env++;
   1822 			return (1);
   1823 		}
   1824 	}
   1825 	debug2("Ignoring env request %s: disallowed name", name);
   1826 
   1827  fail:
   1828 	free(name);
   1829 	free(val);
   1830 	return (0);
   1831 }
   1832 
   1833 static int
   1834 session_auth_agent_req(Session *s)
   1835 {
   1836 	static int called = 0;
   1837 	packet_check_eom();
   1838 	if (no_agent_forwarding_flag || !options.allow_agent_forwarding) {
   1839 		debug("session_auth_agent_req: no_agent_forwarding_flag");
   1840 		return 0;
   1841 	}
   1842 	if (called) {
   1843 		return 0;
   1844 	} else {
   1845 		called = 1;
   1846 		return auth_input_request_forwarding(s->pw);
   1847 	}
   1848 }
   1849 
   1850 int
   1851 session_input_channel_req(Channel *c, const char *rtype)
   1852 {
   1853 	int success = 0;
   1854 	Session *s;
   1855 
   1856 	if ((s = session_by_channel(c->self)) == NULL) {
   1857 		logit("session_input_channel_req: no session %d req %.100s",
   1858 		    c->self, rtype);
   1859 		return 0;
   1860 	}
   1861 	debug("session_input_channel_req: session %d req %s", s->self, rtype);
   1862 
   1863 	/*
   1864 	 * a session is in LARVAL state until a shell, a command
   1865 	 * or a subsystem is executed
   1866 	 */
   1867 	if (c->type == SSH_CHANNEL_LARVAL) {
   1868 		if (strcmp(rtype, "shell") == 0) {
   1869 			success = session_shell_req(s);
   1870 		} else if (strcmp(rtype, "exec") == 0) {
   1871 			success = session_exec_req(s);
   1872 		} else if (strcmp(rtype, "pty-req") == 0) {
   1873 			success = session_pty_req(s);
   1874 		} else if (strcmp(rtype, "x11-req") == 0) {
   1875 			success = session_x11_req(s);
   1876 		} else if (strcmp(rtype, "auth-agent-req (at) openssh.com") == 0) {
   1877 			success = session_auth_agent_req(s);
   1878 		} else if (strcmp(rtype, "subsystem") == 0) {
   1879 			success = session_subsystem_req(s);
   1880 		} else if (strcmp(rtype, "env") == 0) {
   1881 			success = session_env_req(s);
   1882 		}
   1883 	}
   1884 	if (strcmp(rtype, "window-change") == 0) {
   1885 		success = session_window_change_req(s);
   1886 	} else if (strcmp(rtype, "break") == 0) {
   1887 		success = session_break_req(s);
   1888 	}
   1889 
   1890 	return success;
   1891 }
   1892 
   1893 void
   1894 session_set_fds(Session *s, int fdin, int fdout, int fderr, int ignore_fderr,
   1895     int is_tty)
   1896 {
   1897 	/*
   1898 	 * now that have a child and a pipe to the child,
   1899 	 * we can activate our channel and register the fd's
   1900 	 */
   1901 	if (s->chanid == -1)
   1902 		fatal("no channel for session %d", s->self);
   1903 	if(options.hpn_disabled)
   1904 	channel_set_fds(s->chanid,
   1905 	    fdout, fdin, fderr,
   1906 	    ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
   1907 	    1, is_tty, CHAN_SES_WINDOW_DEFAULT);
   1908 	else
   1909 		channel_set_fds(s->chanid,
   1910 		    fdout, fdin, fderr,
   1911 	            ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
   1912 		    1, is_tty, options.hpn_buffer_size);
   1913 }
   1914 
   1915 /*
   1916  * Function to perform pty cleanup. Also called if we get aborted abnormally
   1917  * (e.g., due to a dropped connection).
   1918  */
   1919 void
   1920 session_pty_cleanup2(Session *s)
   1921 {
   1922 	if (s == NULL) {
   1923 		error("session_pty_cleanup: no session");
   1924 		return;
   1925 	}
   1926 	if (s->ttyfd == -1)
   1927 		return;
   1928 
   1929 	debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
   1930 
   1931 	/* Record that the user has logged out. */
   1932 	if (s->pid != 0)
   1933 		record_logout(s->pid, s->tty);
   1934 
   1935 	/* Release the pseudo-tty. */
   1936 	if (getuid() == 0)
   1937 		pty_release(s->tty);
   1938 
   1939 	/*
   1940 	 * Close the server side of the socket pairs.  We must do this after
   1941 	 * the pty cleanup, so that another process doesn't get this pty
   1942 	 * while we're still cleaning up.
   1943 	 */
   1944 	if (s->ptymaster != -1 && close(s->ptymaster) < 0)
   1945 		error("close(s->ptymaster/%d): %s",
   1946 		    s->ptymaster, strerror(errno));
   1947 
   1948 	/* unlink pty from session */
   1949 	s->ttyfd = -1;
   1950 }
   1951 
   1952 void
   1953 session_pty_cleanup(Session *s)
   1954 {
   1955 	PRIVSEP(session_pty_cleanup2(s));
   1956 }
   1957 
   1958 static const char *
   1959 sig2name(int sig)
   1960 {
   1961 #define SSH_SIG(x) if (sig == SIG ## x) return #x
   1962 	SSH_SIG(ABRT);
   1963 	SSH_SIG(ALRM);
   1964 	SSH_SIG(FPE);
   1965 	SSH_SIG(HUP);
   1966 	SSH_SIG(ILL);
   1967 	SSH_SIG(INT);
   1968 	SSH_SIG(KILL);
   1969 	SSH_SIG(PIPE);
   1970 	SSH_SIG(QUIT);
   1971 	SSH_SIG(SEGV);
   1972 	SSH_SIG(TERM);
   1973 	SSH_SIG(USR1);
   1974 	SSH_SIG(USR2);
   1975 #undef	SSH_SIG
   1976 	return "SIG (at) openssh.com";
   1977 }
   1978 
   1979 static void
   1980 session_close_x11(int id)
   1981 {
   1982 	Channel *c;
   1983 
   1984 	if ((c = channel_by_id(id)) == NULL) {
   1985 		debug("session_close_x11: x11 channel %d missing", id);
   1986 	} else {
   1987 		/* Detach X11 listener */
   1988 		debug("session_close_x11: detach x11 channel %d", id);
   1989 		channel_cancel_cleanup(id);
   1990 		if (c->ostate != CHAN_OUTPUT_CLOSED)
   1991 			chan_mark_dead(c);
   1992 	}
   1993 }
   1994 
   1995 static void
   1996 session_close_single_x11(int id, void *arg)
   1997 {
   1998 	Session *s;
   1999 	u_int i;
   2000 
   2001 	debug3("session_close_single_x11: channel %d", id);
   2002 	channel_cancel_cleanup(id);
   2003 	if ((s = session_by_x11_channel(id)) == NULL)
   2004 		fatal("session_close_single_x11: no x11 channel %d", id);
   2005 	for (i = 0; s->x11_chanids[i] != -1; i++) {
   2006 		debug("session_close_single_x11: session %d: "
   2007 		    "closing channel %d", s->self, s->x11_chanids[i]);
   2008 		/*
   2009 		 * The channel "id" is already closing, but make sure we
   2010 		 * close all of its siblings.
   2011 		 */
   2012 		if (s->x11_chanids[i] != id)
   2013 			session_close_x11(s->x11_chanids[i]);
   2014 	}
   2015 	free(s->x11_chanids);
   2016 	s->x11_chanids = NULL;
   2017 	free(s->display);
   2018 	s->display = NULL;
   2019 	free(s->auth_proto);
   2020 	s->auth_proto = NULL;
   2021 	free(s->auth_data);
   2022 	s->auth_data = NULL;
   2023 	free(s->auth_display);
   2024 	s->auth_display = NULL;
   2025 }
   2026 
   2027 static void
   2028 session_exit_message(Session *s, int status)
   2029 {
   2030 	Channel *c;
   2031 
   2032 	if ((c = channel_lookup(s->chanid)) == NULL)
   2033 		fatal("session_exit_message: session %d: no channel %d",
   2034 		    s->self, s->chanid);
   2035 	debug("session_exit_message: session %d channel %d pid %ld",
   2036 	    s->self, s->chanid, (long)s->pid);
   2037 
   2038 	if (WIFEXITED(status)) {
   2039 		channel_request_start(s->chanid, "exit-status", 0);
   2040 		packet_put_int(WEXITSTATUS(status));
   2041 		packet_send();
   2042 	} else if (WIFSIGNALED(status)) {
   2043 		channel_request_start(s->chanid, "exit-signal", 0);
   2044 		packet_put_cstring(sig2name(WTERMSIG(status)));
   2045 		packet_put_char(WCOREDUMP(status)? 1 : 0);
   2046 		packet_put_cstring("");
   2047 		packet_put_cstring("");
   2048 		packet_send();
   2049 	} else {
   2050 		/* Some weird exit cause.  Just exit. */
   2051 		packet_disconnect("wait returned status %04x.", status);
   2052 	}
   2053 
   2054 	/* disconnect channel */
   2055 	debug("session_exit_message: release channel %d", s->chanid);
   2056 
   2057 	/*
   2058 	 * Adjust cleanup callback attachment to send close messages when
   2059 	 * the channel gets EOF. The session will be then be closed
   2060 	 * by session_close_by_channel when the childs close their fds.
   2061 	 */
   2062 	channel_register_cleanup(c->self, session_close_by_channel, 1);
   2063 
   2064 	/*
   2065 	 * emulate a write failure with 'chan_write_failed', nobody will be
   2066 	 * interested in data we write.
   2067 	 * Note that we must not call 'chan_read_failed', since there could
   2068 	 * be some more data waiting in the pipe.
   2069 	 */
   2070 	if (c->ostate != CHAN_OUTPUT_CLOSED)
   2071 		chan_write_failed(c);
   2072 }
   2073 
   2074 void
   2075 session_close(Session *s)
   2076 {
   2077 	struct ssh *ssh = active_state; /* XXX */
   2078 	u_int i;
   2079 
   2080 	verbose("Close session: user %s from %.200s port %d id %d",
   2081 	    s->pw->pw_name,
   2082 	    ssh_remote_ipaddr(ssh),
   2083 	    ssh_remote_port(ssh),
   2084 	    s->self);
   2085 
   2086 	if (s->ttyfd != -1)
   2087 		session_pty_cleanup(s);
   2088 	free(s->term);
   2089 	free(s->display);
   2090 	free(s->x11_chanids);
   2091 	free(s->auth_display);
   2092 	free(s->auth_data);
   2093 	free(s->auth_proto);
   2094 	free(s->subsys);
   2095 	if (s->env != NULL) {
   2096 		for (i = 0; i < s->num_env; i++) {
   2097 			free(s->env[i].name);
   2098 			free(s->env[i].val);
   2099 		}
   2100 		free(s->env);
   2101 	}
   2102 	session_proctitle(s);
   2103 	session_unused(s->self);
   2104 }
   2105 
   2106 void
   2107 session_close_by_pid(pid_t pid, int status)
   2108 {
   2109 	Session *s = session_by_pid(pid);
   2110 	if (s == NULL) {
   2111 		debug("session_close_by_pid: no session for pid %ld",
   2112 		    (long)pid);
   2113 		return;
   2114 	}
   2115 	if (s->chanid != -1)
   2116 		session_exit_message(s, status);
   2117 	if (s->ttyfd != -1)
   2118 		session_pty_cleanup(s);
   2119 	s->pid = 0;
   2120 }
   2121 
   2122 /*
   2123  * this is called when a channel dies before
   2124  * the session 'child' itself dies
   2125  */
   2126 void
   2127 session_close_by_channel(int id, void *arg)
   2128 {
   2129 	Session *s = session_by_channel(id);
   2130 	u_int i;
   2131 
   2132 	if (s == NULL) {
   2133 		debug("session_close_by_channel: no session for id %d", id);
   2134 		return;
   2135 	}
   2136 	debug("session_close_by_channel: channel %d child %ld",
   2137 	    id, (long)s->pid);
   2138 	if (s->pid != 0) {
   2139 		debug("session_close_by_channel: channel %d: has child", id);
   2140 		/*
   2141 		 * delay detach of session, but release pty, since
   2142 		 * the fd's to the child are already closed
   2143 		 */
   2144 		if (s->ttyfd != -1)
   2145 			session_pty_cleanup(s);
   2146 		return;
   2147 	}
   2148 	/* detach by removing callback */
   2149 	channel_cancel_cleanup(s->chanid);
   2150 
   2151 	/* Close any X11 listeners associated with this session */
   2152 	if (s->x11_chanids != NULL) {
   2153 		for (i = 0; s->x11_chanids[i] != -1; i++) {
   2154 			session_close_x11(s->x11_chanids[i]);
   2155 			s->x11_chanids[i] = -1;
   2156 		}
   2157 	}
   2158 
   2159 	s->chanid = -1;
   2160 	session_close(s);
   2161 }
   2162 
   2163 void
   2164 session_destroy_all(void (*closefunc)(Session *))
   2165 {
   2166 	int i;
   2167 	for (i = 0; i < sessions_nalloc; i++) {
   2168 		Session *s = &sessions[i];
   2169 		if (s->used) {
   2170 			if (closefunc != NULL)
   2171 				closefunc(s);
   2172 			else
   2173 				session_close(s);
   2174 		}
   2175 	}
   2176 }
   2177 
   2178 static char *
   2179 session_tty_list(void)
   2180 {
   2181 	static char buf[1024];
   2182 	int i;
   2183 	buf[0] = '\0';
   2184 	for (i = 0; i < sessions_nalloc; i++) {
   2185 		Session *s = &sessions[i];
   2186 		if (s->used && s->ttyfd != -1) {
   2187 			char *p;
   2188 			if (buf[0] != '\0')
   2189 				strlcat(buf, ",", sizeof buf);
   2190 			if ((p = strstr(s->tty, "/pts/")) != NULL)
   2191 				p++;
   2192 			else {
   2193 				if ((p = strrchr(s->tty, '/')) != NULL)
   2194 					p++;
   2195 				else
   2196 					p = s->tty;
   2197 			}
   2198 			strlcat(buf, p, sizeof buf);
   2199 		}
   2200 	}
   2201 	if (buf[0] == '\0')
   2202 		strlcpy(buf, "notty", sizeof buf);
   2203 	return buf;
   2204 }
   2205 
   2206 void
   2207 session_proctitle(Session *s)
   2208 {
   2209 	if (s->pw == NULL)
   2210 		error("no user for session %d", s->self);
   2211 	else
   2212 		setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
   2213 }
   2214 
   2215 int
   2216 session_setup_x11fwd(Session *s)
   2217 {
   2218 	struct stat st;
   2219 	char display[512], auth_display[512];
   2220 	char hostname[NI_MAXHOST];
   2221 	u_int i;
   2222 
   2223 	if (no_x11_forwarding_flag) {
   2224 		packet_send_debug("X11 forwarding disabled in user configuration file.");
   2225 		return 0;
   2226 	}
   2227 	if (!options.x11_forwarding) {
   2228 		debug("X11 forwarding disabled in server configuration file.");
   2229 		return 0;
   2230 	}
   2231 	if (options.xauth_location == NULL ||
   2232 	    (stat(options.xauth_location, &st) == -1)) {
   2233 		packet_send_debug("No xauth program; cannot forward with spoofing.");
   2234 		return 0;
   2235 	}
   2236 	if (s->display != NULL) {
   2237 		debug("X11 display already set.");
   2238 		return 0;
   2239 	}
   2240 	if (x11_create_display_inet(options.x11_display_offset,
   2241 	    options.x11_use_localhost, s->single_connection,
   2242 	    &s->display_number, &s->x11_chanids) == -1) {
   2243 		debug("x11_create_display_inet failed.");
   2244 		return 0;
   2245 	}
   2246 	for (i = 0; s->x11_chanids[i] != -1; i++) {
   2247 		channel_register_cleanup(s->x11_chanids[i],
   2248 		    session_close_single_x11, 0);
   2249 	}
   2250 
   2251 	/* Set up a suitable value for the DISPLAY variable. */
   2252 	if (gethostname(hostname, sizeof(hostname)) < 0)
   2253 		fatal("gethostname: %.100s", strerror(errno));
   2254 	/*
   2255 	 * auth_display must be used as the displayname when the
   2256 	 * authorization entry is added with xauth(1).  This will be
   2257 	 * different than the DISPLAY string for localhost displays.
   2258 	 */
   2259 	if (options.x11_use_localhost) {
   2260 		snprintf(display, sizeof display, "localhost:%u.%u",
   2261 		    s->display_number, s->screen);
   2262 		snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
   2263 		    s->display_number, s->screen);
   2264 		s->display = xstrdup(display);
   2265 		s->auth_display = xstrdup(auth_display);
   2266 	} else {
   2267 		snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
   2268 		    s->display_number, s->screen);
   2269 		s->display = xstrdup(display);
   2270 		s->auth_display = xstrdup(display);
   2271 	}
   2272 
   2273 	return 1;
   2274 }
   2275 
   2276 static void
   2277 do_authenticated2(Authctxt *authctxt)
   2278 {
   2279 	server_loop2(authctxt);
   2280 }
   2281 
   2282 void
   2283 do_cleanup(Authctxt *authctxt)
   2284 {
   2285 	static int called = 0;
   2286 
   2287 	debug("do_cleanup");
   2288 
   2289 	/* no cleanup if we're in the child for login shell */
   2290 	if (is_child)
   2291 		return;
   2292 
   2293 	/* avoid double cleanup */
   2294 	if (called)
   2295 		return;
   2296 	called = 1;
   2297 
   2298 	if (authctxt == NULL || !authctxt->authenticated)
   2299 		return;
   2300 #ifdef KRB4
   2301 	if (options.kerberos_ticket_cleanup)
   2302 		krb4_cleanup_proc(authctxt);
   2303 #endif
   2304 #ifdef KRB5
   2305 	if (options.kerberos_ticket_cleanup &&
   2306 	    authctxt->krb5_ctx)
   2307 		krb5_cleanup_proc(authctxt);
   2308 #endif
   2309 
   2310 #ifdef GSSAPI
   2311 	if (options.gss_cleanup_creds)
   2312 		ssh_gssapi_cleanup_creds();
   2313 #endif
   2314 
   2315 #ifdef USE_PAM
   2316 	if (options.use_pam) {
   2317 		sshpam_cleanup();
   2318 		sshpam_thread_cleanup();
   2319 	}
   2320 #endif
   2321 
   2322 	/* remove agent socket */
   2323 	auth_sock_cleanup_proc(authctxt->pw);
   2324 
   2325 	/*
   2326 	 * Cleanup ptys/utmp only if privsep is disabled,
   2327 	 * or if running in monitor.
   2328 	 */
   2329 	if (!use_privsep || mm_is_monitor())
   2330 		session_destroy_all(session_pty_cleanup2);
   2331 }
   2332 
   2333 /* Return a name for the remote host that fits inside utmp_size */
   2334 
   2335 const char *
   2336 session_get_remote_name_or_ip(struct ssh *ssh, u_int utmp_size, int use_dns)
   2337 {
   2338 	const char *remote = "";
   2339 
   2340 	if (utmp_size > 0)
   2341 		remote = auth_get_canonical_hostname(ssh, use_dns);
   2342 	if (utmp_size == 0 || strlen(remote) > utmp_size)
   2343 		remote = ssh_remote_ipaddr(ssh);
   2344 	return remote;
   2345 }
   2346 
   2347