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