Home | History | Annotate | Line # | Download | only in dist
      1 /*	$NetBSD: serverloop.c,v 1.40 2026/04/08 18:58:41 christos Exp $	*/
      2 /* $OpenBSD: serverloop.c,v 1.246 2026/03/03 09:57:25 dtucker Exp $ */
      3 
      4 /*
      5  * Author: Tatu Ylonen <ylo (at) cs.hut.fi>
      6  * Copyright (c) 1995 Tatu Ylonen <ylo (at) cs.hut.fi>, Espoo, Finland
      7  *                    All rights reserved
      8  * Server main loop for handling the interactive session.
      9  *
     10  * As far as I am concerned, the code I have written for this software
     11  * can be used freely for any purpose.  Any derived versions of this
     12  * software must be clearly marked as such, and if the derived work is
     13  * incompatible with the protocol description in the RFC file, it must be
     14  * called by a name other than "ssh" or "Secure Shell".
     15  *
     16  * SSH2 support by Markus Friedl.
     17  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
     18  *
     19  * Redistribution and use in source and binary forms, with or without
     20  * modification, are permitted provided that the following conditions
     21  * are met:
     22  * 1. Redistributions of source code must retain the above copyright
     23  *    notice, this list of conditions and the following disclaimer.
     24  * 2. Redistributions in binary form must reproduce the above copyright
     25  *    notice, this list of conditions and the following disclaimer in the
     26  *    documentation and/or other materials provided with the distribution.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     29  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     30  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     31  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     33  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     34  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     35  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     36  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     37  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 #include "includes.h"
     41 __RCSID("$NetBSD: serverloop.c,v 1.40 2026/04/08 18:58:41 christos Exp $");
     42 
     43 #include <sys/param.h>	/* MIN MAX */
     44 #include <sys/types.h>
     45 #include <sys/wait.h>
     46 #include <sys/socket.h>
     47 #include <sys/time.h>
     48 #include <sys/queue.h>
     49 
     50 #include <netinet/in.h>
     51 
     52 #include <errno.h>
     53 #include <fcntl.h>
     54 #include <pwd.h>
     55 #include <limits.h>
     56 #include <poll.h>
     57 #include <signal.h>
     58 #include <string.h>
     59 #include <termios.h>
     60 #include <unistd.h>
     61 #include <stdarg.h>
     62 
     63 #include "xmalloc.h"
     64 #include "packet.h"
     65 #include "sshbuf.h"
     66 #include "log.h"
     67 #include "misc.h"
     68 #include "servconf.h"
     69 #include "canohost.h"
     70 #include "sshpty.h"
     71 #include "channels.h"
     72 #include "ssh2.h"
     73 #include "sshkey.h"
     74 #include "cipher.h"
     75 #include "kex.h"
     76 #include "hostfile.h"
     77 #include "auth.h"
     78 #include "session.h"
     79 #include "dispatch.h"
     80 #include "auth-options.h"
     81 #include "serverloop.h"
     82 #include "ssherr.h"
     83 
     84 static u_long stdin_bytes = 0;  /* Number of bytes written to stdin. */
     85 static u_long fdout_bytes = 0;  /* Number of stdout bytes read from program. */
     86 
     87 extern ServerOptions options;
     88 
     89 /* XXX */
     90 extern Authctxt *the_authctxt;
     91 extern struct sshauthopt *auth_opts;
     92 
     93 static int no_more_sessions = 0; /* Disallow further sessions. */
     94 
     95 static volatile sig_atomic_t child_terminated = 0; /* set on SIGCHLD */
     96 static volatile sig_atomic_t siginfo_received = 0;
     97 
     98 /* prototypes */
     99 static void server_init_dispatch(struct ssh *);
    100 
    101 /* requested tunnel forwarding interface(s), shared with session.c */
    102 char *tun_fwd_ifnames = NULL;
    103 
    104 /*
    105  * Returns current time in seconds from Jan 1, 1970 with the maximum
    106  * available resolution.
    107  */
    108 
    109 static double
    110 get_current_time(void)
    111 {
    112 	struct timeval tv;
    113 	gettimeofday(&tv, NULL);
    114 	return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
    115 }
    116 
    117 static void
    118 sigchld_handler(int sig)
    119 {
    120 	child_terminated = 1;
    121 }
    122 
    123 static void
    124 siginfo_handler(int sig)
    125 {
    126 	siginfo_received = 1;
    127 }
    128 
    129 static void
    130 client_alive_check(struct ssh *ssh)
    131 {
    132 	char remote_id[512];
    133 	int r, channel_id;
    134 
    135 	/* timeout, check to see how many we have had */
    136 	if (options.client_alive_count_max > 0 &&
    137 	    ssh_packet_inc_alive_timeouts(ssh) >
    138 	    options.client_alive_count_max) {
    139 		sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
    140 		logit("Timeout, client not responding from %s", remote_id);
    141 		cleanup_exit(255);
    142 	}
    143 
    144 	/*
    145 	 * send a bogus global/channel request with "wantreply",
    146 	 * we should get back a failure
    147 	 */
    148 	if ((channel_id = channel_find_open(ssh)) == -1) {
    149 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
    150 		    (r = sshpkt_put_cstring(ssh, "keepalive (at) openssh.com"))
    151 		    != 0 ||
    152 		    (r = sshpkt_put_u8(ssh, 1)) != 0) /* boolean: want reply */
    153 			fatal_fr(r, "compose");
    154 	} else {
    155 		channel_request_start(ssh, channel_id,
    156 		    "keepalive (at) openssh.com", 1);
    157 	}
    158 	if ((r = sshpkt_send(ssh)) != 0)
    159 		fatal_fr(r, "send");
    160 }
    161 
    162 /*
    163  * Sleep in ppoll() until we can do something.
    164  * Optionally, a maximum time can be specified for the duration of
    165  * the wait (0 = infinite).
    166  */
    167 static void
    168 wait_until_can_do_something(struct ssh *ssh,
    169     int connection_in, int connection_out, struct pollfd **pfdp,
    170     u_int *npfd_allocp, u_int *npfd_activep, sigset_t *sigsetp,
    171     int *conn_in_readyp, int *conn_out_readyp)
    172 {
    173 	struct timespec timeout;
    174 	char remote_id[512];
    175 	int ret;
    176 	int client_alive_scheduled = 0;
    177 	u_int p;
    178 	time_t now;
    179 	static time_t last_client_time, unused_connection_expiry;
    180 
    181 	*conn_in_readyp = *conn_out_readyp = 0;
    182 
    183 	/* Prepare channel poll. First two pollfd entries are reserved */
    184 	ptimeout_init(&timeout);
    185 	channel_prepare_poll(ssh, pfdp, npfd_allocp, npfd_activep, 2, &timeout);
    186 	now = monotime();
    187 	if (*npfd_activep < 2)
    188 		fatal_f("bad npfd %u", *npfd_activep); /* shouldn't happen */
    189 	if (options.rekey_interval > 0 && !ssh_packet_is_rekeying(ssh)) {
    190 		ptimeout_deadline_sec(&timeout,
    191 		    ssh_packet_get_rekey_timeout(ssh));
    192 	}
    193 
    194 	/*
    195 	 * If no channels are open and UnusedConnectionTimeout is set, then
    196 	 * start the clock to terminate the connection.
    197 	 */
    198 	if (options.unused_connection_timeout != 0) {
    199 		if (channel_still_open(ssh))
    200 			unused_connection_expiry = 0;
    201 		else if (unused_connection_expiry == 0) {
    202 			unused_connection_expiry = now +
    203 			    options.unused_connection_timeout;
    204 		}
    205 	}
    206 	if (unused_connection_expiry != 0)
    207 		ptimeout_deadline_monotime(&timeout, unused_connection_expiry);
    208 
    209 	/*
    210 	 * if using client_alive, set the max timeout accordingly,
    211 	 * and indicate that this particular timeout was for client
    212 	 * alive by setting the client_alive_scheduled flag.
    213 	 *
    214 	 * this could be randomized somewhat to make traffic
    215 	 * analysis more difficult, but we're not doing it yet.
    216 	 */
    217 	if (options.client_alive_interval) {
    218 		/* Time we last heard from the client OR sent a keepalive */
    219 		if (last_client_time == 0)
    220 			last_client_time = now;
    221 		ptimeout_deadline_sec(&timeout, options.client_alive_interval);
    222 		/* XXX ? deadline_monotime(last_client_time + alive_interval) */
    223 		client_alive_scheduled = 1;
    224 	}
    225 
    226 #if 0
    227 	/* wrong: bad condition XXX */
    228 	if (channel_not_very_much_buffered_data())
    229 #endif
    230 	/* Monitor client connection on reserved pollfd entries */
    231 	(*pfdp)[0].fd = connection_in;
    232 	(*pfdp)[0].events = POLLIN;
    233 	(*pfdp)[1].fd = connection_out;
    234 	(*pfdp)[1].events = ssh_packet_have_data_to_write(ssh) ? POLLOUT : 0;
    235 
    236 	/*
    237 	 * If child has terminated and there is enough buffer space to read
    238 	 * from it, then read as much as is available and exit.
    239 	 */
    240 	if (child_terminated && ssh_packet_not_very_much_data_to_write(ssh))
    241 		ptimeout_deadline_ms(&timeout, 100);
    242 
    243 	/* Wait for something to happen, or the timeout to expire. */
    244 	ret = ppoll(*pfdp, *npfd_activep, ptimeout_get_tsp(&timeout), sigsetp);
    245 
    246 	if (ret == -1) {
    247 		for (p = 0; p < *npfd_activep; p++)
    248 			(*pfdp)[p].revents = 0;
    249 		if (errno != EINTR)
    250 			fatal_f("ppoll: %.100s", strerror(errno));
    251 		return;
    252 	}
    253 
    254 	*conn_in_readyp = (*pfdp)[0].revents != 0;
    255 	*conn_out_readyp = (*pfdp)[1].revents != 0;
    256 
    257 	now = monotime(); /* need to reset after ppoll() */
    258 	/* ClientAliveInterval probing */
    259 	if (client_alive_scheduled) {
    260 		if (ret == 0 &&
    261 		    now >= last_client_time + options.client_alive_interval) {
    262 			/* ppoll timed out and we're due to probe */
    263 			client_alive_check(ssh);
    264 			last_client_time = now;
    265 		} else if (ret != 0 && *conn_in_readyp) {
    266 			/* Data from peer; reset probe timer. */
    267 			last_client_time = now;
    268 		}
    269 	}
    270 
    271 	/* UnusedConnectionTimeout handling */
    272 	if (unused_connection_expiry != 0 &&
    273 	    now > unused_connection_expiry && !channel_still_open(ssh)) {
    274 		sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
    275 		logit("terminating inactive connection from %s", remote_id);
    276 		cleanup_exit(255);
    277 	}
    278 }
    279 
    280 /*
    281  * Processes input from the client and the program.  Input data is stored
    282  * in buffers and processed later.
    283  */
    284 static int
    285 process_input(struct ssh *ssh, int connection_in)
    286 {
    287 	int r;
    288 
    289 	if ((r = ssh_packet_process_read(ssh, connection_in)) == 0)
    290 		return 0; /* success */
    291 	if (r == SSH_ERR_SYSTEM_ERROR) {
    292 		if (errno == EAGAIN || errno == EINTR)
    293 			return 0;
    294 		if (errno == EPIPE) {
    295 			logit("Connection closed by %.100s port %d",
    296 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
    297 			return -1;
    298 		}
    299 		logit("Read error from remote host %s port %d: %s",
    300 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
    301 		    strerror(errno));
    302 		cleanup_exit(255);
    303 	}
    304 	return -1;
    305 }
    306 
    307 /*
    308  * Sends data from internal buffers to client program stdin.
    309  */
    310 static void
    311 process_output(struct ssh *ssh, int connection_out)
    312 {
    313 	int r;
    314 	static int interactive = -1;
    315 
    316 	/* Send any buffered packet data to the client. */
    317 	if (interactive != !channel_has_bulk(ssh)) {
    318 		interactive = !channel_has_bulk(ssh);
    319 		debug2_f("session QoS is now %s", interactive ?
    320 		    "interactive" : "non-interactive");
    321 		ssh_packet_set_interactive(ssh, interactive);
    322 	}
    323 	if ((r = ssh_packet_write_poll(ssh)) < 0) {
    324 		sshpkt_fatal(ssh, r, "%s: ssh_packet_write_poll",
    325 		    __func__);
    326 	}
    327 }
    328 
    329 static void
    330 process_buffered_input_packets(struct ssh *ssh)
    331 {
    332 	ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, NULL);
    333 }
    334 
    335 static void
    336 collect_children(struct ssh *ssh)
    337 {
    338 	pid_t pid;
    339 	int status;
    340 
    341 	if (child_terminated) {
    342 		debug("Received SIGCHLD.");
    343 		while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
    344 		    (pid == -1 && errno == EINTR))
    345 			if (pid > 0)
    346 				session_close_by_pid(ssh, pid, status);
    347 		child_terminated = 0;
    348 	}
    349 }
    350 
    351 void
    352 server_loop2(struct ssh *ssh, Authctxt *authctxt)
    353 {
    354 	struct pollfd *pfd = NULL;
    355 	u_int npfd_alloc = 0, npfd_active = 0;
    356 	int r, conn_in_ready, conn_out_ready;
    357 	u_int connection_in, connection_out;
    358 	double start_time, total_time;
    359 	sigset_t bsigset, osigset;
    360 
    361 	debug("Entering interactive session for SSH2.");
    362 	start_time = get_current_time();
    363 
    364 	if (sigemptyset(&bsigset) == -1 ||
    365 	    sigaddset(&bsigset, SIGCHLD) == -1 ||
    366 	    sigaddset(&bsigset, SIGINFO) == -1)
    367 		error_f("bsigset setup: %s", strerror(errno));
    368 	ssh_signal(SIGCHLD, sigchld_handler);
    369 	ssh_signal(SIGINFO, siginfo_handler);
    370 	child_terminated = 0;
    371 	connection_in = ssh_packet_get_connection_in(ssh);
    372 	connection_out = ssh_packet_get_connection_out(ssh);
    373 
    374 	server_init_dispatch(ssh);
    375 
    376 	for (;;) {
    377 		process_buffered_input_packets(ssh);
    378 
    379 		if (!ssh_packet_is_rekeying(ssh) &&
    380 		    ssh_packet_not_very_much_data_to_write(ssh))
    381 			channel_output_poll(ssh);
    382 
    383 		/*
    384 		 * Block SIGCHLD while we check for dead children, then pass
    385 		 * the old signal mask through to ppoll() so that it'll wake
    386 		 * up immediately if a child exits after we've called waitpid().
    387 		 */
    388 		if (sigprocmask(SIG_BLOCK, &bsigset, &osigset) == -1)
    389 			error_f("bsigset sigprocmask: %s", strerror(errno));
    390 		collect_children(ssh);
    391 		if (siginfo_received) {
    392 			siginfo_received = 0;
    393 			channel_report_open(ssh, SYSLOG_LEVEL_INFO);
    394 		}
    395 		wait_until_can_do_something(ssh, connection_in, connection_out,
    396 		    &pfd, &npfd_alloc, &npfd_active, &osigset,
    397 		    &conn_in_ready, &conn_out_ready);
    398 		if (sigprocmask(SIG_SETMASK, &osigset, NULL) == -1)
    399 			error_f("osigset sigprocmask: %s", strerror(errno));
    400 
    401 		channel_after_poll(ssh, pfd, npfd_active);
    402 		if (conn_in_ready &&
    403 		    process_input(ssh, connection_in) < 0)
    404 			break;
    405 		/* A timeout may have triggered rekeying */
    406 		if ((r = ssh_packet_check_rekey(ssh)) != 0)
    407 			fatal_fr(r, "cannot start rekeying");
    408 		if (conn_out_ready)
    409 			process_output(ssh, connection_out);
    410 	}
    411 	collect_children(ssh);
    412 	free(pfd);
    413 
    414 	/* free all channels, no more reads and writes */
    415 	channel_free_all(ssh);
    416 
    417 	/* free remaining sessions, e.g. remove wtmp entries */
    418 	session_destroy_all(ssh, NULL);
    419 	total_time = get_current_time() - start_time;
    420 	logit("SSH: Server;LType: Throughput;Remote: %s-%d;IN: %lu;OUT: %lu;Duration: %.1f;tPut_in: %.1f;tPut_out: %.1f",
    421 	      ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
    422 	      stdin_bytes, fdout_bytes, total_time, stdin_bytes / total_time,
    423 	      fdout_bytes / total_time);
    424 }
    425 
    426 static int
    427 server_input_keep_alive(int type, uint32_t seq, struct ssh *ssh)
    428 {
    429 	debug("Got %d/%u for keepalive", type, seq);
    430 	/*
    431 	 * reset timeout, since we got a sane answer from the client.
    432 	 * even if this was generated by something other than
    433 	 * the bogus CHANNEL_REQUEST we send for keepalives.
    434 	 */
    435 	ssh_packet_set_alive_timeouts(ssh, 0);
    436 	return 0;
    437 }
    438 
    439 static Channel *
    440 server_request_direct_tcpip(struct ssh *ssh, int *reason, const char **errmsg)
    441 {
    442 	Channel *c = NULL;
    443 	char *target = NULL, *originator = NULL;
    444 	u_int target_port = 0, originator_port = 0;
    445 	int r;
    446 
    447 	if ((r = sshpkt_get_cstring(ssh, &target, NULL)) != 0 ||
    448 	    (r = sshpkt_get_u32(ssh, &target_port)) != 0 ||
    449 	    (r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
    450 	    (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
    451 	    (r = sshpkt_get_end(ssh)) != 0)
    452 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
    453 	if (target_port > 0xFFFF) {
    454 		error_f("invalid target port");
    455 		*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
    456 		goto out;
    457 	}
    458 	if (originator_port > 0xFFFF) {
    459 		error_f("invalid originator port");
    460 		*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
    461 		goto out;
    462 	}
    463 
    464 	debug_f("originator %s port %u, target %s port %u",
    465 	    originator, originator_port, target, target_port);
    466 
    467 	/* XXX fine grained permissions */
    468 	if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0 &&
    469 	    auth_opts->permit_port_forwarding_flag &&
    470 	    !options.disable_forwarding) {
    471 		c = channel_connect_to_port(ssh, target, target_port,
    472 		    "direct-tcpip", "direct-tcpip", reason, errmsg);
    473 	} else {
    474 		logit("refused local port forward: "
    475 		    "originator %s port %d, target %s port %d",
    476 		    originator, originator_port, target, target_port);
    477 		if (reason != NULL)
    478 			*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
    479 	}
    480 
    481  out:
    482 	free(originator);
    483 	free(target);
    484 	return c;
    485 }
    486 
    487 static Channel *
    488 server_request_direct_streamlocal(struct ssh *ssh)
    489 {
    490 	Channel *c = NULL;
    491 	char *target = NULL, *originator = NULL;
    492 	u_int originator_port = 0;
    493 	struct passwd *pw = the_authctxt->pw;
    494 	int r;
    495 
    496 	if (pw == NULL || !the_authctxt->valid)
    497 		fatal_f("no/invalid user");
    498 
    499 	if ((r = sshpkt_get_cstring(ssh, &target, NULL)) != 0 ||
    500 	    (r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
    501 	    (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
    502 	    (r = sshpkt_get_end(ssh)) != 0)
    503 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
    504 	if (originator_port > 0xFFFF) {
    505 		error_f("invalid originator port");
    506 		goto out;
    507 	}
    508 
    509 	debug_f("originator %s port %d, target %s",
    510 	    originator, originator_port, target);
    511 
    512 	/* XXX fine grained permissions */
    513 	if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 &&
    514 	    auth_opts->permit_port_forwarding_flag &&
    515 	    !options.disable_forwarding) {
    516 		c = channel_connect_to_path(ssh, target,
    517 		    "direct-streamlocal (at) openssh.com", "direct-streamlocal");
    518 	} else {
    519 		logit("refused streamlocal port forward: "
    520 		    "originator %s port %d, target %s",
    521 		    originator, originator_port, target);
    522 	}
    523 
    524 out:
    525 	free(originator);
    526 	free(target);
    527 	return c;
    528 }
    529 
    530 static Channel *
    531 server_request_tun(struct ssh *ssh)
    532 {
    533 	Channel *c = NULL;
    534 	u_int mode, tun;
    535 	int r, sock;
    536 	char *tmp, *ifname = NULL;
    537 
    538 	if ((r = sshpkt_get_u32(ssh, &mode)) != 0)
    539 		sshpkt_fatal(ssh, r, "%s: parse mode", __func__);
    540 	switch (mode) {
    541 	case SSH_TUNMODE_POINTOPOINT:
    542 	case SSH_TUNMODE_ETHERNET:
    543 		break;
    544 	default:
    545 		ssh_packet_send_debug(ssh, "Unsupported tunnel device mode.");
    546 		return NULL;
    547 	}
    548 	if ((options.permit_tun & mode) == 0) {
    549 		ssh_packet_send_debug(ssh, "Server has rejected tunnel device "
    550 		    "forwarding");
    551 		return NULL;
    552 	}
    553 
    554 	if ((r = sshpkt_get_u32(ssh, &tun)) != 0)
    555 		sshpkt_fatal(ssh, r, "%s: parse device", __func__);
    556 	if (tun > INT_MAX) {
    557 		debug_f("invalid tun");
    558 		goto done;
    559 	}
    560 	if (auth_opts->force_tun_device != -1) {
    561 		if (tun != SSH_TUNID_ANY &&
    562 		    auth_opts->force_tun_device != (int)tun)
    563 			goto done;
    564 		tun = auth_opts->force_tun_device;
    565 	}
    566 	sock = tun_open(tun, mode, &ifname);
    567 	if (sock < 0)
    568 		goto done;
    569 	debug("Tunnel forwarding using interface %s", ifname);
    570 
    571 	if (options.hpn_disabled)
    572 	c = channel_new(ssh, "tun", SSH_CHANNEL_OPEN, sock, sock, -1,
    573 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
    574 	else
    575 		c = channel_new(ssh, "tun", SSH_CHANNEL_OPEN, sock, sock, -1,
    576 		    options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
    577 	c->datagram = 1;
    578 
    579 	/*
    580 	 * Update the list of names exposed to the session
    581 	 * XXX remove these if the tunnels are closed (won't matter
    582 	 * much if they are already in the environment though)
    583 	 */
    584 	tmp = tun_fwd_ifnames;
    585 	xasprintf(&tun_fwd_ifnames, "%s%s%s",
    586 	    tun_fwd_ifnames == NULL ? "" : tun_fwd_ifnames,
    587 	    tun_fwd_ifnames == NULL ? "" : ",",
    588 	    ifname);
    589 	free(tmp);
    590 	free(ifname);
    591 
    592  done:
    593 	if (c == NULL)
    594 		ssh_packet_send_debug(ssh, "Failed to open the tunnel device.");
    595 	return c;
    596 }
    597 
    598 static Channel *
    599 server_request_session(struct ssh *ssh)
    600 {
    601 	Channel *c;
    602 	int r;
    603 
    604 	debug("input_session_request");
    605 	if ((r = sshpkt_get_end(ssh)) != 0)
    606 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
    607 
    608 	if (no_more_sessions) {
    609 		ssh_packet_disconnect(ssh, "Possible attack: attempt to open a "
    610 		    "session after additional sessions disabled");
    611 	}
    612 
    613 	/*
    614 	 * A server session has no fd to read or write until a
    615 	 * CHANNEL_REQUEST for a shell is made, so we set the type to
    616 	 * SSH_CHANNEL_LARVAL.  Additionally, a callback for handling all
    617 	 * CHANNEL_REQUEST messages is registered.
    618 	 */
    619 	c = channel_new(ssh, "session", SSH_CHANNEL_LARVAL,
    620 	    -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT,
    621 	    0, "server-session", 1);
    622 	if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled))
    623 		c->dynamic_window = 1;
    624 	if (session_open(the_authctxt, c->self) != 1) {
    625 		debug("session open failed, free channel %d", c->self);
    626 		channel_free(ssh, c);
    627 		return NULL;
    628 	}
    629 	channel_register_cleanup(ssh, c->self, session_close_by_channel, 0);
    630 	return c;
    631 }
    632 
    633 static int
    634 server_input_channel_open(int type, uint32_t seq, struct ssh *ssh)
    635 {
    636 	Channel *c = NULL;
    637 	char *ctype = NULL;
    638 	const char *errmsg = NULL;
    639 	int r, reason = SSH2_OPEN_CONNECT_FAILED;
    640 	u_int rchan = 0, rmaxpack = 0, rwindow = 0;
    641 
    642 	if ((r = sshpkt_get_cstring(ssh, &ctype, NULL)) != 0 ||
    643 	    (r = sshpkt_get_u32(ssh, &rchan)) != 0 ||
    644 	    (r = sshpkt_get_u32(ssh, &rwindow)) != 0 ||
    645 	    (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0)
    646 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
    647 	debug_f("ctype %s rchan %u win %u max %u",
    648 	    ctype, rchan, rwindow, rmaxpack);
    649 
    650 	if (strcmp(ctype, "session") == 0) {
    651 		c = server_request_session(ssh);
    652 	} else if (strcmp(ctype, "direct-tcpip") == 0) {
    653 		c = server_request_direct_tcpip(ssh, &reason, &errmsg);
    654 	} else if (strcmp(ctype, "direct-streamlocal (at) openssh.com") == 0) {
    655 		c = server_request_direct_streamlocal(ssh);
    656 	} else if (strcmp(ctype, "tun (at) openssh.com") == 0) {
    657 		c = server_request_tun(ssh);
    658 	}
    659 	if (c != NULL) {
    660 		debug_f("confirm %s", ctype);
    661 		c->remote_id = rchan;
    662 		c->have_remote_id = 1;
    663 		c->remote_window = rwindow;
    664 		c->remote_maxpacket = rmaxpack;
    665 		if (c->type != SSH_CHANNEL_CONNECTING) {
    666 			if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
    667 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
    668 			    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
    669 			    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
    670 			    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
    671 			    (r = sshpkt_send(ssh)) != 0) {
    672 				sshpkt_fatal(ssh, r,
    673 				    "%s: send open confirm", __func__);
    674 			}
    675 		}
    676 	} else {
    677 		debug_f("failure %s", ctype);
    678 		if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
    679 		    (r = sshpkt_put_u32(ssh, rchan)) != 0 ||
    680 		    (r = sshpkt_put_u32(ssh, reason)) != 0 ||
    681 		    (r = sshpkt_put_cstring(ssh, errmsg ? errmsg : "open failed")) != 0 ||
    682 		    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
    683 		    (r = sshpkt_send(ssh)) != 0) {
    684 			sshpkt_fatal(ssh, r,
    685 			    "%s: send open failure", __func__);
    686 		}
    687 	}
    688 	free(ctype);
    689 	return 0;
    690 }
    691 
    692 static int
    693 server_input_hostkeys_prove(struct ssh *ssh, struct sshbuf **respp)
    694 {
    695 	struct sshbuf *resp = NULL;
    696 	struct sshbuf *sigbuf = NULL;
    697 	struct sshkey *key = NULL, *key_pub = NULL, *key_prv = NULL;
    698 	int r, ndx, success = 0;
    699 	const u_char *blob;
    700 	const char *sigalg, *kex_rsa_sigalg = NULL;
    701 	u_char *sig = NULL;
    702 	size_t blen, slen;
    703 
    704 	if ((resp = sshbuf_new()) == NULL || (sigbuf = sshbuf_new()) == NULL)
    705 		fatal_f("sshbuf_new");
    706 	if (sshkey_type_plain(sshkey_type_from_name(
    707 	    ssh->kex->hostkey_alg)) == KEY_RSA)
    708 		kex_rsa_sigalg = ssh->kex->hostkey_alg;
    709 	while (ssh_packet_remaining(ssh) > 0) {
    710 		sshkey_free(key);
    711 		key = NULL;
    712 		if ((r = sshpkt_get_string_direct(ssh, &blob, &blen)) != 0 ||
    713 		    (r = sshkey_from_blob(blob, blen, &key)) != 0) {
    714 			error_fr(r, "parse key");
    715 			goto out;
    716 		}
    717 		/*
    718 		 * Better check that this is actually one of our hostkeys
    719 		 * before attempting to sign anything with it.
    720 		 */
    721 		if ((ndx = ssh->kex->host_key_index(key, 1, ssh)) == -1) {
    722 			error_f("unknown host %s key", sshkey_type(key));
    723 			goto out;
    724 		}
    725 		/*
    726 		 * XXX refactor: make kex->sign just use an index rather
    727 		 * than passing in public and private keys
    728 		 */
    729 		if ((key_prv = get_hostkey_by_index(ndx)) == NULL &&
    730 		    (key_pub = get_hostkey_public_by_index(ndx, ssh)) == NULL) {
    731 			error_f("can't retrieve hostkey %d", ndx);
    732 			goto out;
    733 		}
    734 		sshbuf_reset(sigbuf);
    735 		free(sig);
    736 		sig = NULL;
    737 		/*
    738 		 * For RSA keys, prefer to use the signature type negotiated
    739 		 * during KEX to the default (SHA1).
    740 		 */
    741 		sigalg = sshkey_ssh_name(key);
    742 		if (sshkey_type_plain(key->type) == KEY_RSA) {
    743 			if (kex_rsa_sigalg != NULL)
    744 				sigalg = kex_rsa_sigalg;
    745 			else if (ssh->kex->flags & KEX_RSA_SHA2_512_SUPPORTED)
    746 				sigalg = "rsa-sha2-512";
    747 			else if (ssh->kex->flags & KEX_RSA_SHA2_256_SUPPORTED)
    748 				sigalg = "rsa-sha2-256";
    749 		}
    750 
    751 		debug3_f("sign %s key (index %d) using sigalg %s",
    752 		    sshkey_type(key), ndx, sigalg == NULL ? "default" : sigalg);
    753 		if ((r = sshbuf_put_cstring(sigbuf,
    754 		    "hostkeys-prove-00 (at) openssh.com")) != 0 ||
    755 		    (r = sshbuf_put_stringb(sigbuf,
    756 		    ssh->kex->session_id)) != 0 ||
    757 		    (r = sshkey_puts(key, sigbuf)) != 0 ||
    758 		    (r = ssh->kex->sign(ssh, key_prv, key_pub, &sig, &slen,
    759 		    sshbuf_ptr(sigbuf), sshbuf_len(sigbuf), sigalg)) != 0 ||
    760 		    (r = sshbuf_put_string(resp, sig, slen)) != 0) {
    761 			error_fr(r, "assemble signature");
    762 			goto out;
    763 		}
    764 	}
    765 	/* Success */
    766 	*respp = resp;
    767 	resp = NULL; /* don't free it */
    768 	success = 1;
    769  out:
    770 	free(sig);
    771 	sshbuf_free(resp);
    772 	sshbuf_free(sigbuf);
    773 	sshkey_free(key);
    774 	return success;
    775 }
    776 
    777 static int
    778 server_input_global_request(int type, uint32_t seq, struct ssh *ssh)
    779 {
    780 	char *rtype = NULL;
    781 	u_char want_reply = 0;
    782 	int r, success = 0, allocated_listen_port = 0;
    783 	u_int port = 0;
    784 	struct sshbuf *resp = NULL;
    785 	struct passwd *pw = the_authctxt->pw;
    786 	struct Forward fwd;
    787 
    788 	memset(&fwd, 0, sizeof(fwd));
    789 	if (pw == NULL || !the_authctxt->valid)
    790 		fatal_f("no/invalid user");
    791 
    792 	if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
    793 	    (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
    794 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
    795 	debug_f("rtype %s want_reply %d", rtype, want_reply);
    796 
    797 	/* -R style forwarding */
    798 	if (strcmp(rtype, "tcpip-forward") == 0) {
    799 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 ||
    800 		    (r = sshpkt_get_u32(ssh, &port)) != 0)
    801 			sshpkt_fatal(ssh, r, "%s: parse tcpip-forward", __func__);
    802 		debug_f("tcpip-forward listen %s port %u",
    803 		    fwd.listen_host, port);
    804 		if (port <= INT_MAX)
    805 			fwd.listen_port = (int)port;
    806 		/* check permissions */
    807 		if (port > INT_MAX ||
    808 		    (options.allow_tcp_forwarding & FORWARD_REMOTE) == 0 ||
    809 		    !auth_opts->permit_port_forwarding_flag ||
    810 		    options.disable_forwarding ||
    811 		    (!want_reply && fwd.listen_port == 0)) {
    812 			success = 0;
    813 			ssh_packet_send_debug(ssh, "Server has disabled port forwarding.");
    814 		} else {
    815 			/* Start listening on the port */
    816 			success = channel_setup_remote_fwd_listener(ssh, &fwd,
    817 			    &allocated_listen_port, &options.fwd_opts);
    818 		}
    819 		if ((resp = sshbuf_new()) == NULL)
    820 			fatal_f("sshbuf_new");
    821 		if (allocated_listen_port != 0 &&
    822 		    (r = sshbuf_put_u32(resp, allocated_listen_port)) != 0)
    823 			fatal_fr(r, "sshbuf_put_u32");
    824 	} else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
    825 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 ||
    826 		    (r = sshpkt_get_u32(ssh, &port)) != 0)
    827 			sshpkt_fatal(ssh, r, "%s: parse cancel-tcpip-forward", __func__);
    828 
    829 		debug_f("cancel-tcpip-forward addr %s port %d",
    830 		    fwd.listen_host, port);
    831 		if (port <= INT_MAX) {
    832 			fwd.listen_port = (int)port;
    833 			success = channel_cancel_rport_listener(ssh, &fwd);
    834 		}
    835 	} else if (strcmp(rtype, "streamlocal-forward (at) openssh.com") == 0) {
    836 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0)
    837 			sshpkt_fatal(ssh, r, "%s: parse streamlocal-forward (at) openssh.com", __func__);
    838 		debug_f("streamlocal-forward listen path %s",
    839 		    fwd.listen_path);
    840 
    841 		/* check permissions */
    842 		if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0
    843 		    || !auth_opts->permit_port_forwarding_flag ||
    844 		    options.disable_forwarding) {
    845 			success = 0;
    846 			ssh_packet_send_debug(ssh, "Server has disabled "
    847 			    "streamlocal forwarding.");
    848 		} else {
    849 			/* Start listening on the socket */
    850 			success = channel_setup_remote_fwd_listener(ssh,
    851 			    &fwd, NULL, &options.fwd_opts);
    852 		}
    853 	} else if (strcmp(rtype, "cancel-streamlocal-forward (at) openssh.com") == 0) {
    854 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0)
    855 			sshpkt_fatal(ssh, r, "%s: parse cancel-streamlocal-forward (at) openssh.com", __func__);
    856 		debug_f("cancel-streamlocal-forward path %s",
    857 		    fwd.listen_path);
    858 
    859 		success = channel_cancel_rport_listener(ssh, &fwd);
    860 	} else if (strcmp(rtype, "no-more-sessions (at) openssh.com") == 0) {
    861 		no_more_sessions = 1;
    862 		success = 1;
    863 	} else if (strcmp(rtype, "hostkeys-prove-00 (at) openssh.com") == 0) {
    864 		success = server_input_hostkeys_prove(ssh, &resp);
    865 	}
    866 	/* XXX sshpkt_get_end() */
    867 	if (want_reply) {
    868 		if ((r = sshpkt_start(ssh, success ?
    869 		    SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE)) != 0 ||
    870 		    (success && resp != NULL && (r = sshpkt_putb(ssh, resp)) != 0) ||
    871 		    (r = sshpkt_send(ssh)) != 0 ||
    872 		    (r = ssh_packet_write_wait(ssh)) < 0)
    873 			sshpkt_fatal(ssh, r, "%s: send reply", __func__);
    874 	}
    875 	free(fwd.listen_host);
    876 	free(fwd.listen_path);
    877 	free(rtype);
    878 	sshbuf_free(resp);
    879 	return 0;
    880 }
    881 
    882 static int
    883 server_input_channel_req(int type, uint32_t seq, struct ssh *ssh)
    884 {
    885 	Channel *c;
    886 	int r, success = 0;
    887 	char *rtype = NULL;
    888 	u_char want_reply = 0;
    889 	u_int id = 0;
    890 
    891 	if ((r = sshpkt_get_u32(ssh, &id)) != 0 ||
    892 	    (r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
    893 	    (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
    894 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
    895 
    896 	debug("server_input_channel_req: channel %u request %s reply %d",
    897 	    id, rtype, want_reply);
    898 
    899 	if (id >= INT_MAX || (c = channel_lookup(ssh, (int)id)) == NULL) {
    900 		ssh_packet_disconnect(ssh, "%s: unknown channel %d",
    901 		    __func__, id);
    902 	}
    903 	if (!strcmp(rtype, "eow (at) openssh.com")) {
    904 		if ((r = sshpkt_get_end(ssh)) != 0)
    905 			sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
    906 		chan_rcvd_eow(ssh, c);
    907 	} else if ((c->type == SSH_CHANNEL_LARVAL ||
    908 	    c->type == SSH_CHANNEL_OPEN) && strcmp(c->ctype, "session") == 0)
    909 		success = session_input_channel_req(ssh, c, rtype);
    910 	if (want_reply && !(c->flags & CHAN_CLOSE_SENT)) {
    911 		if (!c->have_remote_id)
    912 			fatal_f("channel %d: no remote_id", c->self);
    913 		if ((r = sshpkt_start(ssh, success ?
    914 		    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 ||
    915 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
    916 		    (r = sshpkt_send(ssh)) != 0)
    917 			sshpkt_fatal(ssh, r, "%s: send reply", __func__);
    918 	}
    919 	free(rtype);
    920 	return 0;
    921 }
    922 
    923 static void
    924 server_init_dispatch(struct ssh *ssh)
    925 {
    926 	debug("server_init_dispatch");
    927 	ssh_dispatch_init(ssh, &dispatch_protocol_error);
    928 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
    929 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data);
    930 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
    931 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
    932 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
    933 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
    934 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
    935 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
    936 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
    937 	ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
    938 	/* client_alive */
    939 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &server_input_keep_alive);
    940 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
    941 	ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
    942 	ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
    943 	/* rekeying */
    944 	ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
    945 }
    946