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