xref: /netbsd-src/crypto/external/bsd/openssh/dist/serverloop.c (revision 627f7eb200a4419d89b531d55fccd2ee3ffdcde0)
1 /*	$NetBSD: serverloop.c,v 1.29 2021/03/05 17:47:16 christos Exp $	*/
2 /* $OpenBSD: serverloop.c,v 1.225 2021/01/27 10:05:28 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.29 2021/03/05 17:47:16 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_f("reading");
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_fr(r, "compose");
223 	} else {
224 		channel_request_start(ssh, channel_id,
225 		    "keepalive@openssh.com", 1);
226 	}
227 	if ((r = sshpkt_send(ssh)) != 0)
228 		fatal_fr(r, "send");
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 				return 0;
355 			verbose("Read error from remote host %s port %d: %s",
356 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
357 			    strerror(errno));
358 			cleanup_exit(254);
359 		}
360 		/* Buffer any received data. */
361 		if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0)
362 			fatal_fr(r, "ssh_packet_process_incoming");
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 			sshpkt_fatal(ssh, r, "%s: ssh_packet_write_poll",
379 			    __func__);
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 == -1 && 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 	ssh_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 		ssh_signal(SIGTERM, sigterm_handler);
430 		ssh_signal(SIGINT, sigterm_handler);
431 		ssh_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_f("invalid target port");
517 		*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
518 		goto out;
519 	}
520 	if (originator_port > 0xFFFF) {
521 		error_f("invalid originator port");
522 		*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
523 		goto out;
524 	}
525 
526 	debug_f("originator %s port %u, target %s port %u",
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_f("no/invalid user");
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_f("invalid originator port");
568 		goto out;
569 	}
570 
571 	debug_f("originator %s port %d, target %s",
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_f("invalid tun");
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_f("ctype %s rchan %u win %u max %u",
710 	    ctype, rchan, rwindow, rmaxpack);
711 
712 	if (strcmp(ctype, "session") == 0) {
713 		c = server_request_session(ssh);
714 	} else if (strcmp(ctype, "direct-tcpip") == 0) {
715 		c = server_request_direct_tcpip(ssh, &reason, &errmsg);
716 	} else if (strcmp(ctype, "direct-streamlocal@openssh.com") == 0) {
717 		c = server_request_direct_streamlocal(ssh);
718 	} else if (strcmp(ctype, "tun@openssh.com") == 0) {
719 		c = server_request_tun(ssh);
720 	}
721 	if (c != NULL) {
722 		debug_f("confirm %s", ctype);
723 		c->remote_id = rchan;
724 		c->have_remote_id = 1;
725 		c->remote_window = rwindow;
726 		c->remote_maxpacket = rmaxpack;
727 		if (c->type != SSH_CHANNEL_CONNECTING) {
728 			if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
729 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
730 			    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
731 			    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
732 			    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
733 			    (r = sshpkt_send(ssh)) != 0) {
734 				sshpkt_fatal(ssh, r,
735 				    "%s: send open confirm", __func__);
736 			}
737 		}
738 	} else {
739 		debug_f("failure %s", ctype);
740 		if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
741 		    (r = sshpkt_put_u32(ssh, rchan)) != 0 ||
742 		    (r = sshpkt_put_u32(ssh, reason)) != 0 ||
743 		    (r = sshpkt_put_cstring(ssh, errmsg ? errmsg : "open failed")) != 0 ||
744 		    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
745 		    (r = sshpkt_send(ssh)) != 0) {
746 			sshpkt_fatal(ssh, r,
747 			    "%s: send open failure", __func__);
748 		}
749 	}
750 	free(ctype);
751 	return 0;
752 }
753 
754 static int
755 server_input_hostkeys_prove(struct ssh *ssh, struct sshbuf **respp)
756 {
757 	struct sshbuf *resp = NULL;
758 	struct sshbuf *sigbuf = NULL;
759 	struct sshkey *key = NULL, *key_pub = NULL, *key_prv = NULL;
760 	int r, ndx, kexsigtype, use_kexsigtype, success = 0;
761 	const u_char *blob;
762 	u_char *sig = 0;
763 	size_t blen, slen;
764 
765 	if ((resp = sshbuf_new()) == NULL || (sigbuf = sshbuf_new()) == NULL)
766 		fatal_f("sshbuf_new");
767 
768 	kexsigtype = sshkey_type_plain(
769 	    sshkey_type_from_name(ssh->kex->hostkey_alg));
770 	while (ssh_packet_remaining(ssh) > 0) {
771 		sshkey_free(key);
772 		key = NULL;
773 		if ((r = sshpkt_get_string_direct(ssh, &blob, &blen)) != 0 ||
774 		    (r = sshkey_from_blob(blob, blen, &key)) != 0) {
775 			error_fr(r, "parse key");
776 			goto out;
777 		}
778 		/*
779 		 * Better check that this is actually one of our hostkeys
780 		 * before attempting to sign anything with it.
781 		 */
782 		if ((ndx = ssh->kex->host_key_index(key, 1, ssh)) == -1) {
783 			error_f("unknown host %s key", sshkey_type(key));
784 			goto out;
785 		}
786 		/*
787 		 * XXX refactor: make kex->sign just use an index rather
788 		 * than passing in public and private keys
789 		 */
790 		if ((key_prv = get_hostkey_by_index(ndx)) == NULL &&
791 		    (key_pub = get_hostkey_public_by_index(ndx, ssh)) == NULL) {
792 			error_f("can't retrieve hostkey %d", ndx);
793 			goto out;
794 		}
795 		sshbuf_reset(sigbuf);
796 		free(sig);
797 		sig = NULL;
798 		/*
799 		 * For RSA keys, prefer to use the signature type negotiated
800 		 * during KEX to the default (SHA1).
801 		 */
802 		use_kexsigtype = kexsigtype == KEY_RSA &&
803 		    sshkey_type_plain(key->type) == KEY_RSA;
804 		if ((r = sshbuf_put_cstring(sigbuf,
805 		    "hostkeys-prove-00@openssh.com")) != 0 ||
806 		    (r = sshbuf_put_stringb(sigbuf,
807 		    ssh->kex->session_id)) != 0 ||
808 		    (r = sshkey_puts(key, sigbuf)) != 0 ||
809 		    (r = ssh->kex->sign(ssh, key_prv, key_pub, &sig, &slen,
810 		    sshbuf_ptr(sigbuf), sshbuf_len(sigbuf),
811 		    use_kexsigtype ? ssh->kex->hostkey_alg : NULL)) != 0 ||
812 		    (r = sshbuf_put_string(resp, sig, slen)) != 0) {
813 			error_fr(r, "assemble signature");
814 			goto out;
815 		}
816 	}
817 	/* Success */
818 	*respp = resp;
819 	resp = NULL; /* don't free it */
820 	success = 1;
821  out:
822 	free(sig);
823 	sshbuf_free(resp);
824 	sshbuf_free(sigbuf);
825 	sshkey_free(key);
826 	return success;
827 }
828 
829 static int
830 server_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
831 {
832 	char *rtype = NULL;
833 	u_char want_reply = 0;
834 	int r, success = 0, allocated_listen_port = 0;
835 	u_int port = 0;
836 	struct sshbuf *resp = NULL;
837 	struct passwd *pw = the_authctxt->pw;
838 	struct Forward fwd;
839 
840 	memset(&fwd, 0, sizeof(fwd));
841 	if (pw == NULL || !the_authctxt->valid)
842 		fatal_f("no/invalid user");
843 
844 	if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
845 	    (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
846 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
847 	debug_f("rtype %s want_reply %d", rtype, want_reply);
848 
849 	/* -R style forwarding */
850 	if (strcmp(rtype, "tcpip-forward") == 0) {
851 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 ||
852 		    (r = sshpkt_get_u32(ssh, &port)) != 0)
853 			sshpkt_fatal(ssh, r, "%s: parse tcpip-forward", __func__);
854 		debug_f("tcpip-forward listen %s port %u",
855 		    fwd.listen_host, port);
856 		if (port <= INT_MAX)
857 			fwd.listen_port = (int)port;
858 		/* check permissions */
859 		if (port > INT_MAX ||
860 		    (options.allow_tcp_forwarding & FORWARD_REMOTE) == 0 ||
861 		    !auth_opts->permit_port_forwarding_flag ||
862 		    options.disable_forwarding ||
863 		    (!want_reply && fwd.listen_port == 0) ||
864 		    (fwd.listen_port != 0 &&
865 		     !bind_permitted(fwd.listen_port, pw->pw_uid))) {
866 			success = 0;
867 			ssh_packet_send_debug(ssh, "Server has disabled port forwarding.");
868 		} else {
869 			/* Start listening on the port */
870 			success = channel_setup_remote_fwd_listener(ssh, &fwd,
871 			    &allocated_listen_port, &options.fwd_opts);
872 		}
873 		if ((resp = sshbuf_new()) == NULL)
874 			fatal_f("sshbuf_new");
875 		if (allocated_listen_port != 0 &&
876 		    (r = sshbuf_put_u32(resp, allocated_listen_port)) != 0)
877 			fatal_fr(r, "sshbuf_put_u32");
878 	} else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
879 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 ||
880 		    (r = sshpkt_get_u32(ssh, &port)) != 0)
881 			sshpkt_fatal(ssh, r, "%s: parse cancel-tcpip-forward", __func__);
882 
883 		debug_f("cancel-tcpip-forward addr %s port %d",
884 		    fwd.listen_host, port);
885 		if (port <= INT_MAX) {
886 			fwd.listen_port = (int)port;
887 			success = channel_cancel_rport_listener(ssh, &fwd);
888 		}
889 	} else if (strcmp(rtype, "streamlocal-forward@openssh.com") == 0) {
890 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0)
891 			sshpkt_fatal(ssh, r, "%s: parse streamlocal-forward@openssh.com", __func__);
892 		debug_f("streamlocal-forward listen path %s",
893 		    fwd.listen_path);
894 
895 		/* check permissions */
896 		if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0
897 		    || !auth_opts->permit_port_forwarding_flag ||
898 		    options.disable_forwarding ||
899 		    (pw->pw_uid != 0 && !use_privsep)) {
900 			success = 0;
901 			ssh_packet_send_debug(ssh, "Server has disabled "
902 			    "streamlocal forwarding.");
903 		} else {
904 			/* Start listening on the socket */
905 			success = channel_setup_remote_fwd_listener(ssh,
906 			    &fwd, NULL, &options.fwd_opts);
907 		}
908 	} else if (strcmp(rtype, "cancel-streamlocal-forward@openssh.com") == 0) {
909 		if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0)
910 			sshpkt_fatal(ssh, r, "%s: parse cancel-streamlocal-forward@openssh.com", __func__);
911 		debug_f("cancel-streamlocal-forward path %s",
912 		    fwd.listen_path);
913 
914 		success = channel_cancel_rport_listener(ssh, &fwd);
915 	} else if (strcmp(rtype, "no-more-sessions@openssh.com") == 0) {
916 		no_more_sessions = 1;
917 		success = 1;
918 	} else if (strcmp(rtype, "hostkeys-prove-00@openssh.com") == 0) {
919 		success = server_input_hostkeys_prove(ssh, &resp);
920 	}
921 	/* XXX sshpkt_get_end() */
922 	if (want_reply) {
923 		if ((r = sshpkt_start(ssh, success ?
924 		    SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE)) != 0 ||
925 		    (success && resp != NULL && (r = sshpkt_putb(ssh, resp)) != 0) ||
926 		    (r = sshpkt_send(ssh)) != 0 ||
927 		    (r = ssh_packet_write_wait(ssh)) < 0)
928 			sshpkt_fatal(ssh, r, "%s: send reply", __func__);
929 	}
930 	free(fwd.listen_host);
931 	free(fwd.listen_path);
932 	free(rtype);
933 	sshbuf_free(resp);
934 	return 0;
935 }
936 
937 static int
938 server_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
939 {
940 	Channel *c;
941 	int r, success = 0;
942 	char *rtype = NULL;
943 	u_char want_reply = 0;
944 	u_int id = 0;
945 
946 	if ((r = sshpkt_get_u32(ssh, &id)) != 0 ||
947 	    (r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
948 	    (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
949 		sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
950 
951 	debug("server_input_channel_req: channel %u request %s reply %d",
952 	    id, rtype, want_reply);
953 
954 	if (id >= INT_MAX || (c = channel_lookup(ssh, (int)id)) == NULL) {
955 		ssh_packet_disconnect(ssh, "%s: unknown channel %d",
956 		    __func__, id);
957 	}
958 	if (!strcmp(rtype, "eow@openssh.com")) {
959 		if ((r = sshpkt_get_end(ssh)) != 0)
960 			sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
961 		chan_rcvd_eow(ssh, c);
962 	} else if ((c->type == SSH_CHANNEL_LARVAL ||
963 	    c->type == SSH_CHANNEL_OPEN) && strcmp(c->ctype, "session") == 0)
964 		success = session_input_channel_req(ssh, c, rtype);
965 	if (want_reply && !(c->flags & CHAN_CLOSE_SENT)) {
966 		if (!c->have_remote_id)
967 			fatal_f("channel %d: no remote_id", c->self);
968 		if ((r = sshpkt_start(ssh, success ?
969 		    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 ||
970 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
971 		    (r = sshpkt_send(ssh)) != 0)
972 			sshpkt_fatal(ssh, r, "%s: send reply", __func__);
973 	}
974 	free(rtype);
975 	return 0;
976 }
977 
978 static void
979 server_init_dispatch(struct ssh *ssh)
980 {
981 	debug("server_init_dispatch");
982 	ssh_dispatch_init(ssh, &dispatch_protocol_error);
983 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
984 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data);
985 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
986 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
987 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
988 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
989 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
990 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
991 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
992 	ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
993 	/* client_alive */
994 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &server_input_keep_alive);
995 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
996 	ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
997 	ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
998 	/* rekeying */
999 	ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
1000 }
1001