xref: /openbsd-src/usr.bin/ssh/serverloop.c (revision f84b1df5a16cdd762c93854218de246e79975d3b)
1 /* $OpenBSD: serverloop.c,v 1.232 2022/04/20 04:19:11 djm 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 <sys/types.h>
39 #include <sys/wait.h>
40 #include <sys/socket.h>
41 #include <sys/time.h>
42 #include <sys/queue.h>
43 
44 #include <netinet/in.h>
45 
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <pwd.h>
49 #include <limits.h>
50 #include <poll.h>
51 #include <signal.h>
52 #include <string.h>
53 #include <termios.h>
54 #include <unistd.h>
55 #include <stdarg.h>
56 
57 #include "xmalloc.h"
58 #include "packet.h"
59 #include "sshbuf.h"
60 #include "log.h"
61 #include "misc.h"
62 #include "servconf.h"
63 #include "canohost.h"
64 #include "sshpty.h"
65 #include "channels.h"
66 #include "compat.h"
67 #include "ssh2.h"
68 #include "sshkey.h"
69 #include "cipher.h"
70 #include "kex.h"
71 #include "hostfile.h"
72 #include "auth.h"
73 #include "session.h"
74 #include "dispatch.h"
75 #include "auth-options.h"
76 #include "serverloop.h"
77 #include "ssherr.h"
78 
79 extern ServerOptions options;
80 
81 /* XXX */
82 extern Authctxt *the_authctxt;
83 extern struct sshauthopt *auth_opts;
84 extern int use_privsep;
85 
86 static int no_more_sessions = 0; /* Disallow further sessions. */
87 
88 static volatile sig_atomic_t child_terminated = 0;	/* The child has terminated. */
89 
90 /* Cleanup on signals (!use_privsep case only) */
91 static volatile sig_atomic_t received_sigterm = 0;
92 
93 /* prototypes */
94 static void server_init_dispatch(struct ssh *);
95 
96 /* requested tunnel forwarding interface(s), shared with session.c */
97 char *tun_fwd_ifnames = NULL;
98 
99 /* returns 1 if bind to specified port by specified user is permitted */
100 static int
101 bind_permitted(int port, uid_t uid)
102 {
103 	if (use_privsep)
104 		return 1; /* allow system to decide */
105 	if (port < IPPORT_RESERVED && uid != 0)
106 		return 0;
107 	return 1;
108 }
109 
110 /*ARGSUSED*/
111 static void
112 sigchld_handler(int sig)
113 {
114 	child_terminated = 1;
115 }
116 
117 /*ARGSUSED*/
118 static void
119 sigterm_handler(int sig)
120 {
121 	received_sigterm = sig;
122 }
123 
124 static void
125 client_alive_check(struct ssh *ssh)
126 {
127 	char remote_id[512];
128 	int r, channel_id;
129 
130 	/* timeout, check to see how many we have had */
131 	if (options.client_alive_count_max > 0 &&
132 	    ssh_packet_inc_alive_timeouts(ssh) >
133 	    options.client_alive_count_max) {
134 		sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
135 		logit("Timeout, client not responding from %s", remote_id);
136 		cleanup_exit(255);
137 	}
138 
139 	/*
140 	 * send a bogus global/channel request with "wantreply",
141 	 * we should get back a failure
142 	 */
143 	if ((channel_id = channel_find_open(ssh)) == -1) {
144 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
145 		    (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com"))
146 		    != 0 ||
147 		    (r = sshpkt_put_u8(ssh, 1)) != 0) /* boolean: want reply */
148 			fatal_fr(r, "compose");
149 	} else {
150 		channel_request_start(ssh, channel_id,
151 		    "keepalive@openssh.com", 1);
152 	}
153 	if ((r = sshpkt_send(ssh)) != 0)
154 		fatal_fr(r, "send");
155 }
156 
157 /*
158  * Sleep in ppoll() until we can do something.
159  * Optionally, a maximum time can be specified for the duration of
160  * the wait (0 = infinite).
161  */
162 static void
163 wait_until_can_do_something(struct ssh *ssh,
164     int connection_in, int connection_out, struct pollfd **pfdp,
165     u_int *npfd_allocp, u_int *npfd_activep, u_int64_t max_time_ms,
166     sigset_t *sigsetp, int *conn_in_readyp, int *conn_out_readyp)
167 {
168 	struct timespec ts, *tsp;
169 	int ret;
170 	time_t minwait_secs = 0;
171 	int client_alive_scheduled = 0;
172 	u_int p;
173 	/* time we last heard from the client OR sent a keepalive */
174 	static time_t last_client_time;
175 
176 	*conn_in_readyp = *conn_out_readyp = 0;
177 
178 	/* Prepare channel poll. First two pollfd entries are reserved */
179 	channel_prepare_poll(ssh, pfdp, npfd_allocp, npfd_activep,
180 	    2, &minwait_secs);
181 	if (*npfd_activep < 2)
182 		fatal_f("bad npfd %u", *npfd_activep); /* shouldn't happen */
183 
184 	/* XXX need proper deadline system for rekey/client alive */
185 	if (minwait_secs != 0)
186 		max_time_ms = MINIMUM(max_time_ms, (u_int)minwait_secs * 1000);
187 
188 	/*
189 	 * if using client_alive, set the max timeout accordingly,
190 	 * and indicate that this particular timeout was for client
191 	 * alive by setting the client_alive_scheduled flag.
192 	 *
193 	 * this could be randomized somewhat to make traffic
194 	 * analysis more difficult, but we're not doing it yet.
195 	 */
196 	if (options.client_alive_interval) {
197 		uint64_t keepalive_ms =
198 		    (uint64_t)options.client_alive_interval * 1000;
199 
200 		if (max_time_ms == 0 || max_time_ms > keepalive_ms) {
201 			max_time_ms = keepalive_ms;
202 			client_alive_scheduled = 1;
203 		}
204 		if (last_client_time == 0)
205 			last_client_time = monotime();
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 		if (max_time_ms == 0 || client_alive_scheduled)
224 			max_time_ms = 100;
225 
226 	if (max_time_ms == 0)
227 		tsp = NULL;
228 	else {
229 		ts.tv_sec = max_time_ms / 1000;
230 		ts.tv_nsec = 1000000 * (max_time_ms % 1000);
231 		tsp = &ts;
232 	}
233 
234 	/* Wait for something to happen, or the timeout to expire. */
235 	ret = ppoll(*pfdp, *npfd_activep, tsp, sigsetp);
236 
237 	if (ret == -1) {
238 		for (p = 0; p < *npfd_activep; p++)
239 			(*pfdp)[p].revents = 0;
240 		if (errno != EINTR)
241 			fatal_f("ppoll: %.100s", strerror(errno));
242 		return;
243 	}
244 
245 	*conn_in_readyp = (*pfdp)[0].revents != 0;
246 	*conn_out_readyp = (*pfdp)[1].revents != 0;
247 
248 	if (client_alive_scheduled) {
249 		time_t now = monotime();
250 
251 		/*
252 		 * If the ppoll timed out, or returned for some other reason
253 		 * but we haven't heard from the client in time, send keepalive.
254 		 */
255 		if (ret == 0 || (last_client_time != 0 && last_client_time +
256 		    options.client_alive_interval <= now)) {
257 			client_alive_check(ssh);
258 			last_client_time = now;
259 		} else if (*conn_in_readyp)
260 			last_client_time = now;
261 	}
262 }
263 
264 /*
265  * Processes input from the client and the program.  Input data is stored
266  * in buffers and processed later.
267  */
268 static int
269 process_input(struct ssh *ssh, int connection_in)
270 {
271 	int r;
272 
273 	if ((r = ssh_packet_process_read(ssh, connection_in)) == 0)
274 		return 0; /* success */
275 	if (r == SSH_ERR_SYSTEM_ERROR) {
276 		if (errno == EAGAIN || errno == EINTR)
277 			return 0;
278 		if (errno == EPIPE) {
279 			verbose("Connection closed by %.100s port %d",
280 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
281 			return -1;
282 		}
283 		verbose("Read error from remote host %s port %d: %s",
284 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
285 		    strerror(errno));
286 		cleanup_exit(255);
287 	}
288 	return -1;
289 }
290 
291 /*
292  * Sends data from internal buffers to client program stdin.
293  */
294 static void
295 process_output(struct ssh *ssh, int connection_out)
296 {
297 	int r;
298 
299 	/* Send any buffered packet data to the client. */
300 	if ((r = ssh_packet_write_poll(ssh)) != 0) {
301 		sshpkt_fatal(ssh, r, "%s: ssh_packet_write_poll",
302 		    __func__);
303 	}
304 }
305 
306 static void
307 process_buffered_input_packets(struct ssh *ssh)
308 {
309 	ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, NULL);
310 }
311 
312 static void
313 collect_children(struct ssh *ssh)
314 {
315 	pid_t pid;
316 	int status;
317 
318 	if (child_terminated) {
319 		debug("Received SIGCHLD.");
320 		while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
321 		    (pid == -1 && errno == EINTR))
322 			if (pid > 0)
323 				session_close_by_pid(ssh, pid, status);
324 		child_terminated = 0;
325 	}
326 }
327 
328 void
329 server_loop2(struct ssh *ssh, Authctxt *authctxt)
330 {
331 	struct pollfd *pfd = NULL;
332 	u_int npfd_alloc = 0, npfd_active = 0;
333 	int r, conn_in_ready, conn_out_ready;
334 	u_int connection_in, connection_out;
335 	u_int64_t rekey_timeout_ms = 0;
336 	sigset_t bsigset, osigset;
337 
338 	debug("Entering interactive session for SSH2.");
339 
340 	if (sigemptyset(&bsigset) == -1 || sigaddset(&bsigset, SIGCHLD) == -1)
341 		error_f("bsigset setup: %s", strerror(errno));
342 	ssh_signal(SIGCHLD, sigchld_handler);
343 	child_terminated = 0;
344 	connection_in = ssh_packet_get_connection_in(ssh);
345 	connection_out = ssh_packet_get_connection_out(ssh);
346 
347 	if (!use_privsep) {
348 		ssh_signal(SIGTERM, sigterm_handler);
349 		ssh_signal(SIGINT, sigterm_handler);
350 		ssh_signal(SIGQUIT, sigterm_handler);
351 	}
352 
353 	server_init_dispatch(ssh);
354 
355 	for (;;) {
356 		process_buffered_input_packets(ssh);
357 
358 		if (!ssh_packet_is_rekeying(ssh) &&
359 		    ssh_packet_not_very_much_data_to_write(ssh))
360 			channel_output_poll(ssh);
361 		if (options.rekey_interval > 0 &&
362 		    !ssh_packet_is_rekeying(ssh)) {
363 			rekey_timeout_ms = ssh_packet_get_rekey_timeout(ssh) *
364 			    1000;
365 		} else {
366 			rekey_timeout_ms = 0;
367 		}
368 
369 		/*
370 		 * Block SIGCHLD while we check for dead children, then pass
371 		 * the old signal mask through to ppoll() so that it'll wake
372 		 * up immediately if a child exits after we've called waitpid().
373 		 */
374 		if (sigprocmask(SIG_BLOCK, &bsigset, &osigset) == -1)
375 			error_f("bsigset sigprocmask: %s", strerror(errno));
376 		collect_children(ssh);
377 		wait_until_can_do_something(ssh, connection_in, connection_out,
378 		    &pfd, &npfd_alloc, &npfd_active, rekey_timeout_ms, &osigset,
379 		    &conn_in_ready, &conn_out_ready);
380 		if (sigprocmask(SIG_UNBLOCK, &bsigset, &osigset) == -1)
381 			error_f("osigset sigprocmask: %s", strerror(errno));
382 
383 		if (received_sigterm) {
384 			logit("Exiting on signal %d", (int)received_sigterm);
385 			/* Clean up sessions, utmp, etc. */
386 			cleanup_exit(255);
387 		}
388 
389 		channel_after_poll(ssh, pfd, npfd_active);
390 		if (conn_in_ready &&
391 		    process_input(ssh, connection_in) < 0)
392 			break;
393 		/* A timeout may have triggered rekeying */
394 		if ((r = ssh_packet_check_rekey(ssh)) != 0)
395 			fatal_fr(r, "cannot start rekeying");
396 		if (conn_out_ready)
397 			process_output(ssh, connection_out);
398 	}
399 	collect_children(ssh);
400 	free(pfd);
401 
402 	/* free all channels, no more reads and writes */
403 	channel_free_all(ssh);
404 
405 	/* free remaining sessions, e.g. remove wtmp entries */
406 	session_destroy_all(ssh, NULL);
407 }
408 
409 static int
410 server_input_keep_alive(int type, u_int32_t seq, struct ssh *ssh)
411 {
412 	debug("Got %d/%u for keepalive", type, seq);
413 	/*
414 	 * reset timeout, since we got a sane answer from the client.
415 	 * even if this was generated by something other than
416 	 * the bogus CHANNEL_REQUEST we send for keepalives.
417 	 */
418 	ssh_packet_set_alive_timeouts(ssh, 0);
419 	return 0;
420 }
421 
422 static Channel *
423 server_request_direct_tcpip(struct ssh *ssh, int *reason, const char **errmsg)
424 {
425 	Channel *c = NULL;
426 	char *target = NULL, *originator = NULL;
427 	u_int target_port = 0, originator_port = 0;
428 	int r;
429 
430 	if ((r = sshpkt_get_cstring(ssh, &target, NULL)) != 0 ||
431 	    (r = sshpkt_get_u32(ssh, &target_port)) != 0 ||
432 	    (r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
433 	    (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
434 	    (r = sshpkt_get_end(ssh)) != 0)
435 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
436 	if (target_port > 0xFFFF) {
437 		error_f("invalid target port");
438 		*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
439 		goto out;
440 	}
441 	if (originator_port > 0xFFFF) {
442 		error_f("invalid originator port");
443 		*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
444 		goto out;
445 	}
446 
447 	debug_f("originator %s port %u, target %s port %u",
448 	    originator, originator_port, target, target_port);
449 
450 	/* XXX fine grained permissions */
451 	if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0 &&
452 	    auth_opts->permit_port_forwarding_flag &&
453 	    !options.disable_forwarding) {
454 		c = channel_connect_to_port(ssh, target, target_port,
455 		    "direct-tcpip", "direct-tcpip", reason, errmsg);
456 	} else {
457 		logit("refused local port forward: "
458 		    "originator %s port %d, target %s port %d",
459 		    originator, originator_port, target, target_port);
460 		if (reason != NULL)
461 			*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
462 	}
463 
464  out:
465 	free(originator);
466 	free(target);
467 	return c;
468 }
469 
470 static Channel *
471 server_request_direct_streamlocal(struct ssh *ssh)
472 {
473 	Channel *c = NULL;
474 	char *target = NULL, *originator = NULL;
475 	u_int originator_port = 0;
476 	struct passwd *pw = the_authctxt->pw;
477 	int r;
478 
479 	if (pw == NULL || !the_authctxt->valid)
480 		fatal_f("no/invalid user");
481 
482 	if ((r = sshpkt_get_cstring(ssh, &target, NULL)) != 0 ||
483 	    (r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
484 	    (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
485 	    (r = sshpkt_get_end(ssh)) != 0)
486 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
487 	if (originator_port > 0xFFFF) {
488 		error_f("invalid originator port");
489 		goto out;
490 	}
491 
492 	debug_f("originator %s port %d, target %s",
493 	    originator, originator_port, target);
494 
495 	/* XXX fine grained permissions */
496 	if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 &&
497 	    auth_opts->permit_port_forwarding_flag &&
498 	    !options.disable_forwarding && (pw->pw_uid == 0 || use_privsep)) {
499 		c = channel_connect_to_path(ssh, target,
500 		    "direct-streamlocal@openssh.com", "direct-streamlocal");
501 	} else {
502 		logit("refused streamlocal port forward: "
503 		    "originator %s port %d, target %s",
504 		    originator, originator_port, target);
505 	}
506 
507 out:
508 	free(originator);
509 	free(target);
510 	return c;
511 }
512 
513 static Channel *
514 server_request_tun(struct ssh *ssh)
515 {
516 	Channel *c = NULL;
517 	u_int mode, tun;
518 	int r, sock;
519 	char *tmp, *ifname = NULL;
520 
521 	if ((r = sshpkt_get_u32(ssh, &mode)) != 0)
522 		sshpkt_fatal(ssh, r, "%s: parse mode", __func__);
523 	switch (mode) {
524 	case SSH_TUNMODE_POINTOPOINT:
525 	case SSH_TUNMODE_ETHERNET:
526 		break;
527 	default:
528 		ssh_packet_send_debug(ssh, "Unsupported tunnel device mode.");
529 		return NULL;
530 	}
531 	if ((options.permit_tun & mode) == 0) {
532 		ssh_packet_send_debug(ssh, "Server has rejected tunnel device "
533 		    "forwarding");
534 		return NULL;
535 	}
536 
537 	if ((r = sshpkt_get_u32(ssh, &tun)) != 0)
538 		sshpkt_fatal(ssh, r, "%s: parse device", __func__);
539 	if (tun > INT_MAX) {
540 		debug_f("invalid tun");
541 		goto done;
542 	}
543 	if (auth_opts->force_tun_device != -1) {
544 		if (tun != SSH_TUNID_ANY &&
545 		    auth_opts->force_tun_device != (int)tun)
546 			goto done;
547 		tun = auth_opts->force_tun_device;
548 	}
549 	sock = tun_open(tun, mode, &ifname);
550 	if (sock < 0)
551 		goto done;
552 	debug("Tunnel forwarding using interface %s", ifname);
553 
554 	c = channel_new(ssh, "tun", SSH_CHANNEL_OPEN, sock, sock, -1,
555 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
556 	c->datagram = 1;
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, u_int32_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 = 0;
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 = NULL;
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 		debug3_f("sign %s key (index %d) using sigalg %s",
728 		    sshkey_type(key), ndx, sigalg == NULL ? "default" : sigalg);
729 		if ((r = sshbuf_put_cstring(sigbuf,
730 		    "hostkeys-prove-00@openssh.com")) != 0 ||
731 		    (r = sshbuf_put_stringb(sigbuf,
732 		    ssh->kex->session_id)) != 0 ||
733 		    (r = sshkey_puts(key, sigbuf)) != 0 ||
734 		    (r = ssh->kex->sign(ssh, key_prv, key_pub, &sig, &slen,
735 		    sshbuf_ptr(sigbuf), sshbuf_len(sigbuf), sigalg)) != 0 ||
736 		    (r = sshbuf_put_string(resp, sig, slen)) != 0) {
737 			error_fr(r, "assemble signature");
738 			goto out;
739 		}
740 	}
741 	/* Success */
742 	*respp = resp;
743 	resp = NULL; /* don't free it */
744 	success = 1;
745  out:
746 	free(sig);
747 	sshbuf_free(resp);
748 	sshbuf_free(sigbuf);
749 	sshkey_free(key);
750 	return success;
751 }
752 
753 static int
754 server_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
755 {
756 	char *rtype = NULL;
757 	u_char want_reply = 0;
758 	int r, success = 0, allocated_listen_port = 0;
759 	u_int port = 0;
760 	struct sshbuf *resp = NULL;
761 	struct passwd *pw = the_authctxt->pw;
762 	struct Forward fwd;
763 
764 	memset(&fwd, 0, sizeof(fwd));
765 	if (pw == NULL || !the_authctxt->valid)
766 		fatal_f("no/invalid user");
767 
768 	if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
769 	    (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
770 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
771 	debug_f("rtype %s want_reply %d", rtype, want_reply);
772 
773 	/* -R style forwarding */
774 	if (strcmp(rtype, "tcpip-forward") == 0) {
775 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 ||
776 		    (r = sshpkt_get_u32(ssh, &port)) != 0)
777 			sshpkt_fatal(ssh, r, "%s: parse tcpip-forward", __func__);
778 		debug_f("tcpip-forward listen %s port %u",
779 		    fwd.listen_host, port);
780 		if (port <= INT_MAX)
781 			fwd.listen_port = (int)port;
782 		/* check permissions */
783 		if (port > INT_MAX ||
784 		    (options.allow_tcp_forwarding & FORWARD_REMOTE) == 0 ||
785 		    !auth_opts->permit_port_forwarding_flag ||
786 		    options.disable_forwarding ||
787 		    (!want_reply && fwd.listen_port == 0) ||
788 		    (fwd.listen_port != 0 &&
789 		    !bind_permitted(fwd.listen_port, pw->pw_uid))) {
790 			success = 0;
791 			ssh_packet_send_debug(ssh, "Server has disabled port forwarding.");
792 		} else {
793 			/* Start listening on the port */
794 			success = channel_setup_remote_fwd_listener(ssh, &fwd,
795 			    &allocated_listen_port, &options.fwd_opts);
796 		}
797 		if ((resp = sshbuf_new()) == NULL)
798 			fatal_f("sshbuf_new");
799 		if (allocated_listen_port != 0 &&
800 		    (r = sshbuf_put_u32(resp, allocated_listen_port)) != 0)
801 			fatal_fr(r, "sshbuf_put_u32");
802 	} else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
803 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 ||
804 		    (r = sshpkt_get_u32(ssh, &port)) != 0)
805 			sshpkt_fatal(ssh, r, "%s: parse cancel-tcpip-forward", __func__);
806 
807 		debug_f("cancel-tcpip-forward addr %s port %d",
808 		    fwd.listen_host, port);
809 		if (port <= INT_MAX) {
810 			fwd.listen_port = (int)port;
811 			success = channel_cancel_rport_listener(ssh, &fwd);
812 		}
813 	} else if (strcmp(rtype, "streamlocal-forward@openssh.com") == 0) {
814 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0)
815 			sshpkt_fatal(ssh, r, "%s: parse streamlocal-forward@openssh.com", __func__);
816 		debug_f("streamlocal-forward listen path %s",
817 		    fwd.listen_path);
818 
819 		/* check permissions */
820 		if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0
821 		    || !auth_opts->permit_port_forwarding_flag ||
822 		    options.disable_forwarding ||
823 		    (pw->pw_uid != 0 && !use_privsep)) {
824 			success = 0;
825 			ssh_packet_send_debug(ssh, "Server has disabled "
826 			    "streamlocal forwarding.");
827 		} else {
828 			/* Start listening on the socket */
829 			success = channel_setup_remote_fwd_listener(ssh,
830 			    &fwd, NULL, &options.fwd_opts);
831 		}
832 	} else if (strcmp(rtype, "cancel-streamlocal-forward@openssh.com") == 0) {
833 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0)
834 			sshpkt_fatal(ssh, r, "%s: parse cancel-streamlocal-forward@openssh.com", __func__);
835 		debug_f("cancel-streamlocal-forward path %s",
836 		    fwd.listen_path);
837 
838 		success = channel_cancel_rport_listener(ssh, &fwd);
839 	} else if (strcmp(rtype, "no-more-sessions@openssh.com") == 0) {
840 		no_more_sessions = 1;
841 		success = 1;
842 	} else if (strcmp(rtype, "hostkeys-prove-00@openssh.com") == 0) {
843 		success = server_input_hostkeys_prove(ssh, &resp);
844 	}
845 	/* XXX sshpkt_get_end() */
846 	if (want_reply) {
847 		if ((r = sshpkt_start(ssh, success ?
848 		    SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE)) != 0 ||
849 		    (success && resp != NULL && (r = sshpkt_putb(ssh, resp)) != 0) ||
850 		    (r = sshpkt_send(ssh)) != 0 ||
851 		    (r = ssh_packet_write_wait(ssh)) != 0)
852 			sshpkt_fatal(ssh, r, "%s: send reply", __func__);
853 	}
854 	free(fwd.listen_host);
855 	free(fwd.listen_path);
856 	free(rtype);
857 	sshbuf_free(resp);
858 	return 0;
859 }
860 
861 static int
862 server_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
863 {
864 	Channel *c;
865 	int r, success = 0;
866 	char *rtype = NULL;
867 	u_char want_reply = 0;
868 	u_int id = 0;
869 
870 	if ((r = sshpkt_get_u32(ssh, &id)) != 0 ||
871 	    (r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
872 	    (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
873 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
874 
875 	debug("server_input_channel_req: channel %u request %s reply %d",
876 	    id, rtype, want_reply);
877 
878 	if (id >= INT_MAX || (c = channel_lookup(ssh, (int)id)) == NULL) {
879 		ssh_packet_disconnect(ssh, "%s: unknown channel %d",
880 		    __func__, id);
881 	}
882 	if (!strcmp(rtype, "eow@openssh.com")) {
883 		if ((r = sshpkt_get_end(ssh)) != 0)
884 			sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
885 		chan_rcvd_eow(ssh, c);
886 	} else if ((c->type == SSH_CHANNEL_LARVAL ||
887 	    c->type == SSH_CHANNEL_OPEN) && strcmp(c->ctype, "session") == 0)
888 		success = session_input_channel_req(ssh, c, rtype);
889 	if (want_reply && !(c->flags & CHAN_CLOSE_SENT)) {
890 		if (!c->have_remote_id)
891 			fatal_f("channel %d: no remote_id", c->self);
892 		if ((r = sshpkt_start(ssh, success ?
893 		    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 ||
894 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
895 		    (r = sshpkt_send(ssh)) != 0)
896 			sshpkt_fatal(ssh, r, "%s: send reply", __func__);
897 	}
898 	free(rtype);
899 	return 0;
900 }
901 
902 static void
903 server_init_dispatch(struct ssh *ssh)
904 {
905 	debug("server_init_dispatch");
906 	ssh_dispatch_init(ssh, &dispatch_protocol_error);
907 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
908 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data);
909 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
910 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
911 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
912 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
913 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
914 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
915 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
916 	ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
917 	/* client_alive */
918 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &server_input_keep_alive);
919 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
920 	ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
921 	ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
922 	/* rekeying */
923 	ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
924 }
925