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