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