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