xref: /openbsd/usr.bin/ssh/serverloop.c (revision 3cab2bb3)
1 /* $OpenBSD: serverloop.c,v 1.223 2020/07/03 06:29:57 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 		if (last_client_time == 0)
253 			last_client_time = monotime();
254 	}
255 
256 #if 0
257 	/* wrong: bad condition XXX */
258 	if (channel_not_very_much_buffered_data())
259 #endif
260 	FD_SET(connection_in, *readsetp);
261 	notify_prepare(*readsetp);
262 
263 	/*
264 	 * If we have buffered packet data going to the client, mark that
265 	 * descriptor.
266 	 */
267 	if (ssh_packet_have_data_to_write(ssh))
268 		FD_SET(connection_out, *writesetp);
269 
270 	/*
271 	 * If child has terminated and there is enough buffer space to read
272 	 * from it, then read as much as is available and exit.
273 	 */
274 	if (child_terminated && ssh_packet_not_very_much_data_to_write(ssh))
275 		if (max_time_ms == 0 || client_alive_scheduled)
276 			max_time_ms = 100;
277 
278 	if (max_time_ms == 0)
279 		tvp = NULL;
280 	else {
281 		tv.tv_sec = max_time_ms / 1000;
282 		tv.tv_usec = 1000 * (max_time_ms % 1000);
283 		tvp = &tv;
284 	}
285 
286 	/* Wait for something to happen, or the timeout to expire. */
287 	ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
288 
289 	if (ret == -1) {
290 		memset(*readsetp, 0, *nallocp);
291 		memset(*writesetp, 0, *nallocp);
292 		if (errno != EINTR)
293 			error("select: %.100s", strerror(errno));
294 	} else if (client_alive_scheduled) {
295 		time_t now = monotime();
296 
297 		/*
298 		 * If the select timed out, or returned for some other reason
299 		 * but we haven't heard from the client in time, send keepalive.
300 		 */
301 		if (ret == 0 || (last_client_time != 0 && last_client_time +
302 		    options.client_alive_interval <= now)) {
303 			client_alive_check(ssh);
304 			last_client_time = now;
305 		} else if (FD_ISSET(connection_in, *readsetp)) {
306 			last_client_time = now;
307 		}
308 	}
309 
310 	notify_done(*readsetp);
311 }
312 
313 /*
314  * Processes input from the client and the program.  Input data is stored
315  * in buffers and processed later.
316  */
317 static int
318 process_input(struct ssh *ssh, fd_set *readset, int connection_in)
319 {
320 	int r, len;
321 	char buf[16384];
322 
323 	/* Read and buffer any input data from the client. */
324 	if (FD_ISSET(connection_in, readset)) {
325 		len = read(connection_in, buf, sizeof(buf));
326 		if (len == 0) {
327 			verbose("Connection closed by %.100s port %d",
328 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
329 			return -1;
330 		} else if (len == -1) {
331 			if (errno != EINTR && errno != EAGAIN) {
332 				verbose("Read error from remote host "
333 				    "%.100s port %d: %.100s",
334 				    ssh_remote_ipaddr(ssh),
335 				    ssh_remote_port(ssh), strerror(errno));
336 				cleanup_exit(255);
337 			}
338 		} else {
339 			/* Buffer any received data. */
340 			if ((r = ssh_packet_process_incoming(ssh, buf, len))
341 			    != 0)
342 				fatal("%s: ssh_packet_process_incoming: %s",
343 				    __func__, ssh_err(r));
344 		}
345 	}
346 	return 0;
347 }
348 
349 /*
350  * Sends data from internal buffers to client program stdin.
351  */
352 static void
353 process_output(struct ssh *ssh, fd_set *writeset, int connection_out)
354 {
355 	int r;
356 
357 	/* Send any buffered packet data to the client. */
358 	if (FD_ISSET(connection_out, writeset)) {
359 		if ((r = ssh_packet_write_poll(ssh)) != 0) {
360 			sshpkt_fatal(ssh, r, "%s: ssh_packet_write_poll",
361 			    __func__);
362 		}
363 	}
364 }
365 
366 static void
367 process_buffered_input_packets(struct ssh *ssh)
368 {
369 	ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, NULL);
370 }
371 
372 static void
373 collect_children(struct ssh *ssh)
374 {
375 	pid_t pid;
376 	sigset_t oset, nset;
377 	int status;
378 
379 	/* block SIGCHLD while we check for dead children */
380 	sigemptyset(&nset);
381 	sigaddset(&nset, SIGCHLD);
382 	sigprocmask(SIG_BLOCK, &nset, &oset);
383 	if (child_terminated) {
384 		debug("Received SIGCHLD.");
385 		while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
386 		    (pid == -1 && errno == EINTR))
387 			if (pid > 0)
388 				session_close_by_pid(ssh, pid, status);
389 		child_terminated = 0;
390 	}
391 	sigprocmask(SIG_SETMASK, &oset, NULL);
392 }
393 
394 void
395 server_loop2(struct ssh *ssh, Authctxt *authctxt)
396 {
397 	fd_set *readset = NULL, *writeset = NULL;
398 	int max_fd;
399 	u_int nalloc = 0, connection_in, connection_out;
400 	u_int64_t rekey_timeout_ms = 0;
401 
402 	debug("Entering interactive session for SSH2.");
403 
404 	ssh_signal(SIGCHLD, sigchld_handler);
405 	child_terminated = 0;
406 	connection_in = ssh_packet_get_connection_in(ssh);
407 	connection_out = ssh_packet_get_connection_out(ssh);
408 
409 	if (!use_privsep) {
410 		ssh_signal(SIGTERM, sigterm_handler);
411 		ssh_signal(SIGINT, sigterm_handler);
412 		ssh_signal(SIGQUIT, sigterm_handler);
413 	}
414 
415 	notify_setup();
416 
417 	max_fd = MAXIMUM(connection_in, connection_out);
418 	max_fd = MAXIMUM(max_fd, notify_pipe[0]);
419 
420 	server_init_dispatch(ssh);
421 
422 	for (;;) {
423 		process_buffered_input_packets(ssh);
424 
425 		if (!ssh_packet_is_rekeying(ssh) &&
426 		    ssh_packet_not_very_much_data_to_write(ssh))
427 			channel_output_poll(ssh);
428 		if (options.rekey_interval > 0 &&
429 		    !ssh_packet_is_rekeying(ssh)) {
430 			rekey_timeout_ms = ssh_packet_get_rekey_timeout(ssh) *
431 			    1000;
432 		} else {
433 			rekey_timeout_ms = 0;
434 		}
435 
436 		wait_until_can_do_something(ssh, connection_in, connection_out,
437 		    &readset, &writeset, &max_fd, &nalloc, rekey_timeout_ms);
438 
439 		if (received_sigterm) {
440 			logit("Exiting on signal %d", (int)received_sigterm);
441 			/* Clean up sessions, utmp, etc. */
442 			cleanup_exit(255);
443 		}
444 
445 		collect_children(ssh);
446 		if (!ssh_packet_is_rekeying(ssh))
447 			channel_after_select(ssh, readset, writeset);
448 		if (process_input(ssh, readset, connection_in) < 0)
449 			break;
450 		process_output(ssh, writeset, connection_out);
451 	}
452 	collect_children(ssh);
453 
454 	free(readset);
455 	free(writeset);
456 
457 	/* free all channels, no more reads and writes */
458 	channel_free_all(ssh);
459 
460 	/* free remaining sessions, e.g. remove wtmp entries */
461 	session_destroy_all(ssh, NULL);
462 }
463 
464 static int
465 server_input_keep_alive(int type, u_int32_t seq, struct ssh *ssh)
466 {
467 	debug("Got %d/%u for keepalive", type, seq);
468 	/*
469 	 * reset timeout, since we got a sane answer from the client.
470 	 * even if this was generated by something other than
471 	 * the bogus CHANNEL_REQUEST we send for keepalives.
472 	 */
473 	ssh_packet_set_alive_timeouts(ssh, 0);
474 	return 0;
475 }
476 
477 static Channel *
478 server_request_direct_tcpip(struct ssh *ssh, int *reason, const char **errmsg)
479 {
480 	Channel *c = NULL;
481 	char *target = NULL, *originator = NULL;
482 	u_int target_port = 0, originator_port = 0;
483 	int r;
484 
485 	if ((r = sshpkt_get_cstring(ssh, &target, NULL)) != 0 ||
486 	    (r = sshpkt_get_u32(ssh, &target_port)) != 0 ||
487 	    (r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
488 	    (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
489 	    (r = sshpkt_get_end(ssh)) != 0)
490 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
491 	if (target_port > 0xFFFF) {
492 		error("%s: invalid target port", __func__);
493 		*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
494 		goto out;
495 	}
496 	if (originator_port > 0xFFFF) {
497 		error("%s: invalid originator port", __func__);
498 		*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
499 		goto out;
500 	}
501 
502 	debug("%s: originator %s port %u, target %s port %u", __func__,
503 	    originator, originator_port, target, target_port);
504 
505 	/* XXX fine grained permissions */
506 	if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0 &&
507 	    auth_opts->permit_port_forwarding_flag &&
508 	    !options.disable_forwarding) {
509 		c = channel_connect_to_port(ssh, target, target_port,
510 		    "direct-tcpip", "direct-tcpip", reason, errmsg);
511 	} else {
512 		logit("refused local port forward: "
513 		    "originator %s port %d, target %s port %d",
514 		    originator, originator_port, target, target_port);
515 		if (reason != NULL)
516 			*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
517 	}
518 
519  out:
520 	free(originator);
521 	free(target);
522 	return c;
523 }
524 
525 static Channel *
526 server_request_direct_streamlocal(struct ssh *ssh)
527 {
528 	Channel *c = NULL;
529 	char *target = NULL, *originator = NULL;
530 	u_int originator_port = 0;
531 	struct passwd *pw = the_authctxt->pw;
532 	int r;
533 
534 	if (pw == NULL || !the_authctxt->valid)
535 		fatal("%s: no/invalid user", __func__);
536 
537 	if ((r = sshpkt_get_cstring(ssh, &target, NULL)) != 0 ||
538 	    (r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
539 	    (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
540 	    (r = sshpkt_get_end(ssh)) != 0)
541 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
542 	if (originator_port > 0xFFFF) {
543 		error("%s: invalid originator port", __func__);
544 		goto out;
545 	}
546 
547 	debug("%s: originator %s port %d, target %s", __func__,
548 	    originator, originator_port, target);
549 
550 	/* XXX fine grained permissions */
551 	if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 &&
552 	    auth_opts->permit_port_forwarding_flag &&
553 	    !options.disable_forwarding && (pw->pw_uid == 0 || use_privsep)) {
554 		c = channel_connect_to_path(ssh, target,
555 		    "direct-streamlocal@openssh.com", "direct-streamlocal");
556 	} else {
557 		logit("refused streamlocal port forward: "
558 		    "originator %s port %d, target %s",
559 		    originator, originator_port, target);
560 	}
561 
562 out:
563 	free(originator);
564 	free(target);
565 	return c;
566 }
567 
568 static Channel *
569 server_request_tun(struct ssh *ssh)
570 {
571 	Channel *c = NULL;
572 	u_int mode, tun;
573 	int r, sock;
574 	char *tmp, *ifname = NULL;
575 
576 	if ((r = sshpkt_get_u32(ssh, &mode)) != 0)
577 		sshpkt_fatal(ssh, r, "%s: parse mode", __func__);
578 	switch (mode) {
579 	case SSH_TUNMODE_POINTOPOINT:
580 	case SSH_TUNMODE_ETHERNET:
581 		break;
582 	default:
583 		ssh_packet_send_debug(ssh, "Unsupported tunnel device mode.");
584 		return NULL;
585 	}
586 	if ((options.permit_tun & mode) == 0) {
587 		ssh_packet_send_debug(ssh, "Server has rejected tunnel device "
588 		    "forwarding");
589 		return NULL;
590 	}
591 
592 	if ((r = sshpkt_get_u32(ssh, &tun)) != 0)
593 		sshpkt_fatal(ssh, r, "%s: parse device", __func__);
594 	if (tun > INT_MAX) {
595 		debug("%s: invalid tun", __func__);
596 		goto done;
597 	}
598 	if (auth_opts->force_tun_device != -1) {
599 		if (tun != SSH_TUNID_ANY &&
600 		    auth_opts->force_tun_device != (int)tun)
601 			goto done;
602 		tun = auth_opts->force_tun_device;
603 	}
604 	sock = tun_open(tun, mode, &ifname);
605 	if (sock < 0)
606 		goto done;
607 	debug("Tunnel forwarding using interface %s", ifname);
608 
609 	c = channel_new(ssh, "tun", SSH_CHANNEL_OPEN, sock, sock, -1,
610 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
611 	c->datagram = 1;
612 
613 	/*
614 	 * Update the list of names exposed to the session
615 	 * XXX remove these if the tunnels are closed (won't matter
616 	 * much if they are already in the environment though)
617 	 */
618 	tmp = tun_fwd_ifnames;
619 	xasprintf(&tun_fwd_ifnames, "%s%s%s",
620 	    tun_fwd_ifnames == NULL ? "" : tun_fwd_ifnames,
621 	    tun_fwd_ifnames == NULL ? "" : ",",
622 	    ifname);
623 	free(tmp);
624 	free(ifname);
625 
626  done:
627 	if (c == NULL)
628 		ssh_packet_send_debug(ssh, "Failed to open the tunnel device.");
629 	return c;
630 }
631 
632 static Channel *
633 server_request_session(struct ssh *ssh)
634 {
635 	Channel *c;
636 	int r;
637 
638 	debug("input_session_request");
639 	if ((r = sshpkt_get_end(ssh)) != 0)
640 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
641 
642 	if (no_more_sessions) {
643 		ssh_packet_disconnect(ssh, "Possible attack: attempt to open a "
644 		    "session after additional sessions disabled");
645 	}
646 
647 	/*
648 	 * A server session has no fd to read or write until a
649 	 * CHANNEL_REQUEST for a shell is made, so we set the type to
650 	 * SSH_CHANNEL_LARVAL.  Additionally, a callback for handling all
651 	 * CHANNEL_REQUEST messages is registered.
652 	 */
653 	c = channel_new(ssh, "session", SSH_CHANNEL_LARVAL,
654 	    -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT,
655 	    0, "server-session", 1);
656 	if (session_open(the_authctxt, c->self) != 1) {
657 		debug("session open failed, free channel %d", c->self);
658 		channel_free(ssh, c);
659 		return NULL;
660 	}
661 	channel_register_cleanup(ssh, c->self, session_close_by_channel, 0);
662 	return c;
663 }
664 
665 static int
666 server_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
667 {
668 	Channel *c = NULL;
669 	char *ctype = NULL;
670 	const char *errmsg = NULL;
671 	int r, reason = SSH2_OPEN_CONNECT_FAILED;
672 	u_int rchan = 0, rmaxpack = 0, rwindow = 0;
673 
674 	if ((r = sshpkt_get_cstring(ssh, &ctype, NULL)) != 0 ||
675 	    (r = sshpkt_get_u32(ssh, &rchan)) != 0 ||
676 	    (r = sshpkt_get_u32(ssh, &rwindow)) != 0 ||
677 	    (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0)
678 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
679 	debug("%s: ctype %s rchan %u win %u max %u", __func__,
680 	    ctype, rchan, rwindow, rmaxpack);
681 
682 	if (strcmp(ctype, "session") == 0) {
683 		c = server_request_session(ssh);
684 	} else if (strcmp(ctype, "direct-tcpip") == 0) {
685 		c = server_request_direct_tcpip(ssh, &reason, &errmsg);
686 	} else if (strcmp(ctype, "direct-streamlocal@openssh.com") == 0) {
687 		c = server_request_direct_streamlocal(ssh);
688 	} else if (strcmp(ctype, "tun@openssh.com") == 0) {
689 		c = server_request_tun(ssh);
690 	}
691 	if (c != NULL) {
692 		debug("%s: confirm %s", __func__, ctype);
693 		c->remote_id = rchan;
694 		c->have_remote_id = 1;
695 		c->remote_window = rwindow;
696 		c->remote_maxpacket = rmaxpack;
697 		if (c->type != SSH_CHANNEL_CONNECTING) {
698 			if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
699 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
700 			    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
701 			    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
702 			    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
703 			    (r = sshpkt_send(ssh)) != 0) {
704 				sshpkt_fatal(ssh, r,
705 				    "%s: send open confirm", __func__);
706 			}
707 		}
708 	} else {
709 		debug("%s: failure %s", __func__, ctype);
710 		if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
711 		    (r = sshpkt_put_u32(ssh, rchan)) != 0 ||
712 		    (r = sshpkt_put_u32(ssh, reason)) != 0 ||
713 		    (r = sshpkt_put_cstring(ssh, errmsg ? errmsg : "open failed")) != 0 ||
714 		    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
715 		    (r = sshpkt_send(ssh)) != 0) {
716 			sshpkt_fatal(ssh, r,
717 			    "%s: send open failure", __func__);
718 		}
719 	}
720 	free(ctype);
721 	return 0;
722 }
723 
724 static int
725 server_input_hostkeys_prove(struct ssh *ssh, struct sshbuf **respp)
726 {
727 	struct sshbuf *resp = NULL;
728 	struct sshbuf *sigbuf = NULL;
729 	struct sshkey *key = NULL, *key_pub = NULL, *key_prv = NULL;
730 	int r, ndx, kexsigtype, use_kexsigtype, success = 0;
731 	const u_char *blob;
732 	u_char *sig = 0;
733 	size_t blen, slen;
734 
735 	if ((resp = sshbuf_new()) == NULL || (sigbuf = sshbuf_new()) == NULL)
736 		fatal("%s: sshbuf_new", __func__);
737 
738 	kexsigtype = sshkey_type_plain(
739 	    sshkey_type_from_name(ssh->kex->hostkey_alg));
740 	while (ssh_packet_remaining(ssh) > 0) {
741 		sshkey_free(key);
742 		key = NULL;
743 		if ((r = sshpkt_get_string_direct(ssh, &blob, &blen)) != 0 ||
744 		    (r = sshkey_from_blob(blob, blen, &key)) != 0) {
745 			error("%s: couldn't parse key: %s",
746 			    __func__, ssh_err(r));
747 			goto out;
748 		}
749 		/*
750 		 * Better check that this is actually one of our hostkeys
751 		 * before attempting to sign anything with it.
752 		 */
753 		if ((ndx = ssh->kex->host_key_index(key, 1, ssh)) == -1) {
754 			error("%s: unknown host %s key",
755 			    __func__, sshkey_type(key));
756 			goto out;
757 		}
758 		/*
759 		 * XXX refactor: make kex->sign just use an index rather
760 		 * than passing in public and private keys
761 		 */
762 		if ((key_prv = get_hostkey_by_index(ndx)) == NULL &&
763 		    (key_pub = get_hostkey_public_by_index(ndx, ssh)) == NULL) {
764 			error("%s: can't retrieve hostkey %d", __func__, ndx);
765 			goto out;
766 		}
767 		sshbuf_reset(sigbuf);
768 		free(sig);
769 		sig = NULL;
770 		/*
771 		 * For RSA keys, prefer to use the signature type negotiated
772 		 * during KEX to the default (SHA1).
773 		 */
774 		use_kexsigtype = kexsigtype == KEY_RSA &&
775 		    sshkey_type_plain(key->type) == KEY_RSA;
776 		if ((r = sshbuf_put_cstring(sigbuf,
777 		    "hostkeys-prove-00@openssh.com")) != 0 ||
778 		    (r = sshbuf_put_string(sigbuf,
779 		    ssh->kex->session_id, ssh->kex->session_id_len)) != 0 ||
780 		    (r = sshkey_puts(key, sigbuf)) != 0 ||
781 		    (r = ssh->kex->sign(ssh, key_prv, key_pub, &sig, &slen,
782 		    sshbuf_ptr(sigbuf), sshbuf_len(sigbuf),
783 		    use_kexsigtype ? ssh->kex->hostkey_alg : NULL)) != 0 ||
784 		    (r = sshbuf_put_string(resp, sig, slen)) != 0) {
785 			error("%s: couldn't prepare signature: %s",
786 			    __func__, ssh_err(r));
787 			goto out;
788 		}
789 	}
790 	/* Success */
791 	*respp = resp;
792 	resp = NULL; /* don't free it */
793 	success = 1;
794  out:
795 	free(sig);
796 	sshbuf_free(resp);
797 	sshbuf_free(sigbuf);
798 	sshkey_free(key);
799 	return success;
800 }
801 
802 static int
803 server_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
804 {
805 	char *rtype = NULL;
806 	u_char want_reply = 0;
807 	int r, success = 0, allocated_listen_port = 0;
808 	u_int port = 0;
809 	struct sshbuf *resp = NULL;
810 	struct passwd *pw = the_authctxt->pw;
811 	struct Forward fwd;
812 
813 	memset(&fwd, 0, sizeof(fwd));
814 	if (pw == NULL || !the_authctxt->valid)
815 		fatal("%s: no/invalid user", __func__);
816 
817 	if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
818 	    (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
819 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
820 	debug("%s: rtype %s want_reply %d", __func__, rtype, want_reply);
821 
822 	/* -R style forwarding */
823 	if (strcmp(rtype, "tcpip-forward") == 0) {
824 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 ||
825 		    (r = sshpkt_get_u32(ssh, &port)) != 0)
826 			sshpkt_fatal(ssh, r, "%s: parse tcpip-forward", __func__);
827 		debug("%s: tcpip-forward listen %s port %u", __func__,
828 		    fwd.listen_host, port);
829 		if (port <= INT_MAX)
830 			fwd.listen_port = (int)port;
831 		/* check permissions */
832 		if (port > INT_MAX ||
833 		    (options.allow_tcp_forwarding & FORWARD_REMOTE) == 0 ||
834 		    !auth_opts->permit_port_forwarding_flag ||
835 		    options.disable_forwarding ||
836 		    (!want_reply && fwd.listen_port == 0) ||
837 		    (fwd.listen_port != 0 &&
838 		     !bind_permitted(fwd.listen_port, pw->pw_uid))) {
839 			success = 0;
840 			ssh_packet_send_debug(ssh, "Server has disabled port forwarding.");
841 		} else {
842 			/* Start listening on the port */
843 			success = channel_setup_remote_fwd_listener(ssh, &fwd,
844 			    &allocated_listen_port, &options.fwd_opts);
845 		}
846 		if ((resp = sshbuf_new()) == NULL)
847 			fatal("%s: sshbuf_new", __func__);
848 		if (allocated_listen_port != 0 &&
849 		    (r = sshbuf_put_u32(resp, allocated_listen_port)) != 0)
850 			fatal("%s: sshbuf_put_u32: %s", __func__, ssh_err(r));
851 	} else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
852 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 ||
853 		    (r = sshpkt_get_u32(ssh, &port)) != 0)
854 			sshpkt_fatal(ssh, r, "%s: parse cancel-tcpip-forward", __func__);
855 
856 		debug("%s: cancel-tcpip-forward addr %s port %d", __func__,
857 		    fwd.listen_host, port);
858 		if (port <= INT_MAX) {
859 			fwd.listen_port = (int)port;
860 			success = channel_cancel_rport_listener(ssh, &fwd);
861 		}
862 	} else if (strcmp(rtype, "streamlocal-forward@openssh.com") == 0) {
863 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0)
864 			sshpkt_fatal(ssh, r, "%s: parse streamlocal-forward@openssh.com", __func__);
865 		debug("%s: streamlocal-forward listen path %s", __func__,
866 		    fwd.listen_path);
867 
868 		/* check permissions */
869 		if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0
870 		    || !auth_opts->permit_port_forwarding_flag ||
871 		    options.disable_forwarding ||
872 		    (pw->pw_uid != 0 && !use_privsep)) {
873 			success = 0;
874 			ssh_packet_send_debug(ssh, "Server has disabled "
875 			    "streamlocal forwarding.");
876 		} else {
877 			/* Start listening on the socket */
878 			success = channel_setup_remote_fwd_listener(ssh,
879 			    &fwd, NULL, &options.fwd_opts);
880 		}
881 	} else if (strcmp(rtype, "cancel-streamlocal-forward@openssh.com") == 0) {
882 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0)
883 			sshpkt_fatal(ssh, r, "%s: parse cancel-streamlocal-forward@openssh.com", __func__);
884 		debug("%s: cancel-streamlocal-forward path %s", __func__,
885 		    fwd.listen_path);
886 
887 		success = channel_cancel_rport_listener(ssh, &fwd);
888 	} else if (strcmp(rtype, "no-more-sessions@openssh.com") == 0) {
889 		no_more_sessions = 1;
890 		success = 1;
891 	} else if (strcmp(rtype, "hostkeys-prove-00@openssh.com") == 0) {
892 		success = server_input_hostkeys_prove(ssh, &resp);
893 	}
894 	/* XXX sshpkt_get_end() */
895 	if (want_reply) {
896 		if ((r = sshpkt_start(ssh, success ?
897 		    SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE)) != 0 ||
898 		    (success && resp != NULL && (r = sshpkt_putb(ssh, resp)) != 0) ||
899 		    (r = sshpkt_send(ssh)) != 0 ||
900 		    (r = ssh_packet_write_wait(ssh)) != 0)
901 			sshpkt_fatal(ssh, r, "%s: send reply", __func__);
902 	}
903 	free(fwd.listen_host);
904 	free(fwd.listen_path);
905 	free(rtype);
906 	sshbuf_free(resp);
907 	return 0;
908 }
909 
910 static int
911 server_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
912 {
913 	Channel *c;
914 	int r, success = 0;
915 	char *rtype = NULL;
916 	u_char want_reply = 0;
917 	u_int id = 0;
918 
919 	if ((r = sshpkt_get_u32(ssh, &id)) != 0 ||
920 	    (r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
921 	    (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
922 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
923 
924 	debug("server_input_channel_req: channel %u request %s reply %d",
925 	    id, rtype, want_reply);
926 
927 	if (id >= INT_MAX || (c = channel_lookup(ssh, (int)id)) == NULL) {
928 		ssh_packet_disconnect(ssh, "%s: unknown channel %d",
929 		    __func__, id);
930 	}
931 	if (!strcmp(rtype, "eow@openssh.com")) {
932 		if ((r = sshpkt_get_end(ssh)) != 0)
933 			sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
934 		chan_rcvd_eow(ssh, c);
935 	} else if ((c->type == SSH_CHANNEL_LARVAL ||
936 	    c->type == SSH_CHANNEL_OPEN) && strcmp(c->ctype, "session") == 0)
937 		success = session_input_channel_req(ssh, c, rtype);
938 	if (want_reply && !(c->flags & CHAN_CLOSE_SENT)) {
939 		if (!c->have_remote_id)
940 			fatal("%s: channel %d: no remote_id",
941 			    __func__, c->self);
942 		if ((r = sshpkt_start(ssh, success ?
943 		    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 ||
944 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
945 		    (r = sshpkt_send(ssh)) != 0)
946 			sshpkt_fatal(ssh, r, "%s: send reply", __func__);
947 	}
948 	free(rtype);
949 	return 0;
950 }
951 
952 static void
953 server_init_dispatch(struct ssh *ssh)
954 {
955 	debug("server_init_dispatch");
956 	ssh_dispatch_init(ssh, &dispatch_protocol_error);
957 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
958 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data);
959 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
960 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
961 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
962 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
963 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
964 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
965 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
966 	ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
967 	/* client_alive */
968 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &server_input_keep_alive);
969 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
970 	ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
971 	ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
972 	/* rekeying */
973 	ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
974 }
975