xref: /openbsd-src/usr.bin/ssh/serverloop.c (revision 198f0b5dccae76a18ee7603263e9fb6884a167ec)
1 /* $OpenBSD: serverloop.c,v 1.231 2022/01/22 00:49:34 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 		if (!ssh_packet_is_rekeying(ssh))
390 			channel_after_poll(ssh, pfd, npfd_active);
391 		if (conn_in_ready &&
392 		    process_input(ssh, connection_in) < 0)
393 			break;
394 		/* A timeout may have triggered rekeying */
395 		if ((r = ssh_packet_check_rekey(ssh)) != 0)
396 			fatal_fr(r, "cannot start rekeying");
397 		if (conn_out_ready)
398 			process_output(ssh, connection_out);
399 	}
400 	collect_children(ssh);
401 	free(pfd);
402 
403 	/* free all channels, no more reads and writes */
404 	channel_free_all(ssh);
405 
406 	/* free remaining sessions, e.g. remove wtmp entries */
407 	session_destroy_all(ssh, NULL);
408 }
409 
410 static int
411 server_input_keep_alive(int type, u_int32_t seq, struct ssh *ssh)
412 {
413 	debug("Got %d/%u for keepalive", type, seq);
414 	/*
415 	 * reset timeout, since we got a sane answer from the client.
416 	 * even if this was generated by something other than
417 	 * the bogus CHANNEL_REQUEST we send for keepalives.
418 	 */
419 	ssh_packet_set_alive_timeouts(ssh, 0);
420 	return 0;
421 }
422 
423 static Channel *
424 server_request_direct_tcpip(struct ssh *ssh, int *reason, const char **errmsg)
425 {
426 	Channel *c = NULL;
427 	char *target = NULL, *originator = NULL;
428 	u_int target_port = 0, originator_port = 0;
429 	int r;
430 
431 	if ((r = sshpkt_get_cstring(ssh, &target, NULL)) != 0 ||
432 	    (r = sshpkt_get_u32(ssh, &target_port)) != 0 ||
433 	    (r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
434 	    (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
435 	    (r = sshpkt_get_end(ssh)) != 0)
436 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
437 	if (target_port > 0xFFFF) {
438 		error_f("invalid target port");
439 		*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
440 		goto out;
441 	}
442 	if (originator_port > 0xFFFF) {
443 		error_f("invalid originator port");
444 		*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
445 		goto out;
446 	}
447 
448 	debug_f("originator %s port %u, target %s port %u",
449 	    originator, originator_port, target, target_port);
450 
451 	/* XXX fine grained permissions */
452 	if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0 &&
453 	    auth_opts->permit_port_forwarding_flag &&
454 	    !options.disable_forwarding) {
455 		c = channel_connect_to_port(ssh, target, target_port,
456 		    "direct-tcpip", "direct-tcpip", reason, errmsg);
457 	} else {
458 		logit("refused local port forward: "
459 		    "originator %s port %d, target %s port %d",
460 		    originator, originator_port, target, target_port);
461 		if (reason != NULL)
462 			*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
463 	}
464 
465  out:
466 	free(originator);
467 	free(target);
468 	return c;
469 }
470 
471 static Channel *
472 server_request_direct_streamlocal(struct ssh *ssh)
473 {
474 	Channel *c = NULL;
475 	char *target = NULL, *originator = NULL;
476 	u_int originator_port = 0;
477 	struct passwd *pw = the_authctxt->pw;
478 	int r;
479 
480 	if (pw == NULL || !the_authctxt->valid)
481 		fatal_f("no/invalid user");
482 
483 	if ((r = sshpkt_get_cstring(ssh, &target, NULL)) != 0 ||
484 	    (r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
485 	    (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
486 	    (r = sshpkt_get_end(ssh)) != 0)
487 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
488 	if (originator_port > 0xFFFF) {
489 		error_f("invalid originator port");
490 		goto out;
491 	}
492 
493 	debug_f("originator %s port %d, target %s",
494 	    originator, originator_port, target);
495 
496 	/* XXX fine grained permissions */
497 	if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 &&
498 	    auth_opts->permit_port_forwarding_flag &&
499 	    !options.disable_forwarding && (pw->pw_uid == 0 || use_privsep)) {
500 		c = channel_connect_to_path(ssh, target,
501 		    "direct-streamlocal@openssh.com", "direct-streamlocal");
502 	} else {
503 		logit("refused streamlocal port forward: "
504 		    "originator %s port %d, target %s",
505 		    originator, originator_port, target);
506 	}
507 
508 out:
509 	free(originator);
510 	free(target);
511 	return c;
512 }
513 
514 static Channel *
515 server_request_tun(struct ssh *ssh)
516 {
517 	Channel *c = NULL;
518 	u_int mode, tun;
519 	int r, sock;
520 	char *tmp, *ifname = NULL;
521 
522 	if ((r = sshpkt_get_u32(ssh, &mode)) != 0)
523 		sshpkt_fatal(ssh, r, "%s: parse mode", __func__);
524 	switch (mode) {
525 	case SSH_TUNMODE_POINTOPOINT:
526 	case SSH_TUNMODE_ETHERNET:
527 		break;
528 	default:
529 		ssh_packet_send_debug(ssh, "Unsupported tunnel device mode.");
530 		return NULL;
531 	}
532 	if ((options.permit_tun & mode) == 0) {
533 		ssh_packet_send_debug(ssh, "Server has rejected tunnel device "
534 		    "forwarding");
535 		return NULL;
536 	}
537 
538 	if ((r = sshpkt_get_u32(ssh, &tun)) != 0)
539 		sshpkt_fatal(ssh, r, "%s: parse device", __func__);
540 	if (tun > INT_MAX) {
541 		debug_f("invalid tun");
542 		goto done;
543 	}
544 	if (auth_opts->force_tun_device != -1) {
545 		if (tun != SSH_TUNID_ANY &&
546 		    auth_opts->force_tun_device != (int)tun)
547 			goto done;
548 		tun = auth_opts->force_tun_device;
549 	}
550 	sock = tun_open(tun, mode, &ifname);
551 	if (sock < 0)
552 		goto done;
553 	debug("Tunnel forwarding using interface %s", ifname);
554 
555 	c = channel_new(ssh, "tun", SSH_CHANNEL_OPEN, sock, sock, -1,
556 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
557 	c->datagram = 1;
558 
559 	/*
560 	 * Update the list of names exposed to the session
561 	 * XXX remove these if the tunnels are closed (won't matter
562 	 * much if they are already in the environment though)
563 	 */
564 	tmp = tun_fwd_ifnames;
565 	xasprintf(&tun_fwd_ifnames, "%s%s%s",
566 	    tun_fwd_ifnames == NULL ? "" : tun_fwd_ifnames,
567 	    tun_fwd_ifnames == NULL ? "" : ",",
568 	    ifname);
569 	free(tmp);
570 	free(ifname);
571 
572  done:
573 	if (c == NULL)
574 		ssh_packet_send_debug(ssh, "Failed to open the tunnel device.");
575 	return c;
576 }
577 
578 static Channel *
579 server_request_session(struct ssh *ssh)
580 {
581 	Channel *c;
582 	int r;
583 
584 	debug("input_session_request");
585 	if ((r = sshpkt_get_end(ssh)) != 0)
586 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
587 
588 	if (no_more_sessions) {
589 		ssh_packet_disconnect(ssh, "Possible attack: attempt to open a "
590 		    "session after additional sessions disabled");
591 	}
592 
593 	/*
594 	 * A server session has no fd to read or write until a
595 	 * CHANNEL_REQUEST for a shell is made, so we set the type to
596 	 * SSH_CHANNEL_LARVAL.  Additionally, a callback for handling all
597 	 * CHANNEL_REQUEST messages is registered.
598 	 */
599 	c = channel_new(ssh, "session", SSH_CHANNEL_LARVAL,
600 	    -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT,
601 	    0, "server-session", 1);
602 	if (session_open(the_authctxt, c->self) != 1) {
603 		debug("session open failed, free channel %d", c->self);
604 		channel_free(ssh, c);
605 		return NULL;
606 	}
607 	channel_register_cleanup(ssh, c->self, session_close_by_channel, 0);
608 	return c;
609 }
610 
611 static int
612 server_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
613 {
614 	Channel *c = NULL;
615 	char *ctype = NULL;
616 	const char *errmsg = NULL;
617 	int r, reason = SSH2_OPEN_CONNECT_FAILED;
618 	u_int rchan = 0, rmaxpack = 0, rwindow = 0;
619 
620 	if ((r = sshpkt_get_cstring(ssh, &ctype, NULL)) != 0 ||
621 	    (r = sshpkt_get_u32(ssh, &rchan)) != 0 ||
622 	    (r = sshpkt_get_u32(ssh, &rwindow)) != 0 ||
623 	    (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0)
624 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
625 	debug_f("ctype %s rchan %u win %u max %u",
626 	    ctype, rchan, rwindow, rmaxpack);
627 
628 	if (strcmp(ctype, "session") == 0) {
629 		c = server_request_session(ssh);
630 	} else if (strcmp(ctype, "direct-tcpip") == 0) {
631 		c = server_request_direct_tcpip(ssh, &reason, &errmsg);
632 	} else if (strcmp(ctype, "direct-streamlocal@openssh.com") == 0) {
633 		c = server_request_direct_streamlocal(ssh);
634 	} else if (strcmp(ctype, "tun@openssh.com") == 0) {
635 		c = server_request_tun(ssh);
636 	}
637 	if (c != NULL) {
638 		debug_f("confirm %s", ctype);
639 		c->remote_id = rchan;
640 		c->have_remote_id = 1;
641 		c->remote_window = rwindow;
642 		c->remote_maxpacket = rmaxpack;
643 		if (c->type != SSH_CHANNEL_CONNECTING) {
644 			if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
645 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
646 			    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
647 			    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
648 			    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
649 			    (r = sshpkt_send(ssh)) != 0) {
650 				sshpkt_fatal(ssh, r,
651 				    "%s: send open confirm", __func__);
652 			}
653 		}
654 	} else {
655 		debug_f("failure %s", ctype);
656 		if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
657 		    (r = sshpkt_put_u32(ssh, rchan)) != 0 ||
658 		    (r = sshpkt_put_u32(ssh, reason)) != 0 ||
659 		    (r = sshpkt_put_cstring(ssh, errmsg ? errmsg : "open failed")) != 0 ||
660 		    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
661 		    (r = sshpkt_send(ssh)) != 0) {
662 			sshpkt_fatal(ssh, r,
663 			    "%s: send open failure", __func__);
664 		}
665 	}
666 	free(ctype);
667 	return 0;
668 }
669 
670 static int
671 server_input_hostkeys_prove(struct ssh *ssh, struct sshbuf **respp)
672 {
673 	struct sshbuf *resp = NULL;
674 	struct sshbuf *sigbuf = NULL;
675 	struct sshkey *key = NULL, *key_pub = NULL, *key_prv = NULL;
676 	int r, ndx, success = 0;
677 	const u_char *blob;
678 	const char *sigalg, *kex_rsa_sigalg = NULL;
679 	u_char *sig = 0;
680 	size_t blen, slen;
681 
682 	if ((resp = sshbuf_new()) == NULL || (sigbuf = sshbuf_new()) == NULL)
683 		fatal_f("sshbuf_new");
684 	if (sshkey_type_plain(sshkey_type_from_name(
685 	    ssh->kex->hostkey_alg)) == KEY_RSA)
686 		kex_rsa_sigalg = ssh->kex->hostkey_alg;
687 	while (ssh_packet_remaining(ssh) > 0) {
688 		sshkey_free(key);
689 		key = NULL;
690 		if ((r = sshpkt_get_string_direct(ssh, &blob, &blen)) != 0 ||
691 		    (r = sshkey_from_blob(blob, blen, &key)) != 0) {
692 			error_fr(r, "parse key");
693 			goto out;
694 		}
695 		/*
696 		 * Better check that this is actually one of our hostkeys
697 		 * before attempting to sign anything with it.
698 		 */
699 		if ((ndx = ssh->kex->host_key_index(key, 1, ssh)) == -1) {
700 			error_f("unknown host %s key", sshkey_type(key));
701 			goto out;
702 		}
703 		/*
704 		 * XXX refactor: make kex->sign just use an index rather
705 		 * than passing in public and private keys
706 		 */
707 		if ((key_prv = get_hostkey_by_index(ndx)) == NULL &&
708 		    (key_pub = get_hostkey_public_by_index(ndx, ssh)) == NULL) {
709 			error_f("can't retrieve hostkey %d", ndx);
710 			goto out;
711 		}
712 		sshbuf_reset(sigbuf);
713 		free(sig);
714 		sig = NULL;
715 		/*
716 		 * For RSA keys, prefer to use the signature type negotiated
717 		 * during KEX to the default (SHA1).
718 		 */
719 		sigalg = NULL;
720 		if (sshkey_type_plain(key->type) == KEY_RSA) {
721 			if (kex_rsa_sigalg != NULL)
722 				sigalg = kex_rsa_sigalg;
723 			else if (ssh->kex->flags & KEX_RSA_SHA2_512_SUPPORTED)
724 				sigalg = "rsa-sha2-512";
725 			else if (ssh->kex->flags & KEX_RSA_SHA2_256_SUPPORTED)
726 				sigalg = "rsa-sha2-256";
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, u_int32_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 		    (fwd.listen_port != 0 &&
790 		    !bind_permitted(fwd.listen_port, pw->pw_uid))) {
791 			success = 0;
792 			ssh_packet_send_debug(ssh, "Server has disabled port forwarding.");
793 		} else {
794 			/* Start listening on the port */
795 			success = channel_setup_remote_fwd_listener(ssh, &fwd,
796 			    &allocated_listen_port, &options.fwd_opts);
797 		}
798 		if ((resp = sshbuf_new()) == NULL)
799 			fatal_f("sshbuf_new");
800 		if (allocated_listen_port != 0 &&
801 		    (r = sshbuf_put_u32(resp, allocated_listen_port)) != 0)
802 			fatal_fr(r, "sshbuf_put_u32");
803 	} else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
804 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 ||
805 		    (r = sshpkt_get_u32(ssh, &port)) != 0)
806 			sshpkt_fatal(ssh, r, "%s: parse cancel-tcpip-forward", __func__);
807 
808 		debug_f("cancel-tcpip-forward addr %s port %d",
809 		    fwd.listen_host, port);
810 		if (port <= INT_MAX) {
811 			fwd.listen_port = (int)port;
812 			success = channel_cancel_rport_listener(ssh, &fwd);
813 		}
814 	} else if (strcmp(rtype, "streamlocal-forward@openssh.com") == 0) {
815 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0)
816 			sshpkt_fatal(ssh, r, "%s: parse streamlocal-forward@openssh.com", __func__);
817 		debug_f("streamlocal-forward listen path %s",
818 		    fwd.listen_path);
819 
820 		/* check permissions */
821 		if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0
822 		    || !auth_opts->permit_port_forwarding_flag ||
823 		    options.disable_forwarding ||
824 		    (pw->pw_uid != 0 && !use_privsep)) {
825 			success = 0;
826 			ssh_packet_send_debug(ssh, "Server has disabled "
827 			    "streamlocal forwarding.");
828 		} else {
829 			/* Start listening on the socket */
830 			success = channel_setup_remote_fwd_listener(ssh,
831 			    &fwd, NULL, &options.fwd_opts);
832 		}
833 	} else if (strcmp(rtype, "cancel-streamlocal-forward@openssh.com") == 0) {
834 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0)
835 			sshpkt_fatal(ssh, r, "%s: parse cancel-streamlocal-forward@openssh.com", __func__);
836 		debug_f("cancel-streamlocal-forward path %s",
837 		    fwd.listen_path);
838 
839 		success = channel_cancel_rport_listener(ssh, &fwd);
840 	} else if (strcmp(rtype, "no-more-sessions@openssh.com") == 0) {
841 		no_more_sessions = 1;
842 		success = 1;
843 	} else if (strcmp(rtype, "hostkeys-prove-00@openssh.com") == 0) {
844 		success = server_input_hostkeys_prove(ssh, &resp);
845 	}
846 	/* XXX sshpkt_get_end() */
847 	if (want_reply) {
848 		if ((r = sshpkt_start(ssh, success ?
849 		    SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE)) != 0 ||
850 		    (success && resp != NULL && (r = sshpkt_putb(ssh, resp)) != 0) ||
851 		    (r = sshpkt_send(ssh)) != 0 ||
852 		    (r = ssh_packet_write_wait(ssh)) != 0)
853 			sshpkt_fatal(ssh, r, "%s: send reply", __func__);
854 	}
855 	free(fwd.listen_host);
856 	free(fwd.listen_path);
857 	free(rtype);
858 	sshbuf_free(resp);
859 	return 0;
860 }
861 
862 static int
863 server_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
864 {
865 	Channel *c;
866 	int r, success = 0;
867 	char *rtype = NULL;
868 	u_char want_reply = 0;
869 	u_int id = 0;
870 
871 	if ((r = sshpkt_get_u32(ssh, &id)) != 0 ||
872 	    (r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
873 	    (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
874 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
875 
876 	debug("server_input_channel_req: channel %u request %s reply %d",
877 	    id, rtype, want_reply);
878 
879 	if (id >= INT_MAX || (c = channel_lookup(ssh, (int)id)) == NULL) {
880 		ssh_packet_disconnect(ssh, "%s: unknown channel %d",
881 		    __func__, id);
882 	}
883 	if (!strcmp(rtype, "eow@openssh.com")) {
884 		if ((r = sshpkt_get_end(ssh)) != 0)
885 			sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
886 		chan_rcvd_eow(ssh, c);
887 	} else if ((c->type == SSH_CHANNEL_LARVAL ||
888 	    c->type == SSH_CHANNEL_OPEN) && strcmp(c->ctype, "session") == 0)
889 		success = session_input_channel_req(ssh, c, rtype);
890 	if (want_reply && !(c->flags & CHAN_CLOSE_SENT)) {
891 		if (!c->have_remote_id)
892 			fatal_f("channel %d: no remote_id", c->self);
893 		if ((r = sshpkt_start(ssh, success ?
894 		    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 ||
895 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
896 		    (r = sshpkt_send(ssh)) != 0)
897 			sshpkt_fatal(ssh, r, "%s: send reply", __func__);
898 	}
899 	free(rtype);
900 	return 0;
901 }
902 
903 static void
904 server_init_dispatch(struct ssh *ssh)
905 {
906 	debug("server_init_dispatch");
907 	ssh_dispatch_init(ssh, &dispatch_protocol_error);
908 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
909 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data);
910 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
911 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
912 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
913 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
914 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
915 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
916 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
917 	ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
918 	/* client_alive */
919 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &server_input_keep_alive);
920 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
921 	ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
922 	ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
923 	/* rekeying */
924 	ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
925 }
926