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