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