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