xref: /openbsd-src/usr.bin/ssh/serverloop.c (revision 5c389b79544373bccfce668b646e62e7ba9802a3)
1 /* $OpenBSD: serverloop.c,v 1.236 2023/03/08 04:43:12 guenther 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 "ssh2.h"
67 #include "sshkey.h"
68 #include "cipher.h"
69 #include "kex.h"
70 #include "hostfile.h"
71 #include "auth.h"
72 #include "session.h"
73 #include "dispatch.h"
74 #include "auth-options.h"
75 #include "serverloop.h"
76 #include "ssherr.h"
77 
78 extern ServerOptions options;
79 
80 /* XXX */
81 extern Authctxt *the_authctxt;
82 extern struct sshauthopt *auth_opts;
83 extern int use_privsep;
84 
85 static int no_more_sessions = 0; /* Disallow further sessions. */
86 
87 static volatile sig_atomic_t child_terminated = 0;	/* The child has terminated. */
88 
89 /* Cleanup on signals (!use_privsep case only) */
90 static volatile sig_atomic_t received_sigterm = 0;
91 
92 /* prototypes */
93 static void server_init_dispatch(struct ssh *);
94 
95 /* requested tunnel forwarding interface(s), shared with session.c */
96 char *tun_fwd_ifnames = NULL;
97 
98 /* returns 1 if bind to specified port by specified user is permitted */
99 static int
100 bind_permitted(int port, uid_t uid)
101 {
102 	if (use_privsep)
103 		return 1; /* allow system to decide */
104 	if (port < IPPORT_RESERVED && uid != 0)
105 		return 0;
106 	return 1;
107 }
108 
109 static void
110 sigchld_handler(int sig)
111 {
112 	child_terminated = 1;
113 }
114 
115 static void
116 sigterm_handler(int sig)
117 {
118 	received_sigterm = sig;
119 }
120 
121 static void
122 client_alive_check(struct ssh *ssh)
123 {
124 	char remote_id[512];
125 	int r, channel_id;
126 
127 	/* timeout, check to see how many we have had */
128 	if (options.client_alive_count_max > 0 &&
129 	    ssh_packet_inc_alive_timeouts(ssh) >
130 	    options.client_alive_count_max) {
131 		sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
132 		logit("Timeout, client not responding from %s", remote_id);
133 		cleanup_exit(255);
134 	}
135 
136 	/*
137 	 * send a bogus global/channel request with "wantreply",
138 	 * we should get back a failure
139 	 */
140 	if ((channel_id = channel_find_open(ssh)) == -1) {
141 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
142 		    (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com"))
143 		    != 0 ||
144 		    (r = sshpkt_put_u8(ssh, 1)) != 0) /* boolean: want reply */
145 			fatal_fr(r, "compose");
146 	} else {
147 		channel_request_start(ssh, channel_id,
148 		    "keepalive@openssh.com", 1);
149 	}
150 	if ((r = sshpkt_send(ssh)) != 0)
151 		fatal_fr(r, "send");
152 }
153 
154 /*
155  * Sleep in ppoll() until we can do something.
156  * Optionally, a maximum time can be specified for the duration of
157  * the wait (0 = infinite).
158  */
159 static void
160 wait_until_can_do_something(struct ssh *ssh,
161     int connection_in, int connection_out, struct pollfd **pfdp,
162     u_int *npfd_allocp, u_int *npfd_activep, sigset_t *sigsetp,
163     int *conn_in_readyp, int *conn_out_readyp)
164 {
165 	struct timespec timeout;
166 	char remote_id[512];
167 	int ret;
168 	int client_alive_scheduled = 0;
169 	u_int p;
170 	time_t now;
171 	static time_t last_client_time, unused_connection_expiry;
172 
173 	*conn_in_readyp = *conn_out_readyp = 0;
174 
175 	/* Prepare channel poll. First two pollfd entries are reserved */
176 	ptimeout_init(&timeout);
177 	channel_prepare_poll(ssh, pfdp, npfd_allocp, npfd_activep, 2, &timeout);
178 	now = monotime();
179 	if (*npfd_activep < 2)
180 		fatal_f("bad npfd %u", *npfd_activep); /* shouldn't happen */
181 	if (options.rekey_interval > 0 && !ssh_packet_is_rekeying(ssh)) {
182 		ptimeout_deadline_sec(&timeout,
183 		    ssh_packet_get_rekey_timeout(ssh));
184 	}
185 
186 	/*
187 	 * If no channels are open and UnusedConnectionTimeout is set, then
188 	 * start the clock to terminate the connection.
189 	 */
190 	if (options.unused_connection_timeout != 0) {
191 		if (channel_still_open(ssh) || unused_connection_expiry == 0) {
192 			unused_connection_expiry = now +
193 			    options.unused_connection_timeout;
194 		}
195 		ptimeout_deadline_monotime(&timeout, unused_connection_expiry);
196 	}
197 
198 	/*
199 	 * if using client_alive, set the max timeout accordingly,
200 	 * and indicate that this particular timeout was for client
201 	 * alive by setting the client_alive_scheduled flag.
202 	 *
203 	 * this could be randomized somewhat to make traffic
204 	 * analysis more difficult, but we're not doing it yet.
205 	 */
206 	if (options.client_alive_interval) {
207 		/* Time we last heard from the client OR sent a keepalive */
208 		if (last_client_time == 0)
209 			last_client_time = now;
210 		ptimeout_deadline_sec(&timeout, options.client_alive_interval);
211 		/* XXX ? deadline_monotime(last_client_time + alive_interval) */
212 		client_alive_scheduled = 1;
213 	}
214 
215 #if 0
216 	/* wrong: bad condition XXX */
217 	if (channel_not_very_much_buffered_data())
218 #endif
219 	/* Monitor client connection on reserved pollfd entries */
220 	(*pfdp)[0].fd = connection_in;
221 	(*pfdp)[0].events = POLLIN;
222 	(*pfdp)[1].fd = connection_out;
223 	(*pfdp)[1].events = ssh_packet_have_data_to_write(ssh) ? POLLOUT : 0;
224 
225 	/*
226 	 * If child has terminated and there is enough buffer space to read
227 	 * from it, then read as much as is available and exit.
228 	 */
229 	if (child_terminated && ssh_packet_not_very_much_data_to_write(ssh))
230 		ptimeout_deadline_ms(&timeout, 100);
231 
232 	/* Wait for something to happen, or the timeout to expire. */
233 	ret = ppoll(*pfdp, *npfd_activep, ptimeout_get_tsp(&timeout), sigsetp);
234 
235 	if (ret == -1) {
236 		for (p = 0; p < *npfd_activep; p++)
237 			(*pfdp)[p].revents = 0;
238 		if (errno != EINTR)
239 			fatal_f("ppoll: %.100s", strerror(errno));
240 		return;
241 	}
242 
243 	*conn_in_readyp = (*pfdp)[0].revents != 0;
244 	*conn_out_readyp = (*pfdp)[1].revents != 0;
245 
246 	now = monotime(); /* need to reset after ppoll() */
247 	/* ClientAliveInterval probing */
248 	if (client_alive_scheduled) {
249 		if (ret == 0 &&
250 		    now > last_client_time + options.client_alive_interval) {
251 			/* ppoll timed out and we're due to probe */
252 			client_alive_check(ssh);
253 			last_client_time = now;
254 		} else if (ret != 0 && *conn_in_readyp) {
255 			/* Data from peer; reset probe timer. */
256 			last_client_time = now;
257 		}
258 	}
259 
260 	/* UnusedConnectionTimeout handling */
261 	if (unused_connection_expiry != 0 &&
262 	    now > unused_connection_expiry && !channel_still_open(ssh)) {
263 		sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
264 		logit("terminating inactive connection from %s", remote_id);
265 		cleanup_exit(255);
266 	}
267 }
268 
269 /*
270  * Processes input from the client and the program.  Input data is stored
271  * in buffers and processed later.
272  */
273 static int
274 process_input(struct ssh *ssh, int connection_in)
275 {
276 	int r;
277 
278 	if ((r = ssh_packet_process_read(ssh, connection_in)) == 0)
279 		return 0; /* success */
280 	if (r == SSH_ERR_SYSTEM_ERROR) {
281 		if (errno == EAGAIN || errno == EINTR)
282 			return 0;
283 		if (errno == EPIPE) {
284 			verbose("Connection closed by %.100s port %d",
285 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
286 			return -1;
287 		}
288 		verbose("Read error from remote host %s port %d: %s",
289 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
290 		    strerror(errno));
291 		cleanup_exit(255);
292 	}
293 	return -1;
294 }
295 
296 /*
297  * Sends data from internal buffers to client program stdin.
298  */
299 static void
300 process_output(struct ssh *ssh, int connection_out)
301 {
302 	int r;
303 
304 	/* Send any buffered packet data to the client. */
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 || sigaddset(&bsigset, SIGCHLD) == -1)
345 		error_f("bsigset setup: %s", strerror(errno));
346 	ssh_signal(SIGCHLD, sigchld_handler);
347 	child_terminated = 0;
348 	connection_in = ssh_packet_get_connection_in(ssh);
349 	connection_out = ssh_packet_get_connection_out(ssh);
350 
351 	if (!use_privsep) {
352 		ssh_signal(SIGTERM, sigterm_handler);
353 		ssh_signal(SIGINT, sigterm_handler);
354 		ssh_signal(SIGQUIT, sigterm_handler);
355 	}
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 		wait_until_can_do_something(ssh, connection_in, connection_out,
375 		    &pfd, &npfd_alloc, &npfd_active, &osigset,
376 		    &conn_in_ready, &conn_out_ready);
377 		if (sigprocmask(SIG_UNBLOCK, &bsigset, &osigset) == -1)
378 			error_f("osigset sigprocmask: %s", strerror(errno));
379 
380 		if (received_sigterm) {
381 			logit("Exiting on signal %d", (int)received_sigterm);
382 			/* Clean up sessions, utmp, etc. */
383 			cleanup_exit(255);
384 		}
385 
386 		channel_after_poll(ssh, pfd, npfd_active);
387 		if (conn_in_ready &&
388 		    process_input(ssh, connection_in) < 0)
389 			break;
390 		/* A timeout may have triggered rekeying */
391 		if ((r = ssh_packet_check_rekey(ssh)) != 0)
392 			fatal_fr(r, "cannot start rekeying");
393 		if (conn_out_ready)
394 			process_output(ssh, connection_out);
395 	}
396 	collect_children(ssh);
397 	free(pfd);
398 
399 	/* free all channels, no more reads and writes */
400 	channel_free_all(ssh);
401 
402 	/* free remaining sessions, e.g. remove wtmp entries */
403 	session_destroy_all(ssh, NULL);
404 }
405 
406 static int
407 server_input_keep_alive(int type, u_int32_t seq, struct ssh *ssh)
408 {
409 	debug("Got %d/%u for keepalive", type, seq);
410 	/*
411 	 * reset timeout, since we got a sane answer from the client.
412 	 * even if this was generated by something other than
413 	 * the bogus CHANNEL_REQUEST we send for keepalives.
414 	 */
415 	ssh_packet_set_alive_timeouts(ssh, 0);
416 	return 0;
417 }
418 
419 static Channel *
420 server_request_direct_tcpip(struct ssh *ssh, int *reason, const char **errmsg)
421 {
422 	Channel *c = NULL;
423 	char *target = NULL, *originator = NULL;
424 	u_int target_port = 0, originator_port = 0;
425 	int r;
426 
427 	if ((r = sshpkt_get_cstring(ssh, &target, NULL)) != 0 ||
428 	    (r = sshpkt_get_u32(ssh, &target_port)) != 0 ||
429 	    (r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
430 	    (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
431 	    (r = sshpkt_get_end(ssh)) != 0)
432 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
433 	if (target_port > 0xFFFF) {
434 		error_f("invalid target port");
435 		*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
436 		goto out;
437 	}
438 	if (originator_port > 0xFFFF) {
439 		error_f("invalid originator port");
440 		*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
441 		goto out;
442 	}
443 
444 	debug_f("originator %s port %u, target %s port %u",
445 	    originator, originator_port, target, target_port);
446 
447 	/* XXX fine grained permissions */
448 	if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0 &&
449 	    auth_opts->permit_port_forwarding_flag &&
450 	    !options.disable_forwarding) {
451 		c = channel_connect_to_port(ssh, target, target_port,
452 		    "direct-tcpip", "direct-tcpip", reason, errmsg);
453 	} else {
454 		logit("refused local port forward: "
455 		    "originator %s port %d, target %s port %d",
456 		    originator, originator_port, target, target_port);
457 		if (reason != NULL)
458 			*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
459 	}
460 
461  out:
462 	free(originator);
463 	free(target);
464 	return c;
465 }
466 
467 static Channel *
468 server_request_direct_streamlocal(struct ssh *ssh)
469 {
470 	Channel *c = NULL;
471 	char *target = NULL, *originator = NULL;
472 	u_int originator_port = 0;
473 	struct passwd *pw = the_authctxt->pw;
474 	int r;
475 
476 	if (pw == NULL || !the_authctxt->valid)
477 		fatal_f("no/invalid user");
478 
479 	if ((r = sshpkt_get_cstring(ssh, &target, NULL)) != 0 ||
480 	    (r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
481 	    (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
482 	    (r = sshpkt_get_end(ssh)) != 0)
483 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
484 	if (originator_port > 0xFFFF) {
485 		error_f("invalid originator port");
486 		goto out;
487 	}
488 
489 	debug_f("originator %s port %d, target %s",
490 	    originator, originator_port, target);
491 
492 	/* XXX fine grained permissions */
493 	if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 &&
494 	    auth_opts->permit_port_forwarding_flag &&
495 	    !options.disable_forwarding && (pw->pw_uid == 0 || use_privsep)) {
496 		c = channel_connect_to_path(ssh, target,
497 		    "direct-streamlocal@openssh.com", "direct-streamlocal");
498 	} else {
499 		logit("refused streamlocal port forward: "
500 		    "originator %s port %d, target %s",
501 		    originator, originator_port, target);
502 	}
503 
504 out:
505 	free(originator);
506 	free(target);
507 	return c;
508 }
509 
510 static Channel *
511 server_request_tun(struct ssh *ssh)
512 {
513 	Channel *c = NULL;
514 	u_int mode, tun;
515 	int r, sock;
516 	char *tmp, *ifname = NULL;
517 
518 	if ((r = sshpkt_get_u32(ssh, &mode)) != 0)
519 		sshpkt_fatal(ssh, r, "%s: parse mode", __func__);
520 	switch (mode) {
521 	case SSH_TUNMODE_POINTOPOINT:
522 	case SSH_TUNMODE_ETHERNET:
523 		break;
524 	default:
525 		ssh_packet_send_debug(ssh, "Unsupported tunnel device mode.");
526 		return NULL;
527 	}
528 	if ((options.permit_tun & mode) == 0) {
529 		ssh_packet_send_debug(ssh, "Server has rejected tunnel device "
530 		    "forwarding");
531 		return NULL;
532 	}
533 
534 	if ((r = sshpkt_get_u32(ssh, &tun)) != 0)
535 		sshpkt_fatal(ssh, r, "%s: parse device", __func__);
536 	if (tun > INT_MAX) {
537 		debug_f("invalid tun");
538 		goto done;
539 	}
540 	if (auth_opts->force_tun_device != -1) {
541 		if (tun != SSH_TUNID_ANY &&
542 		    auth_opts->force_tun_device != (int)tun)
543 			goto done;
544 		tun = auth_opts->force_tun_device;
545 	}
546 	sock = tun_open(tun, mode, &ifname);
547 	if (sock < 0)
548 		goto done;
549 	debug("Tunnel forwarding using interface %s", ifname);
550 
551 	c = channel_new(ssh, "tun", SSH_CHANNEL_OPEN, sock, sock, -1,
552 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
553 	c->datagram = 1;
554 
555 	/*
556 	 * Update the list of names exposed to the session
557 	 * XXX remove these if the tunnels are closed (won't matter
558 	 * much if they are already in the environment though)
559 	 */
560 	tmp = tun_fwd_ifnames;
561 	xasprintf(&tun_fwd_ifnames, "%s%s%s",
562 	    tun_fwd_ifnames == NULL ? "" : tun_fwd_ifnames,
563 	    tun_fwd_ifnames == NULL ? "" : ",",
564 	    ifname);
565 	free(tmp);
566 	free(ifname);
567 
568  done:
569 	if (c == NULL)
570 		ssh_packet_send_debug(ssh, "Failed to open the tunnel device.");
571 	return c;
572 }
573 
574 static Channel *
575 server_request_session(struct ssh *ssh)
576 {
577 	Channel *c;
578 	int r;
579 
580 	debug("input_session_request");
581 	if ((r = sshpkt_get_end(ssh)) != 0)
582 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
583 
584 	if (no_more_sessions) {
585 		ssh_packet_disconnect(ssh, "Possible attack: attempt to open a "
586 		    "session after additional sessions disabled");
587 	}
588 
589 	/*
590 	 * A server session has no fd to read or write until a
591 	 * CHANNEL_REQUEST for a shell is made, so we set the type to
592 	 * SSH_CHANNEL_LARVAL.  Additionally, a callback for handling all
593 	 * CHANNEL_REQUEST messages is registered.
594 	 */
595 	c = channel_new(ssh, "session", SSH_CHANNEL_LARVAL,
596 	    -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT,
597 	    0, "server-session", 1);
598 	if (session_open(the_authctxt, c->self) != 1) {
599 		debug("session open failed, free channel %d", c->self);
600 		channel_free(ssh, c);
601 		return NULL;
602 	}
603 	channel_register_cleanup(ssh, c->self, session_close_by_channel, 0);
604 	return c;
605 }
606 
607 static int
608 server_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
609 {
610 	Channel *c = NULL;
611 	char *ctype = NULL;
612 	const char *errmsg = NULL;
613 	int r, reason = SSH2_OPEN_CONNECT_FAILED;
614 	u_int rchan = 0, rmaxpack = 0, rwindow = 0;
615 
616 	if ((r = sshpkt_get_cstring(ssh, &ctype, NULL)) != 0 ||
617 	    (r = sshpkt_get_u32(ssh, &rchan)) != 0 ||
618 	    (r = sshpkt_get_u32(ssh, &rwindow)) != 0 ||
619 	    (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0)
620 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
621 	debug_f("ctype %s rchan %u win %u max %u",
622 	    ctype, rchan, rwindow, rmaxpack);
623 
624 	if (strcmp(ctype, "session") == 0) {
625 		c = server_request_session(ssh);
626 	} else if (strcmp(ctype, "direct-tcpip") == 0) {
627 		c = server_request_direct_tcpip(ssh, &reason, &errmsg);
628 	} else if (strcmp(ctype, "direct-streamlocal@openssh.com") == 0) {
629 		c = server_request_direct_streamlocal(ssh);
630 	} else if (strcmp(ctype, "tun@openssh.com") == 0) {
631 		c = server_request_tun(ssh);
632 	}
633 	if (c != NULL) {
634 		debug_f("confirm %s", ctype);
635 		c->remote_id = rchan;
636 		c->have_remote_id = 1;
637 		c->remote_window = rwindow;
638 		c->remote_maxpacket = rmaxpack;
639 		if (c->type != SSH_CHANNEL_CONNECTING) {
640 			if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
641 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
642 			    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
643 			    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
644 			    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
645 			    (r = sshpkt_send(ssh)) != 0) {
646 				sshpkt_fatal(ssh, r,
647 				    "%s: send open confirm", __func__);
648 			}
649 		}
650 	} else {
651 		debug_f("failure %s", ctype);
652 		if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
653 		    (r = sshpkt_put_u32(ssh, rchan)) != 0 ||
654 		    (r = sshpkt_put_u32(ssh, reason)) != 0 ||
655 		    (r = sshpkt_put_cstring(ssh, errmsg ? errmsg : "open failed")) != 0 ||
656 		    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
657 		    (r = sshpkt_send(ssh)) != 0) {
658 			sshpkt_fatal(ssh, r,
659 			    "%s: send open failure", __func__);
660 		}
661 	}
662 	free(ctype);
663 	return 0;
664 }
665 
666 static int
667 server_input_hostkeys_prove(struct ssh *ssh, struct sshbuf **respp)
668 {
669 	struct sshbuf *resp = NULL;
670 	struct sshbuf *sigbuf = NULL;
671 	struct sshkey *key = NULL, *key_pub = NULL, *key_prv = NULL;
672 	int r, ndx, success = 0;
673 	const u_char *blob;
674 	const char *sigalg, *kex_rsa_sigalg = NULL;
675 	u_char *sig = 0;
676 	size_t blen, slen;
677 
678 	if ((resp = sshbuf_new()) == NULL || (sigbuf = sshbuf_new()) == NULL)
679 		fatal_f("sshbuf_new");
680 	if (sshkey_type_plain(sshkey_type_from_name(
681 	    ssh->kex->hostkey_alg)) == KEY_RSA)
682 		kex_rsa_sigalg = ssh->kex->hostkey_alg;
683 	while (ssh_packet_remaining(ssh) > 0) {
684 		sshkey_free(key);
685 		key = NULL;
686 		if ((r = sshpkt_get_string_direct(ssh, &blob, &blen)) != 0 ||
687 		    (r = sshkey_from_blob(blob, blen, &key)) != 0) {
688 			error_fr(r, "parse key");
689 			goto out;
690 		}
691 		/*
692 		 * Better check that this is actually one of our hostkeys
693 		 * before attempting to sign anything with it.
694 		 */
695 		if ((ndx = ssh->kex->host_key_index(key, 1, ssh)) == -1) {
696 			error_f("unknown host %s key", sshkey_type(key));
697 			goto out;
698 		}
699 		/*
700 		 * XXX refactor: make kex->sign just use an index rather
701 		 * than passing in public and private keys
702 		 */
703 		if ((key_prv = get_hostkey_by_index(ndx)) == NULL &&
704 		    (key_pub = get_hostkey_public_by_index(ndx, ssh)) == NULL) {
705 			error_f("can't retrieve hostkey %d", ndx);
706 			goto out;
707 		}
708 		sshbuf_reset(sigbuf);
709 		free(sig);
710 		sig = NULL;
711 		/*
712 		 * For RSA keys, prefer to use the signature type negotiated
713 		 * during KEX to the default (SHA1).
714 		 */
715 		sigalg = NULL;
716 		if (sshkey_type_plain(key->type) == KEY_RSA) {
717 			if (kex_rsa_sigalg != NULL)
718 				sigalg = kex_rsa_sigalg;
719 			else if (ssh->kex->flags & KEX_RSA_SHA2_512_SUPPORTED)
720 				sigalg = "rsa-sha2-512";
721 			else if (ssh->kex->flags & KEX_RSA_SHA2_256_SUPPORTED)
722 				sigalg = "rsa-sha2-256";
723 		}
724 		debug3_f("sign %s key (index %d) using sigalg %s",
725 		    sshkey_type(key), ndx, sigalg == NULL ? "default" : sigalg);
726 		if ((r = sshbuf_put_cstring(sigbuf,
727 		    "hostkeys-prove-00@openssh.com")) != 0 ||
728 		    (r = sshbuf_put_stringb(sigbuf,
729 		    ssh->kex->session_id)) != 0 ||
730 		    (r = sshkey_puts(key, sigbuf)) != 0 ||
731 		    (r = ssh->kex->sign(ssh, key_prv, key_pub, &sig, &slen,
732 		    sshbuf_ptr(sigbuf), sshbuf_len(sigbuf), sigalg)) != 0 ||
733 		    (r = sshbuf_put_string(resp, sig, slen)) != 0) {
734 			error_fr(r, "assemble signature");
735 			goto out;
736 		}
737 	}
738 	/* Success */
739 	*respp = resp;
740 	resp = NULL; /* don't free it */
741 	success = 1;
742  out:
743 	free(sig);
744 	sshbuf_free(resp);
745 	sshbuf_free(sigbuf);
746 	sshkey_free(key);
747 	return success;
748 }
749 
750 static int
751 server_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
752 {
753 	char *rtype = NULL;
754 	u_char want_reply = 0;
755 	int r, success = 0, allocated_listen_port = 0;
756 	u_int port = 0;
757 	struct sshbuf *resp = NULL;
758 	struct passwd *pw = the_authctxt->pw;
759 	struct Forward fwd;
760 
761 	memset(&fwd, 0, sizeof(fwd));
762 	if (pw == NULL || !the_authctxt->valid)
763 		fatal_f("no/invalid user");
764 
765 	if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
766 	    (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
767 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
768 	debug_f("rtype %s want_reply %d", rtype, want_reply);
769 
770 	/* -R style forwarding */
771 	if (strcmp(rtype, "tcpip-forward") == 0) {
772 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 ||
773 		    (r = sshpkt_get_u32(ssh, &port)) != 0)
774 			sshpkt_fatal(ssh, r, "%s: parse tcpip-forward", __func__);
775 		debug_f("tcpip-forward listen %s port %u",
776 		    fwd.listen_host, port);
777 		if (port <= INT_MAX)
778 			fwd.listen_port = (int)port;
779 		/* check permissions */
780 		if (port > INT_MAX ||
781 		    (options.allow_tcp_forwarding & FORWARD_REMOTE) == 0 ||
782 		    !auth_opts->permit_port_forwarding_flag ||
783 		    options.disable_forwarding ||
784 		    (!want_reply && fwd.listen_port == 0) ||
785 		    (fwd.listen_port != 0 &&
786 		    !bind_permitted(fwd.listen_port, pw->pw_uid))) {
787 			success = 0;
788 			ssh_packet_send_debug(ssh, "Server has disabled port forwarding.");
789 		} else {
790 			/* Start listening on the port */
791 			success = channel_setup_remote_fwd_listener(ssh, &fwd,
792 			    &allocated_listen_port, &options.fwd_opts);
793 		}
794 		if ((resp = sshbuf_new()) == NULL)
795 			fatal_f("sshbuf_new");
796 		if (allocated_listen_port != 0 &&
797 		    (r = sshbuf_put_u32(resp, allocated_listen_port)) != 0)
798 			fatal_fr(r, "sshbuf_put_u32");
799 	} else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
800 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 ||
801 		    (r = sshpkt_get_u32(ssh, &port)) != 0)
802 			sshpkt_fatal(ssh, r, "%s: parse cancel-tcpip-forward", __func__);
803 
804 		debug_f("cancel-tcpip-forward addr %s port %d",
805 		    fwd.listen_host, port);
806 		if (port <= INT_MAX) {
807 			fwd.listen_port = (int)port;
808 			success = channel_cancel_rport_listener(ssh, &fwd);
809 		}
810 	} else if (strcmp(rtype, "streamlocal-forward@openssh.com") == 0) {
811 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0)
812 			sshpkt_fatal(ssh, r, "%s: parse streamlocal-forward@openssh.com", __func__);
813 		debug_f("streamlocal-forward listen path %s",
814 		    fwd.listen_path);
815 
816 		/* check permissions */
817 		if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0
818 		    || !auth_opts->permit_port_forwarding_flag ||
819 		    options.disable_forwarding ||
820 		    (pw->pw_uid != 0 && !use_privsep)) {
821 			success = 0;
822 			ssh_packet_send_debug(ssh, "Server has disabled "
823 			    "streamlocal forwarding.");
824 		} else {
825 			/* Start listening on the socket */
826 			success = channel_setup_remote_fwd_listener(ssh,
827 			    &fwd, NULL, &options.fwd_opts);
828 		}
829 	} else if (strcmp(rtype, "cancel-streamlocal-forward@openssh.com") == 0) {
830 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0)
831 			sshpkt_fatal(ssh, r, "%s: parse cancel-streamlocal-forward@openssh.com", __func__);
832 		debug_f("cancel-streamlocal-forward path %s",
833 		    fwd.listen_path);
834 
835 		success = channel_cancel_rport_listener(ssh, &fwd);
836 	} else if (strcmp(rtype, "no-more-sessions@openssh.com") == 0) {
837 		no_more_sessions = 1;
838 		success = 1;
839 	} else if (strcmp(rtype, "hostkeys-prove-00@openssh.com") == 0) {
840 		success = server_input_hostkeys_prove(ssh, &resp);
841 	}
842 	/* XXX sshpkt_get_end() */
843 	if (want_reply) {
844 		if ((r = sshpkt_start(ssh, success ?
845 		    SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE)) != 0 ||
846 		    (success && resp != NULL && (r = sshpkt_putb(ssh, resp)) != 0) ||
847 		    (r = sshpkt_send(ssh)) != 0 ||
848 		    (r = ssh_packet_write_wait(ssh)) != 0)
849 			sshpkt_fatal(ssh, r, "%s: send reply", __func__);
850 	}
851 	free(fwd.listen_host);
852 	free(fwd.listen_path);
853 	free(rtype);
854 	sshbuf_free(resp);
855 	return 0;
856 }
857 
858 static int
859 server_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
860 {
861 	Channel *c;
862 	int r, success = 0;
863 	char *rtype = NULL;
864 	u_char want_reply = 0;
865 	u_int id = 0;
866 
867 	if ((r = sshpkt_get_u32(ssh, &id)) != 0 ||
868 	    (r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
869 	    (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
870 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
871 
872 	debug("server_input_channel_req: channel %u request %s reply %d",
873 	    id, rtype, want_reply);
874 
875 	if (id >= INT_MAX || (c = channel_lookup(ssh, (int)id)) == NULL) {
876 		ssh_packet_disconnect(ssh, "%s: unknown channel %d",
877 		    __func__, id);
878 	}
879 	if (!strcmp(rtype, "eow@openssh.com")) {
880 		if ((r = sshpkt_get_end(ssh)) != 0)
881 			sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
882 		chan_rcvd_eow(ssh, c);
883 	} else if ((c->type == SSH_CHANNEL_LARVAL ||
884 	    c->type == SSH_CHANNEL_OPEN) && strcmp(c->ctype, "session") == 0)
885 		success = session_input_channel_req(ssh, c, rtype);
886 	if (want_reply && !(c->flags & CHAN_CLOSE_SENT)) {
887 		if (!c->have_remote_id)
888 			fatal_f("channel %d: no remote_id", c->self);
889 		if ((r = sshpkt_start(ssh, success ?
890 		    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 ||
891 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
892 		    (r = sshpkt_send(ssh)) != 0)
893 			sshpkt_fatal(ssh, r, "%s: send reply", __func__);
894 	}
895 	free(rtype);
896 	return 0;
897 }
898 
899 static void
900 server_init_dispatch(struct ssh *ssh)
901 {
902 	debug("server_init_dispatch");
903 	ssh_dispatch_init(ssh, &dispatch_protocol_error);
904 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
905 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data);
906 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
907 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
908 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
909 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
910 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
911 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
912 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
913 	ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
914 	/* client_alive */
915 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &server_input_keep_alive);
916 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
917 	ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
918 	ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
919 	/* rekeying */
920 	ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
921 }
922