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