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