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