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