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