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