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