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