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