xref: /openbsd-src/usr.bin/ssh/serverloop.c (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1 /* $OpenBSD: serverloop.c,v 1.186 2016/09/12 01:22:38 deraadt 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 <signal.h>
50 #include <string.h>
51 #include <termios.h>
52 #include <unistd.h>
53 #include <stdarg.h>
54 
55 #include "xmalloc.h"
56 #include "packet.h"
57 #include "buffer.h"
58 #include "log.h"
59 #include "misc.h"
60 #include "servconf.h"
61 #include "canohost.h"
62 #include "sshpty.h"
63 #include "channels.h"
64 #include "compat.h"
65 #include "ssh2.h"
66 #include "key.h"
67 #include "cipher.h"
68 #include "kex.h"
69 #include "hostfile.h"
70 #include "auth.h"
71 #include "session.h"
72 #include "dispatch.h"
73 #include "auth-options.h"
74 #include "serverloop.h"
75 #include "ssherr.h"
76 
77 extern ServerOptions options;
78 
79 /* XXX */
80 extern Authctxt *the_authctxt;
81 extern int use_privsep;
82 
83 static int no_more_sessions = 0; /* Disallow further sessions. */
84 
85 /*
86  * This SIGCHLD kludge is used to detect when the child exits.  The server
87  * will exit after that, as soon as forwarded connections have terminated.
88  */
89 
90 static volatile sig_atomic_t child_terminated = 0;	/* The child has terminated. */
91 
92 /* Cleanup on signals (!use_privsep case only) */
93 static volatile sig_atomic_t received_sigterm = 0;
94 
95 /* prototypes */
96 static void server_init_dispatch(void);
97 
98 /*
99  * we write to this pipe if a SIGCHLD is caught in order to avoid
100  * the race between select() and child_terminated
101  */
102 static int notify_pipe[2];
103 static void
104 notify_setup(void)
105 {
106 	if (pipe(notify_pipe) < 0) {
107 		error("pipe(notify_pipe) failed %s", strerror(errno));
108 	} else if ((fcntl(notify_pipe[0], F_SETFD, FD_CLOEXEC) == -1) ||
109 	    (fcntl(notify_pipe[1], F_SETFD, FD_CLOEXEC) == -1)) {
110 		error("fcntl(notify_pipe, F_SETFD) failed %s", strerror(errno));
111 		close(notify_pipe[0]);
112 		close(notify_pipe[1]);
113 	} else {
114 		set_nonblock(notify_pipe[0]);
115 		set_nonblock(notify_pipe[1]);
116 		return;
117 	}
118 	notify_pipe[0] = -1;	/* read end */
119 	notify_pipe[1] = -1;	/* write end */
120 }
121 static void
122 notify_parent(void)
123 {
124 	if (notify_pipe[1] != -1)
125 		(void)write(notify_pipe[1], "", 1);
126 }
127 static void
128 notify_prepare(fd_set *readset)
129 {
130 	if (notify_pipe[0] != -1)
131 		FD_SET(notify_pipe[0], readset);
132 }
133 static void
134 notify_done(fd_set *readset)
135 {
136 	char c;
137 
138 	if (notify_pipe[0] != -1 && FD_ISSET(notify_pipe[0], readset))
139 		while (read(notify_pipe[0], &c, 1) != -1)
140 			debug2("notify_done: reading");
141 }
142 
143 /*ARGSUSED*/
144 static void
145 sigchld_handler(int sig)
146 {
147 	int save_errno = errno;
148 	child_terminated = 1;
149 	signal(SIGCHLD, sigchld_handler);
150 	notify_parent();
151 	errno = save_errno;
152 }
153 
154 /*ARGSUSED*/
155 static void
156 sigterm_handler(int sig)
157 {
158 	received_sigterm = sig;
159 }
160 
161 static void
162 client_alive_check(void)
163 {
164 	int channel_id;
165 
166 	/* timeout, check to see how many we have had */
167 	if (packet_inc_alive_timeouts() > options.client_alive_count_max) {
168 		logit("Timeout, client not responding.");
169 		cleanup_exit(255);
170 	}
171 
172 	/*
173 	 * send a bogus global/channel request with "wantreply",
174 	 * we should get back a failure
175 	 */
176 	if ((channel_id = channel_find_open()) == -1) {
177 		packet_start(SSH2_MSG_GLOBAL_REQUEST);
178 		packet_put_cstring("keepalive@openssh.com");
179 		packet_put_char(1);	/* boolean: want reply */
180 	} else {
181 		channel_request_start(channel_id, "keepalive@openssh.com", 1);
182 	}
183 	packet_send();
184 }
185 
186 /*
187  * Sleep in select() until we can do something.  This will initialize the
188  * select masks.  Upon return, the masks will indicate which descriptors
189  * have data or can accept data.  Optionally, a maximum time can be specified
190  * for the duration of the wait (0 = infinite).
191  */
192 static void
193 wait_until_can_do_something(int connection_in, int connection_out,
194     fd_set **readsetp, fd_set **writesetp, int *maxfdp,
195     u_int *nallocp, u_int64_t max_time_ms)
196 {
197 	struct timeval tv, *tvp;
198 	int ret;
199 	time_t minwait_secs = 0;
200 	int client_alive_scheduled = 0;
201 
202 	/* Allocate and update select() masks for channel descriptors. */
203 	channel_prepare_select(readsetp, writesetp, maxfdp, nallocp,
204 	    &minwait_secs, 0);
205 
206 	/* XXX need proper deadline system for rekey/client alive */
207 	if (minwait_secs != 0)
208 		max_time_ms = MINIMUM(max_time_ms, (u_int)minwait_secs * 1000);
209 
210 	/*
211 	 * if using client_alive, set the max timeout accordingly,
212 	 * and indicate that this particular timeout was for client
213 	 * alive by setting the client_alive_scheduled flag.
214 	 *
215 	 * this could be randomized somewhat to make traffic
216 	 * analysis more difficult, but we're not doing it yet.
217 	 */
218 	if (options.client_alive_interval) {
219 		uint64_t keepalive_ms =
220 		    (uint64_t)options.client_alive_interval * 1000;
221 
222 		client_alive_scheduled = 1;
223 		if (max_time_ms == 0 || max_time_ms > keepalive_ms)
224 			max_time_ms = keepalive_ms;
225 	}
226 
227 #if 0
228 	/* wrong: bad condition XXX */
229 	if (channel_not_very_much_buffered_data())
230 #endif
231 	FD_SET(connection_in, *readsetp);
232 	notify_prepare(*readsetp);
233 
234 	/*
235 	 * If we have buffered packet data going to the client, mark that
236 	 * descriptor.
237 	 */
238 	if (packet_have_data_to_write())
239 		FD_SET(connection_out, *writesetp);
240 
241 	/*
242 	 * If child has terminated and there is enough buffer space to read
243 	 * from it, then read as much as is available and exit.
244 	 */
245 	if (child_terminated && packet_not_very_much_data_to_write())
246 		if (max_time_ms == 0 || client_alive_scheduled)
247 			max_time_ms = 100;
248 
249 	if (max_time_ms == 0)
250 		tvp = NULL;
251 	else {
252 		tv.tv_sec = max_time_ms / 1000;
253 		tv.tv_usec = 1000 * (max_time_ms % 1000);
254 		tvp = &tv;
255 	}
256 
257 	/* Wait for something to happen, or the timeout to expire. */
258 	ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
259 
260 	if (ret == -1) {
261 		memset(*readsetp, 0, *nallocp);
262 		memset(*writesetp, 0, *nallocp);
263 		if (errno != EINTR)
264 			error("select: %.100s", strerror(errno));
265 	} else if (ret == 0 && client_alive_scheduled)
266 		client_alive_check();
267 
268 	notify_done(*readsetp);
269 }
270 
271 /*
272  * Processes input from the client and the program.  Input data is stored
273  * in buffers and processed later.
274  */
275 static int
276 process_input(fd_set *readset, int connection_in)
277 {
278 	struct ssh *ssh = active_state; /* XXX */
279 	int len;
280 	char buf[16384];
281 
282 	/* Read and buffer any input data from the client. */
283 	if (FD_ISSET(connection_in, readset)) {
284 		len = read(connection_in, buf, sizeof(buf));
285 		if (len == 0) {
286 			verbose("Connection closed by %.100s port %d",
287 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
288 			return -1;
289 		} else if (len < 0) {
290 			if (errno != EINTR && errno != EAGAIN) {
291 				verbose("Read error from remote host "
292 				    "%.100s port %d: %.100s",
293 				    ssh_remote_ipaddr(ssh),
294 				    ssh_remote_port(ssh), strerror(errno));
295 				cleanup_exit(255);
296 			}
297 		} else {
298 			/* Buffer any received data. */
299 			packet_process_incoming(buf, len);
300 		}
301 	}
302 	return 0;
303 }
304 
305 /*
306  * Sends data from internal buffers to client program stdin.
307  */
308 static void
309 process_output(fd_set *writeset, int connection_out)
310 {
311 	/* Send any buffered packet data to the client. */
312 	if (FD_ISSET(connection_out, writeset))
313 		packet_write_poll();
314 }
315 
316 static void
317 process_buffered_input_packets(void)
318 {
319 	dispatch_run(DISPATCH_NONBLOCK, NULL, active_state);
320 }
321 
322 static void
323 collect_children(void)
324 {
325 	pid_t pid;
326 	sigset_t oset, nset;
327 	int status;
328 
329 	/* block SIGCHLD while we check for dead children */
330 	sigemptyset(&nset);
331 	sigaddset(&nset, SIGCHLD);
332 	sigprocmask(SIG_BLOCK, &nset, &oset);
333 	if (child_terminated) {
334 		debug("Received SIGCHLD.");
335 		while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
336 		    (pid < 0 && errno == EINTR))
337 			if (pid > 0)
338 				session_close_by_pid(pid, status);
339 		child_terminated = 0;
340 	}
341 	sigprocmask(SIG_SETMASK, &oset, NULL);
342 }
343 
344 void
345 server_loop2(Authctxt *authctxt)
346 {
347 	fd_set *readset = NULL, *writeset = NULL;
348 	int max_fd;
349 	u_int nalloc = 0, connection_in, connection_out;
350 	u_int64_t rekey_timeout_ms = 0;
351 
352 	debug("Entering interactive session for SSH2.");
353 
354 	signal(SIGCHLD, sigchld_handler);
355 	child_terminated = 0;
356 	connection_in = packet_get_connection_in();
357 	connection_out = packet_get_connection_out();
358 
359 	if (!use_privsep) {
360 		signal(SIGTERM, sigterm_handler);
361 		signal(SIGINT, sigterm_handler);
362 		signal(SIGQUIT, sigterm_handler);
363 	}
364 
365 	notify_setup();
366 
367 	max_fd = MAXIMUM(connection_in, connection_out);
368 	max_fd = MAXIMUM(max_fd, notify_pipe[0]);
369 
370 	server_init_dispatch();
371 
372 	for (;;) {
373 		process_buffered_input_packets();
374 
375 		if (!ssh_packet_is_rekeying(active_state) &&
376 		    packet_not_very_much_data_to_write())
377 			channel_output_poll();
378 		if (options.rekey_interval > 0 &&
379 		    !ssh_packet_is_rekeying(active_state))
380 			rekey_timeout_ms = packet_get_rekey_timeout() * 1000;
381 		else
382 			rekey_timeout_ms = 0;
383 
384 		wait_until_can_do_something(connection_in, connection_out,
385 		    &readset, &writeset, &max_fd, &nalloc, rekey_timeout_ms);
386 
387 		if (received_sigterm) {
388 			logit("Exiting on signal %d", (int)received_sigterm);
389 			/* Clean up sessions, utmp, etc. */
390 			cleanup_exit(255);
391 		}
392 
393 		collect_children();
394 		if (!ssh_packet_is_rekeying(active_state))
395 			channel_after_select(readset, writeset);
396 		if (process_input(readset, connection_in) < 0)
397 			break;
398 		process_output(writeset, connection_out);
399 	}
400 	collect_children();
401 
402 	free(readset);
403 	free(writeset);
404 
405 	/* free all channels, no more reads and writes */
406 	channel_free_all();
407 
408 	/* free remaining sessions, e.g. remove wtmp entries */
409 	session_destroy_all(NULL);
410 }
411 
412 static int
413 server_input_keep_alive(int type, u_int32_t seq, void *ctxt)
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 	packet_set_alive_timeouts(0);
422 	return 0;
423 }
424 
425 static Channel *
426 server_request_direct_tcpip(void)
427 {
428 	Channel *c = NULL;
429 	char *target, *originator;
430 	u_short target_port, originator_port;
431 
432 	target = packet_get_string(NULL);
433 	target_port = packet_get_int();
434 	originator = packet_get_string(NULL);
435 	originator_port = packet_get_int();
436 	packet_check_eom();
437 
438 	debug("server_request_direct_tcpip: originator %s port %d, target %s "
439 	    "port %d", originator, originator_port, target, target_port);
440 
441 	/* XXX fine grained permissions */
442 	if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0 &&
443 	    !no_port_forwarding_flag) {
444 		c = channel_connect_to_port(target, target_port,
445 		    "direct-tcpip", "direct-tcpip");
446 	} else {
447 		logit("refused local port forward: "
448 		    "originator %s port %d, target %s port %d",
449 		    originator, originator_port, target, target_port);
450 	}
451 
452 	free(originator);
453 	free(target);
454 
455 	return c;
456 }
457 
458 static Channel *
459 server_request_direct_streamlocal(void)
460 {
461 	Channel *c = NULL;
462 	char *target, *originator;
463 	u_short originator_port;
464 
465 	target = packet_get_string(NULL);
466 	originator = packet_get_string(NULL);
467 	originator_port = packet_get_int();
468 	packet_check_eom();
469 
470 	debug("server_request_direct_streamlocal: originator %s port %d, target %s",
471 	    originator, originator_port, target);
472 
473 	/* XXX fine grained permissions */
474 	if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 &&
475 	    !no_port_forwarding_flag) {
476 		c = channel_connect_to_path(target,
477 		    "direct-streamlocal@openssh.com", "direct-streamlocal");
478 	} else {
479 		logit("refused streamlocal port forward: "
480 		    "originator %s port %d, target %s",
481 		    originator, originator_port, target);
482 	}
483 
484 	free(originator);
485 	free(target);
486 
487 	return c;
488 }
489 
490 static Channel *
491 server_request_tun(void)
492 {
493 	Channel *c = NULL;
494 	int mode, tun;
495 	int sock;
496 
497 	mode = packet_get_int();
498 	switch (mode) {
499 	case SSH_TUNMODE_POINTOPOINT:
500 	case SSH_TUNMODE_ETHERNET:
501 		break;
502 	default:
503 		packet_send_debug("Unsupported tunnel device mode.");
504 		return NULL;
505 	}
506 	if ((options.permit_tun & mode) == 0) {
507 		packet_send_debug("Server has rejected tunnel device "
508 		    "forwarding");
509 		return NULL;
510 	}
511 
512 	tun = packet_get_int();
513 	if (forced_tun_device != -1) {
514 		if (tun != SSH_TUNID_ANY && forced_tun_device != tun)
515 			goto done;
516 		tun = forced_tun_device;
517 	}
518 	sock = tun_open(tun, mode);
519 	if (sock < 0)
520 		goto done;
521 	c = channel_new("tun", SSH_CHANNEL_OPEN, sock, sock, -1,
522 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
523 	c->datagram = 1;
524 
525  done:
526 	if (c == NULL)
527 		packet_send_debug("Failed to open the tunnel device.");
528 	return c;
529 }
530 
531 static Channel *
532 server_request_session(void)
533 {
534 	Channel *c;
535 
536 	debug("input_session_request");
537 	packet_check_eom();
538 
539 	if (no_more_sessions) {
540 		packet_disconnect("Possible attack: attempt to open a session "
541 		    "after additional sessions disabled");
542 	}
543 
544 	/*
545 	 * A server session has no fd to read or write until a
546 	 * CHANNEL_REQUEST for a shell is made, so we set the type to
547 	 * SSH_CHANNEL_LARVAL.  Additionally, a callback for handling all
548 	 * CHANNEL_REQUEST messages is registered.
549 	 */
550 	c = channel_new("session", SSH_CHANNEL_LARVAL,
551 	    -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT,
552 	    0, "server-session", 1);
553 	if (session_open(the_authctxt, c->self) != 1) {
554 		debug("session open failed, free channel %d", c->self);
555 		channel_free(c);
556 		return NULL;
557 	}
558 	channel_register_cleanup(c->self, session_close_by_channel, 0);
559 	return c;
560 }
561 
562 static int
563 server_input_channel_open(int type, u_int32_t seq, void *ctxt)
564 {
565 	Channel *c = NULL;
566 	char *ctype;
567 	int rchan;
568 	u_int rmaxpack, rwindow, len;
569 
570 	ctype = packet_get_string(&len);
571 	rchan = packet_get_int();
572 	rwindow = packet_get_int();
573 	rmaxpack = packet_get_int();
574 
575 	debug("server_input_channel_open: ctype %s rchan %d win %d max %d",
576 	    ctype, rchan, rwindow, rmaxpack);
577 
578 	if (strcmp(ctype, "session") == 0) {
579 		c = server_request_session();
580 	} else if (strcmp(ctype, "direct-tcpip") == 0) {
581 		c = server_request_direct_tcpip();
582 	} else if (strcmp(ctype, "direct-streamlocal@openssh.com") == 0) {
583 		c = server_request_direct_streamlocal();
584 	} else if (strcmp(ctype, "tun@openssh.com") == 0) {
585 		c = server_request_tun();
586 	}
587 	if (c != NULL) {
588 		debug("server_input_channel_open: confirm %s", ctype);
589 		c->remote_id = rchan;
590 		c->remote_window = rwindow;
591 		c->remote_maxpacket = rmaxpack;
592 		if (c->type != SSH_CHANNEL_CONNECTING) {
593 			packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
594 			packet_put_int(c->remote_id);
595 			packet_put_int(c->self);
596 			packet_put_int(c->local_window);
597 			packet_put_int(c->local_maxpacket);
598 			packet_send();
599 		}
600 	} else {
601 		debug("server_input_channel_open: failure %s", ctype);
602 		packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
603 		packet_put_int(rchan);
604 		packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
605 		if (!(datafellows & SSH_BUG_OPENFAILURE)) {
606 			packet_put_cstring("open failed");
607 			packet_put_cstring("");
608 		}
609 		packet_send();
610 	}
611 	free(ctype);
612 	return 0;
613 }
614 
615 static int
616 server_input_hostkeys_prove(struct sshbuf **respp)
617 {
618 	struct ssh *ssh = active_state; /* XXX */
619 	struct sshbuf *resp = NULL;
620 	struct sshbuf *sigbuf = NULL;
621 	struct sshkey *key = NULL, *key_pub = NULL, *key_prv = NULL;
622 	int r, ndx, success = 0;
623 	const u_char *blob;
624 	u_char *sig = 0;
625 	size_t blen, slen;
626 
627 	if ((resp = sshbuf_new()) == NULL || (sigbuf = sshbuf_new()) == NULL)
628 		fatal("%s: sshbuf_new", __func__);
629 
630 	while (ssh_packet_remaining(ssh) > 0) {
631 		sshkey_free(key);
632 		key = NULL;
633 		if ((r = sshpkt_get_string_direct(ssh, &blob, &blen)) != 0 ||
634 		    (r = sshkey_from_blob(blob, blen, &key)) != 0) {
635 			error("%s: couldn't parse key: %s",
636 			    __func__, ssh_err(r));
637 			goto out;
638 		}
639 		/*
640 		 * Better check that this is actually one of our hostkeys
641 		 * before attempting to sign anything with it.
642 		 */
643 		if ((ndx = ssh->kex->host_key_index(key, 1, ssh)) == -1) {
644 			error("%s: unknown host %s key",
645 			    __func__, sshkey_type(key));
646 			goto out;
647 		}
648 		/*
649 		 * XXX refactor: make kex->sign just use an index rather
650 		 * than passing in public and private keys
651 		 */
652 		if ((key_prv = get_hostkey_by_index(ndx)) == NULL &&
653 		    (key_pub = get_hostkey_public_by_index(ndx, ssh)) == NULL) {
654 			error("%s: can't retrieve hostkey %d", __func__, ndx);
655 			goto out;
656 		}
657 		sshbuf_reset(sigbuf);
658 		free(sig);
659 		sig = NULL;
660 		if ((r = sshbuf_put_cstring(sigbuf,
661 		    "hostkeys-prove-00@openssh.com")) != 0 ||
662 		    (r = sshbuf_put_string(sigbuf,
663 		    ssh->kex->session_id, ssh->kex->session_id_len)) != 0 ||
664 		    (r = sshkey_puts(key, sigbuf)) != 0 ||
665 		    (r = ssh->kex->sign(key_prv, key_pub, &sig, &slen,
666 		    sshbuf_ptr(sigbuf), sshbuf_len(sigbuf), NULL, 0)) != 0 ||
667 		    (r = sshbuf_put_string(resp, sig, slen)) != 0) {
668 			error("%s: couldn't prepare signature: %s",
669 			    __func__, ssh_err(r));
670 			goto out;
671 		}
672 	}
673 	/* Success */
674 	*respp = resp;
675 	resp = NULL; /* don't free it */
676 	success = 1;
677  out:
678 	free(sig);
679 	sshbuf_free(resp);
680 	sshbuf_free(sigbuf);
681 	sshkey_free(key);
682 	return success;
683 }
684 
685 static int
686 server_input_global_request(int type, u_int32_t seq, void *ctxt)
687 {
688 	char *rtype;
689 	int want_reply;
690 	int r, success = 0, allocated_listen_port = 0;
691 	struct sshbuf *resp = NULL;
692 
693 	rtype = packet_get_string(NULL);
694 	want_reply = packet_get_char();
695 	debug("server_input_global_request: rtype %s want_reply %d", rtype, want_reply);
696 
697 	/* -R style forwarding */
698 	if (strcmp(rtype, "tcpip-forward") == 0) {
699 		struct passwd *pw;
700 		struct Forward fwd;
701 
702 		pw = the_authctxt->pw;
703 		if (pw == NULL || !the_authctxt->valid)
704 			fatal("server_input_global_request: no/invalid user");
705 		memset(&fwd, 0, sizeof(fwd));
706 		fwd.listen_host = packet_get_string(NULL);
707 		fwd.listen_port = (u_short)packet_get_int();
708 		debug("server_input_global_request: tcpip-forward listen %s port %d",
709 		    fwd.listen_host, fwd.listen_port);
710 
711 		/* check permissions */
712 		if ((options.allow_tcp_forwarding & FORWARD_REMOTE) == 0 ||
713 		    no_port_forwarding_flag ||
714 		    (!want_reply && fwd.listen_port == 0) ||
715 		    (fwd.listen_port != 0 && fwd.listen_port < IPPORT_RESERVED &&
716 		    pw->pw_uid != 0)) {
717 			success = 0;
718 			packet_send_debug("Server has disabled port forwarding.");
719 		} else {
720 			/* Start listening on the port */
721 			success = channel_setup_remote_fwd_listener(&fwd,
722 			    &allocated_listen_port, &options.fwd_opts);
723 		}
724 		free(fwd.listen_host);
725 		if ((resp = sshbuf_new()) == NULL)
726 			fatal("%s: sshbuf_new", __func__);
727 		if (allocated_listen_port != 0 &&
728 		    (r = sshbuf_put_u32(resp, allocated_listen_port)) != 0)
729 			fatal("%s: sshbuf_put_u32: %s", __func__, ssh_err(r));
730 	} else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
731 		struct Forward fwd;
732 
733 		memset(&fwd, 0, sizeof(fwd));
734 		fwd.listen_host = packet_get_string(NULL);
735 		fwd.listen_port = (u_short)packet_get_int();
736 		debug("%s: cancel-tcpip-forward addr %s port %d", __func__,
737 		    fwd.listen_host, fwd.listen_port);
738 
739 		success = channel_cancel_rport_listener(&fwd);
740 		free(fwd.listen_host);
741 	} else if (strcmp(rtype, "streamlocal-forward@openssh.com") == 0) {
742 		struct Forward fwd;
743 
744 		memset(&fwd, 0, sizeof(fwd));
745 		fwd.listen_path = packet_get_string(NULL);
746 		debug("server_input_global_request: streamlocal-forward listen path %s",
747 		    fwd.listen_path);
748 
749 		/* check permissions */
750 		if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0
751 		    || no_port_forwarding_flag) {
752 			success = 0;
753 			packet_send_debug("Server has disabled port forwarding.");
754 		} else {
755 			/* Start listening on the socket */
756 			success = channel_setup_remote_fwd_listener(
757 			    &fwd, NULL, &options.fwd_opts);
758 		}
759 		free(fwd.listen_path);
760 	} else if (strcmp(rtype, "cancel-streamlocal-forward@openssh.com") == 0) {
761 		struct Forward fwd;
762 
763 		memset(&fwd, 0, sizeof(fwd));
764 		fwd.listen_path = packet_get_string(NULL);
765 		debug("%s: cancel-streamlocal-forward path %s", __func__,
766 		    fwd.listen_path);
767 
768 		success = channel_cancel_rport_listener(&fwd);
769 		free(fwd.listen_path);
770 	} else if (strcmp(rtype, "no-more-sessions@openssh.com") == 0) {
771 		no_more_sessions = 1;
772 		success = 1;
773 	} else if (strcmp(rtype, "hostkeys-prove-00@openssh.com") == 0) {
774 		success = server_input_hostkeys_prove(&resp);
775 	}
776 	if (want_reply) {
777 		packet_start(success ?
778 		    SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
779 		if (success && resp != NULL)
780 			ssh_packet_put_raw(active_state, sshbuf_ptr(resp),
781 			    sshbuf_len(resp));
782 		packet_send();
783 		packet_write_wait();
784 	}
785 	free(rtype);
786 	sshbuf_free(resp);
787 	return 0;
788 }
789 
790 static int
791 server_input_channel_req(int type, u_int32_t seq, void *ctxt)
792 {
793 	Channel *c;
794 	int id, reply, success = 0;
795 	char *rtype;
796 
797 	id = packet_get_int();
798 	rtype = packet_get_string(NULL);
799 	reply = packet_get_char();
800 
801 	debug("server_input_channel_req: channel %d request %s reply %d",
802 	    id, rtype, reply);
803 
804 	if ((c = channel_lookup(id)) == NULL)
805 		packet_disconnect("server_input_channel_req: "
806 		    "unknown channel %d", id);
807 	if (!strcmp(rtype, "eow@openssh.com")) {
808 		packet_check_eom();
809 		chan_rcvd_eow(c);
810 	} else if ((c->type == SSH_CHANNEL_LARVAL ||
811 	    c->type == SSH_CHANNEL_OPEN) && strcmp(c->ctype, "session") == 0)
812 		success = session_input_channel_req(c, rtype);
813 	if (reply && !(c->flags & CHAN_CLOSE_SENT)) {
814 		packet_start(success ?
815 		    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
816 		packet_put_int(c->remote_id);
817 		packet_send();
818 	}
819 	free(rtype);
820 	return 0;
821 }
822 
823 static void
824 server_init_dispatch(void)
825 {
826 	debug("server_init_dispatch");
827 	dispatch_init(&dispatch_protocol_error);
828 	dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
829 	dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
830 	dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
831 	dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
832 	dispatch_set(SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
833 	dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
834 	dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
835 	dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
836 	dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
837 	dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
838 	/* client_alive */
839 	dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &server_input_keep_alive);
840 	dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
841 	dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
842 	dispatch_set(SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
843 	/* rekeying */
844 	dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
845 }
846