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