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