1 /* $OpenBSD: channels.c,v 1.351 2016/07/19 11:38:53 dtucker Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This file contains functions for generic socket connection forwarding.
7 * There is also code for initiating connection forwarding for X11 connections,
8 * arbitrary tcp/ip connections, and the authentication agent connection.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * SSH2 support added by Markus Friedl.
17 * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl. All rights reserved.
18 * Copyright (c) 1999 Dug Song. All rights reserved.
19 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44 #include <sys/types.h>
45 #include <sys/param.h> /* MIN MAX */
47 #include <sys/ioctl.h>
49 #include <sys/socket.h>
50 #ifdef HAVE_SYS_TIME_H
51 # include <sys/time.h>
54 #include <netinet/in.h>
55 #include <arpa/inet.h>
70 #include "openbsd-compat/sys-queue.h"
84 #include "pathnames.h"
89 * Pointer to an array containing all allocated channels. The array is
90 * dynamically extended as needed.
92 static Channel **channels = NULL;
95 * Size of the channel array. All slots of the array must always be
96 * initialized (at least the type field); unused slots set to NULL
98 static u_int channels_alloc = 0;
101 * Maximum file descriptor value used in any of the channels. This is
102 * updated in channel_new.
104 static int channel_max_fd = 0;
107 /* -- tcp forwarding */
110 * Data structure for storing which hosts are permitted for forward requests.
111 * The local sides of any remote forwards are stored in this array to prevent
112 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
113 * network (which might be behind a firewall).
115 /* XXX: streamlocal wants a path instead of host:port */
116 /* Overload host_to_connect; we could just make this match Forward */
117 /* XXX - can we use listen_host instead of listen_path? */
119 char *host_to_connect; /* Connect to 'host'. */
120 int port_to_connect; /* Connect to 'port'. */
121 char *listen_host; /* Remote side should listen address. */
122 char *listen_path; /* Remote side should listen path. */
123 int listen_port; /* Remote side should listen port. */
126 /* List of all permitted host/port pairs to connect by the user. */
127 static ForwardPermission *permitted_opens = NULL;
129 /* List of all permitted host/port pairs to connect by the admin. */
130 static ForwardPermission *permitted_adm_opens = NULL;
132 /* Number of permitted host/port pairs in the array permitted by the user. */
133 static int num_permitted_opens = 0;
135 /* Number of permitted host/port pair in the array permitted by the admin. */
136 static int num_adm_permitted_opens = 0;
138 /* special-case port number meaning allow any port */
139 #define FWD_PERMIT_ANY_PORT 0
141 /* special-case wildcard meaning allow any host */
142 #define FWD_PERMIT_ANY_HOST "*"
145 * If this is true, all opens are permitted. This is the case on the server
146 * on which we have to trust the client anyway, and the user could do
147 * anything after logging in anyway.
149 static int all_opens_permitted = 0;
152 /* -- X11 forwarding */
154 /* Maximum number of fake X11 displays to try. */
155 #define MAX_DISPLAYS 1000
157 /* Saved X11 local (client) display. */
158 static char *x11_saved_display = NULL;
160 /* Saved X11 authentication protocol name. */
161 static char *x11_saved_proto = NULL;
163 /* Saved X11 authentication data. This is the real data. */
164 static char *x11_saved_data = NULL;
165 static u_int x11_saved_data_len = 0;
167 /* Deadline after which all X11 connections are refused */
168 static u_int x11_refuse_time;
171 * Fake X11 authentication data. This is what the server will be sending us;
172 * we should replace any occurrences of this by the real data.
174 static u_char *x11_fake_data = NULL;
175 static u_int x11_fake_data_len;
178 /* -- agent forwarding */
182 /* AF_UNSPEC or AF_INET or AF_INET6 */
183 static int IPv4or6 = AF_UNSPEC;
186 static void port_open_helper(Channel *c, char *rtype);
188 /* non-blocking connect helpers */
189 static int connect_next(struct channel_connect *);
190 static void channel_connect_ctx_free(struct channel_connect *);
192 /* -- channel core */
195 channel_by_id(int id)
199 if (id < 0 || (u_int)id >= channels_alloc) {
200 logit("channel_by_id: %d: bad id", id);
205 logit("channel_by_id: %d: bad id: channel free", id);
212 * Returns the channel if it is allowed to receive protocol messages.
213 * Private channels, like listening sockets, may not receive messages.
216 channel_lookup(int id)
220 if ((c = channel_by_id(id)) == NULL)
224 case SSH_CHANNEL_X11_OPEN:
225 case SSH_CHANNEL_LARVAL:
226 case SSH_CHANNEL_CONNECTING:
227 case SSH_CHANNEL_DYNAMIC:
228 case SSH_CHANNEL_OPENING:
229 case SSH_CHANNEL_OPEN:
230 case SSH_CHANNEL_INPUT_DRAINING:
231 case SSH_CHANNEL_OUTPUT_DRAINING:
232 case SSH_CHANNEL_ABANDONED:
235 logit("Non-public channel %d, type %d.", id, c->type);
240 * Register filedescriptors for a channel, used when allocating a channel or
241 * when the channel consumer/producer is ready, e.g. shell exec'd
244 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
245 int extusage, int nonblock, int is_tty)
247 /* Update the maximum file descriptor value. */
248 channel_max_fd = MAX(channel_max_fd, rfd);
249 channel_max_fd = MAX(channel_max_fd, wfd);
250 channel_max_fd = MAX(channel_max_fd, efd);
253 fcntl(rfd, F_SETFD, FD_CLOEXEC);
254 if (wfd != -1 && wfd != rfd)
255 fcntl(wfd, F_SETFD, FD_CLOEXEC);
256 if (efd != -1 && efd != rfd && efd != wfd)
257 fcntl(efd, F_SETFD, FD_CLOEXEC);
261 c->sock = (rfd == wfd) ? rfd : -1;
263 c->extended_usage = extusage;
265 if ((c->isatty = is_tty) != 0)
266 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
268 /* XXX: Later AIX versions can't push as much data to tty */
269 c->wfd_isatty = is_tty || isatty(c->wfd);
272 /* enable nonblocking mode */
284 * Allocate a new channel object and set its type and socket. This will cause
285 * remote_name to be freed.
288 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
289 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
295 /* Do initial allocation if this is the first call. */
296 if (channels_alloc == 0) {
298 channels = xcalloc(channels_alloc, sizeof(Channel *));
299 for (i = 0; i < channels_alloc; i++)
302 /* Try to find a free slot where to put the new channel. */
303 for (found = -1, i = 0; i < channels_alloc; i++)
304 if (channels[i] == NULL) {
305 /* Found a free slot. */
310 /* There are no free slots. Take last+1 slot and expand the array. */
311 found = channels_alloc;
312 if (channels_alloc > 10000)
313 fatal("channel_new: internal error: channels_alloc %d "
314 "too big.", channels_alloc);
315 channels = xreallocarray(channels, channels_alloc + 10,
317 channels_alloc += 10;
318 debug2("channel: expanding %d", channels_alloc);
319 for (i = found; i < channels_alloc; i++)
322 /* Initialize and return new channel. */
323 c = channels[found] = xcalloc(1, sizeof(Channel));
324 buffer_init(&c->input);
325 buffer_init(&c->output);
326 buffer_init(&c->extended);
328 c->listening_addr = NULL;
329 c->listening_port = 0;
330 c->ostate = CHAN_OUTPUT_OPEN;
331 c->istate = CHAN_INPUT_OPEN;
333 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock, 0);
338 c->local_window = window;
339 c->local_window_max = window;
340 c->local_consumed = 0;
341 c->local_maxpacket = maxpack;
343 c->remote_name = xstrdup(remote_name);
344 c->remote_window = 0;
345 c->remote_maxpacket = 0;
347 c->single_connection = 0;
348 c->detach_user = NULL;
350 c->open_confirm = NULL;
351 c->open_confirm_ctx = NULL;
352 c->input_filter = NULL;
353 c->output_filter = NULL;
354 c->filter_ctx = NULL;
355 c->filter_cleanup = NULL;
360 c->delayed = 1; /* prevent call to channel_post handler */
361 TAILQ_INIT(&c->status_confirms);
362 debug("channel %d: new [%s]", found, remote_name);
367 channel_find_maxfd(void)
373 for (i = 0; i < channels_alloc; i++) {
376 max = MAX(max, c->rfd);
377 max = MAX(max, c->wfd);
378 max = MAX(max, c->efd);
385 channel_close_fd(int *fdp)
387 int ret = 0, fd = *fdp;
392 if (fd == channel_max_fd)
393 channel_max_fd = channel_find_maxfd();
398 /* Close all channel fd/socket. */
400 channel_close_fds(Channel *c)
402 channel_close_fd(&c->sock);
403 channel_close_fd(&c->rfd);
404 channel_close_fd(&c->wfd);
405 channel_close_fd(&c->efd);
408 /* Free the channel and close its fd/socket. */
410 channel_free(Channel *c)
414 struct channel_confirm *cc;
416 for (n = 0, i = 0; i < channels_alloc; i++)
419 debug("channel %d: free: %s, nchannels %u", c->self,
420 c->remote_name ? c->remote_name : "???", n);
422 s = channel_open_message();
423 debug3("channel %d: status: %s", c->self, s);
427 shutdown(c->sock, SHUT_RDWR);
428 channel_close_fds(c);
429 buffer_free(&c->input);
430 buffer_free(&c->output);
431 buffer_free(&c->extended);
432 free(c->remote_name);
433 c->remote_name = NULL;
436 free(c->listening_addr);
437 c->listening_addr = NULL;
438 while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
439 if (cc->abandon_cb != NULL)
440 cc->abandon_cb(c, cc->ctx);
441 TAILQ_REMOVE(&c->status_confirms, cc, entry);
442 explicit_bzero(cc, sizeof(*cc));
445 if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
446 c->filter_cleanup(c->self, c->filter_ctx);
447 channels[c->self] = NULL;
452 channel_free_all(void)
456 for (i = 0; i < channels_alloc; i++)
457 if (channels[i] != NULL)
458 channel_free(channels[i]);
462 * Closes the sockets/fds of all channels. This is used to close extra file
463 * descriptors after a fork.
466 channel_close_all(void)
470 for (i = 0; i < channels_alloc; i++)
471 if (channels[i] != NULL)
472 channel_close_fds(channels[i]);
476 * Stop listening to channels.
479 channel_stop_listening(void)
484 for (i = 0; i < channels_alloc; i++) {
488 case SSH_CHANNEL_AUTH_SOCKET:
489 case SSH_CHANNEL_PORT_LISTENER:
490 case SSH_CHANNEL_RPORT_LISTENER:
491 case SSH_CHANNEL_X11_LISTENER:
492 case SSH_CHANNEL_UNIX_LISTENER:
493 case SSH_CHANNEL_RUNIX_LISTENER:
494 channel_close_fd(&c->sock);
503 * Returns true if no channel has too much buffered data, and false if one or
504 * more channel is overfull.
507 channel_not_very_much_buffered_data(void)
512 for (i = 0; i < channels_alloc; i++) {
514 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
517 buffer_len(&c->input) > packet_get_maxsize()) {
518 debug2("channel %d: big input buffer %d",
519 c->self, buffer_len(&c->input));
523 if (buffer_len(&c->output) > packet_get_maxsize()) {
524 debug2("channel %d: big output buffer %u > %u",
525 c->self, buffer_len(&c->output),
526 packet_get_maxsize());
534 /* Returns true if any channel is still open. */
536 channel_still_open(void)
541 for (i = 0; i < channels_alloc; i++) {
546 case SSH_CHANNEL_X11_LISTENER:
547 case SSH_CHANNEL_PORT_LISTENER:
548 case SSH_CHANNEL_RPORT_LISTENER:
549 case SSH_CHANNEL_MUX_LISTENER:
550 case SSH_CHANNEL_CLOSED:
551 case SSH_CHANNEL_AUTH_SOCKET:
552 case SSH_CHANNEL_DYNAMIC:
553 case SSH_CHANNEL_CONNECTING:
554 case SSH_CHANNEL_ZOMBIE:
555 case SSH_CHANNEL_ABANDONED:
556 case SSH_CHANNEL_UNIX_LISTENER:
557 case SSH_CHANNEL_RUNIX_LISTENER:
559 case SSH_CHANNEL_LARVAL:
561 fatal("cannot happen: SSH_CHANNEL_LARVAL");
563 case SSH_CHANNEL_OPENING:
564 case SSH_CHANNEL_OPEN:
565 case SSH_CHANNEL_X11_OPEN:
566 case SSH_CHANNEL_MUX_CLIENT:
568 case SSH_CHANNEL_INPUT_DRAINING:
569 case SSH_CHANNEL_OUTPUT_DRAINING:
571 fatal("cannot happen: OUT_DRAIN");
574 fatal("channel_still_open: bad channel type %d", c->type);
581 /* Returns the id of an open channel suitable for keepaliving */
583 channel_find_open(void)
588 for (i = 0; i < channels_alloc; i++) {
590 if (c == NULL || c->remote_id < 0)
593 case SSH_CHANNEL_CLOSED:
594 case SSH_CHANNEL_DYNAMIC:
595 case SSH_CHANNEL_X11_LISTENER:
596 case SSH_CHANNEL_PORT_LISTENER:
597 case SSH_CHANNEL_RPORT_LISTENER:
598 case SSH_CHANNEL_MUX_LISTENER:
599 case SSH_CHANNEL_MUX_CLIENT:
600 case SSH_CHANNEL_OPENING:
601 case SSH_CHANNEL_CONNECTING:
602 case SSH_CHANNEL_ZOMBIE:
603 case SSH_CHANNEL_ABANDONED:
604 case SSH_CHANNEL_UNIX_LISTENER:
605 case SSH_CHANNEL_RUNIX_LISTENER:
607 case SSH_CHANNEL_LARVAL:
608 case SSH_CHANNEL_AUTH_SOCKET:
609 case SSH_CHANNEL_OPEN:
610 case SSH_CHANNEL_X11_OPEN:
612 case SSH_CHANNEL_INPUT_DRAINING:
613 case SSH_CHANNEL_OUTPUT_DRAINING:
615 fatal("cannot happen: OUT_DRAIN");
618 fatal("channel_find_open: bad channel type %d", c->type);
627 * Returns a message describing the currently open forwarded connections,
628 * suitable for sending to the client. The message contains crlf pairs for
632 channel_open_message(void)
639 buffer_init(&buffer);
640 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
641 buffer_append(&buffer, buf, strlen(buf));
642 for (i = 0; i < channels_alloc; i++) {
647 case SSH_CHANNEL_X11_LISTENER:
648 case SSH_CHANNEL_PORT_LISTENER:
649 case SSH_CHANNEL_RPORT_LISTENER:
650 case SSH_CHANNEL_CLOSED:
651 case SSH_CHANNEL_AUTH_SOCKET:
652 case SSH_CHANNEL_ZOMBIE:
653 case SSH_CHANNEL_ABANDONED:
654 case SSH_CHANNEL_MUX_CLIENT:
655 case SSH_CHANNEL_MUX_LISTENER:
656 case SSH_CHANNEL_UNIX_LISTENER:
657 case SSH_CHANNEL_RUNIX_LISTENER:
659 case SSH_CHANNEL_LARVAL:
660 case SSH_CHANNEL_OPENING:
661 case SSH_CHANNEL_CONNECTING:
662 case SSH_CHANNEL_DYNAMIC:
663 case SSH_CHANNEL_OPEN:
664 case SSH_CHANNEL_X11_OPEN:
665 case SSH_CHANNEL_INPUT_DRAINING:
666 case SSH_CHANNEL_OUTPUT_DRAINING:
667 snprintf(buf, sizeof buf,
668 " #%d %.300s (t%d r%d i%u/%d o%u/%d fd %d/%d cc %d)\r\n",
669 c->self, c->remote_name,
670 c->type, c->remote_id,
671 c->istate, buffer_len(&c->input),
672 c->ostate, buffer_len(&c->output),
673 c->rfd, c->wfd, c->ctl_chan);
674 buffer_append(&buffer, buf, strlen(buf));
677 fatal("channel_open_message: bad channel type %d", c->type);
681 buffer_append(&buffer, "\0", 1);
682 cp = xstrdup((char *)buffer_ptr(&buffer));
683 buffer_free(&buffer);
688 channel_send_open(int id)
690 Channel *c = channel_lookup(id);
693 logit("channel_send_open: %d: bad id", id);
696 debug2("channel %d: send open", id);
697 packet_start(SSH2_MSG_CHANNEL_OPEN);
698 packet_put_cstring(c->ctype);
699 packet_put_int(c->self);
700 packet_put_int(c->local_window);
701 packet_put_int(c->local_maxpacket);
706 channel_request_start(int id, char *service, int wantconfirm)
708 Channel *c = channel_lookup(id);
711 logit("channel_request_start: %d: unknown channel id", id);
714 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
715 packet_start(SSH2_MSG_CHANNEL_REQUEST);
716 packet_put_int(c->remote_id);
717 packet_put_cstring(service);
718 packet_put_char(wantconfirm);
722 channel_register_status_confirm(int id, channel_confirm_cb *cb,
723 channel_confirm_abandon_cb *abandon_cb, void *ctx)
725 struct channel_confirm *cc;
728 if ((c = channel_lookup(id)) == NULL)
729 fatal("channel_register_expect: %d: bad id", id);
731 cc = xcalloc(1, sizeof(*cc));
733 cc->abandon_cb = abandon_cb;
735 TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
739 channel_register_open_confirm(int id, channel_open_fn *fn, void *ctx)
741 Channel *c = channel_lookup(id);
744 logit("channel_register_open_confirm: %d: bad id", id);
747 c->open_confirm = fn;
748 c->open_confirm_ctx = ctx;
752 channel_register_cleanup(int id, channel_callback_fn *fn, int do_close)
754 Channel *c = channel_by_id(id);
757 logit("channel_register_cleanup: %d: bad id", id);
761 c->detach_close = do_close;
765 channel_cancel_cleanup(int id)
767 Channel *c = channel_by_id(id);
770 logit("channel_cancel_cleanup: %d: bad id", id);
773 c->detach_user = NULL;
778 channel_register_filter(int id, channel_infilter_fn *ifn,
779 channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
781 Channel *c = channel_lookup(id);
784 logit("channel_register_filter: %d: bad id", id);
787 c->input_filter = ifn;
788 c->output_filter = ofn;
790 c->filter_cleanup = cfn;
794 channel_set_fds(int id, int rfd, int wfd, int efd,
795 int extusage, int nonblock, int is_tty, u_int window_max)
797 Channel *c = channel_lookup(id);
799 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
800 fatal("channel_activate for non-larval channel %d.", id);
801 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock, is_tty);
802 c->type = SSH_CHANNEL_OPEN;
803 c->local_window = c->local_window_max = window_max;
804 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
805 packet_put_int(c->remote_id);
806 packet_put_int(c->local_window);
811 * 'channel_pre*' are called just before select() to add any bits relevant to
812 * channels in the select bitmasks.
815 * 'channel_post*': perform any appropriate operations for channels which
816 * have events pending.
818 typedef void chan_fn(Channel *c, fd_set *readset, fd_set *writeset);
819 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
820 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
824 channel_pre_listener(Channel *c, fd_set *readset, fd_set *writeset)
826 FD_SET(c->sock, readset);
831 channel_pre_connecting(Channel *c, fd_set *readset, fd_set *writeset)
833 debug3("channel %d: waiting for connection", c->self);
834 FD_SET(c->sock, writeset);
838 channel_pre_open_13(Channel *c, fd_set *readset, fd_set *writeset)
840 if (buffer_len(&c->input) < packet_get_maxsize())
841 FD_SET(c->sock, readset);
842 if (buffer_len(&c->output) > 0)
843 FD_SET(c->sock, writeset);
847 channel_pre_open(Channel *c, fd_set *readset, fd_set *writeset)
849 u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
851 if (c->istate == CHAN_INPUT_OPEN &&
853 buffer_len(&c->input) < limit &&
854 buffer_check_alloc(&c->input, CHAN_RBUF))
855 FD_SET(c->rfd, readset);
856 if (c->ostate == CHAN_OUTPUT_OPEN ||
857 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
858 if (buffer_len(&c->output) > 0) {
859 FD_SET(c->wfd, writeset);
860 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
861 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
862 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
863 c->self, c->efd, buffer_len(&c->extended));
868 /** XXX check close conditions, too */
869 if (compat20 && c->efd != -1 &&
870 !(c->istate == CHAN_INPUT_CLOSED && c->ostate == CHAN_OUTPUT_CLOSED)) {
871 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
872 buffer_len(&c->extended) > 0)
873 FD_SET(c->efd, writeset);
874 else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
875 (c->extended_usage == CHAN_EXTENDED_READ ||
876 c->extended_usage == CHAN_EXTENDED_IGNORE) &&
877 buffer_len(&c->extended) < c->remote_window)
878 FD_SET(c->efd, readset);
880 /* XXX: What about efd? races? */
885 channel_pre_input_draining(Channel *c, fd_set *readset, fd_set *writeset)
887 if (buffer_len(&c->input) == 0) {
888 packet_start(SSH_MSG_CHANNEL_CLOSE);
889 packet_put_int(c->remote_id);
891 c->type = SSH_CHANNEL_CLOSED;
892 debug2("channel %d: closing after input drain.", c->self);
898 channel_pre_output_draining(Channel *c, fd_set *readset, fd_set *writeset)
900 if (buffer_len(&c->output) == 0)
903 FD_SET(c->sock, writeset);
907 * This is a special state for X11 authentication spoofing. An opened X11
908 * connection (when authentication spoofing is being done) remains in this
909 * state until the first packet has been completely read. The authentication
910 * data in that packet is then substituted by the real data if it matches the
911 * fake data, and the channel is put into normal mode.
912 * XXX All this happens at the client side.
913 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
916 x11_open_helper(Buffer *b)
919 u_int proto_len, data_len;
921 /* Is this being called after the refusal deadline? */
922 if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
923 verbose("Rejected X11 connection after ForwardX11Timeout "
928 /* Check if the fixed size part of the packet is in buffer. */
929 if (buffer_len(b) < 12)
932 /* Parse the lengths of variable-length fields. */
934 if (ucp[0] == 0x42) { /* Byte order MSB first. */
935 proto_len = 256 * ucp[6] + ucp[7];
936 data_len = 256 * ucp[8] + ucp[9];
937 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
938 proto_len = ucp[6] + 256 * ucp[7];
939 data_len = ucp[8] + 256 * ucp[9];
941 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
946 /* Check if the whole packet is in buffer. */
948 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
951 /* Check if authentication protocol matches. */
952 if (proto_len != strlen(x11_saved_proto) ||
953 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
954 debug2("X11 connection uses different authentication protocol.");
957 /* Check if authentication data matches our fake data. */
958 if (data_len != x11_fake_data_len ||
959 timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
960 x11_fake_data, x11_fake_data_len) != 0) {
961 debug2("X11 auth data does not match fake data.");
964 /* Check fake data length */
965 if (x11_fake_data_len != x11_saved_data_len) {
966 error("X11 fake_data_len %d != saved_data_len %d",
967 x11_fake_data_len, x11_saved_data_len);
971 * Received authentication protocol and data match
972 * our fake data. Substitute the fake data with real
975 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
976 x11_saved_data, x11_saved_data_len);
981 channel_pre_x11_open_13(Channel *c, fd_set *readset, fd_set *writeset)
983 int ret = x11_open_helper(&c->output);
986 /* Start normal processing for the channel. */
987 c->type = SSH_CHANNEL_OPEN;
988 channel_pre_open_13(c, readset, writeset);
989 } else if (ret == -1) {
991 * We have received an X11 connection that has bad
992 * authentication information.
994 logit("X11 connection rejected because of wrong authentication.");
995 buffer_clear(&c->input);
996 buffer_clear(&c->output);
997 channel_close_fd(&c->sock);
999 c->type = SSH_CHANNEL_CLOSED;
1000 packet_start(SSH_MSG_CHANNEL_CLOSE);
1001 packet_put_int(c->remote_id);
1007 channel_pre_x11_open(Channel *c, fd_set *readset, fd_set *writeset)
1009 int ret = x11_open_helper(&c->output);
1011 /* c->force_drain = 1; */
1014 c->type = SSH_CHANNEL_OPEN;
1015 channel_pre_open(c, readset, writeset);
1016 } else if (ret == -1) {
1017 logit("X11 connection rejected because of wrong authentication.");
1018 debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
1019 chan_read_failed(c);
1020 buffer_clear(&c->input);
1022 buffer_clear(&c->output);
1023 /* for proto v1, the peer will send an IEOF */
1025 chan_write_failed(c);
1027 c->type = SSH_CHANNEL_OPEN;
1028 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
1033 channel_pre_mux_client(Channel *c, fd_set *readset, fd_set *writeset)
1035 if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
1036 buffer_check_alloc(&c->input, CHAN_RBUF))
1037 FD_SET(c->rfd, readset);
1038 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1039 /* clear buffer immediately (discard any partial packet) */
1040 buffer_clear(&c->input);
1042 /* Start output drain. XXX just kill chan? */
1043 chan_rcvd_oclose(c);
1045 if (c->ostate == CHAN_OUTPUT_OPEN ||
1046 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1047 if (buffer_len(&c->output) > 0)
1048 FD_SET(c->wfd, writeset);
1049 else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
1054 /* try to decode a socks4 header */
1057 channel_decode_socks4(Channel *c, fd_set *readset, fd_set *writeset)
1060 u_int len, have, i, found, need;
1065 u_int16_t dest_port;
1066 struct in_addr dest_addr;
1069 debug2("channel %d: decode socks4", c->self);
1071 have = buffer_len(&c->input);
1072 len = sizeof(s4_req);
1075 p = (char *)buffer_ptr(&c->input);
1078 /* SOCKS4A uses an invalid IP address 0.0.0.x */
1079 if (p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] != 0) {
1080 debug2("channel %d: socks4a request", c->self);
1081 /* ... and needs an extra string (the hostname) */
1084 /* Check for terminating NUL on the string(s) */
1085 for (found = 0, i = len; i < have; i++) {
1092 /* the peer is probably sending garbage */
1093 debug("channel %d: decode socks4: too long",
1100 buffer_get(&c->input, (char *)&s4_req.version, 1);
1101 buffer_get(&c->input, (char *)&s4_req.command, 1);
1102 buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
1103 buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
1104 have = buffer_len(&c->input);
1105 p = (char *)buffer_ptr(&c->input);
1106 if (memchr(p, '\0', have) == NULL)
1107 fatal("channel %d: decode socks4: user not nul terminated",
1110 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1111 len++; /* trailing '\0' */
1113 fatal("channel %d: decode socks4: len %d > have %d",
1114 c->self, len, have);
1115 strlcpy(username, p, sizeof(username));
1116 buffer_consume(&c->input, len);
1120 if (need == 1) { /* SOCKS4: one string */
1121 host = inet_ntoa(s4_req.dest_addr);
1122 c->path = xstrdup(host);
1123 } else { /* SOCKS4A: two strings */
1124 have = buffer_len(&c->input);
1125 p = (char *)buffer_ptr(&c->input);
1127 debug2("channel %d: decode socks4a: host %s/%d",
1129 len++; /* trailing '\0' */
1131 fatal("channel %d: decode socks4a: len %d > have %d",
1132 c->self, len, have);
1133 if (len > NI_MAXHOST) {
1134 error("channel %d: hostname \"%.100s\" too long",
1138 c->path = xstrdup(p);
1139 buffer_consume(&c->input, len);
1141 c->host_port = ntohs(s4_req.dest_port);
1143 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1144 c->self, c->path, c->host_port, s4_req.command);
1146 if (s4_req.command != 1) {
1147 debug("channel %d: cannot handle: %s cn %d",
1148 c->self, need == 1 ? "SOCKS4" : "SOCKS4A", s4_req.command);
1151 s4_rsp.version = 0; /* vn: 0 for reply */
1152 s4_rsp.command = 90; /* cd: req granted */
1153 s4_rsp.dest_port = 0; /* ignored */
1154 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
1155 buffer_append(&c->output, &s4_rsp, sizeof(s4_rsp));
1159 /* try to decode a socks5 header */
1160 #define SSH_SOCKS5_AUTHDONE 0x1000
1161 #define SSH_SOCKS5_NOAUTH 0x00
1162 #define SSH_SOCKS5_IPV4 0x01
1163 #define SSH_SOCKS5_DOMAIN 0x03
1164 #define SSH_SOCKS5_IPV6 0x04
1165 #define SSH_SOCKS5_CONNECT 0x01
1166 #define SSH_SOCKS5_SUCCESS 0x00
1170 channel_decode_socks5(Channel *c, fd_set *readset, fd_set *writeset)
1178 u_int16_t dest_port;
1179 char dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
1181 u_int have, need, i, found, nmethods, addrlen, af;
1183 debug2("channel %d: decode socks5", c->self);
1184 p = buffer_ptr(&c->input);
1187 have = buffer_len(&c->input);
1188 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1189 /* format: ver | nmethods | methods */
1193 if (have < nmethods + 2)
1195 /* look for method: "NO AUTHENTICATION REQUIRED" */
1196 for (found = 0, i = 2; i < nmethods + 2; i++) {
1197 if (p[i] == SSH_SOCKS5_NOAUTH) {
1203 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1207 buffer_consume(&c->input, nmethods + 2);
1208 buffer_put_char(&c->output, 0x05); /* version */
1209 buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
1210 FD_SET(c->sock, writeset);
1211 c->flags |= SSH_SOCKS5_AUTHDONE;
1212 debug2("channel %d: socks5 auth done", c->self);
1213 return 0; /* need more */
1215 debug2("channel %d: socks5 post auth", c->self);
1216 if (have < sizeof(s5_req)+1)
1217 return 0; /* need more */
1218 memcpy(&s5_req, p, sizeof(s5_req));
1219 if (s5_req.version != 0x05 ||
1220 s5_req.command != SSH_SOCKS5_CONNECT ||
1221 s5_req.reserved != 0x00) {
1222 debug2("channel %d: only socks5 connect supported", c->self);
1225 switch (s5_req.atyp){
1226 case SSH_SOCKS5_IPV4:
1230 case SSH_SOCKS5_DOMAIN:
1231 addrlen = p[sizeof(s5_req)];
1234 case SSH_SOCKS5_IPV6:
1239 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1242 need = sizeof(s5_req) + addrlen + 2;
1243 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1247 buffer_consume(&c->input, sizeof(s5_req));
1248 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1249 buffer_consume(&c->input, 1); /* host string length */
1250 buffer_get(&c->input, &dest_addr, addrlen);
1251 buffer_get(&c->input, (char *)&dest_port, 2);
1252 dest_addr[addrlen] = '\0';
1255 if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1256 if (addrlen >= NI_MAXHOST) {
1257 error("channel %d: dynamic request: socks5 hostname "
1258 "\"%.100s\" too long", c->self, dest_addr);
1261 c->path = xstrdup(dest_addr);
1263 if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
1265 c->path = xstrdup(ntop);
1267 c->host_port = ntohs(dest_port);
1269 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1270 c->self, c->path, c->host_port, s5_req.command);
1272 s5_rsp.version = 0x05;
1273 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1274 s5_rsp.reserved = 0; /* ignored */
1275 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1276 dest_port = 0; /* ignored */
1278 buffer_append(&c->output, &s5_rsp, sizeof(s5_rsp));
1279 buffer_put_int(&c->output, ntohl(INADDR_ANY)); /* bind address */
1280 buffer_append(&c->output, &dest_port, sizeof(dest_port));
1285 channel_connect_stdio_fwd(const char *host_to_connect, u_short port_to_connect,
1290 debug("channel_connect_stdio_fwd %s:%d", host_to_connect,
1293 c = channel_new("stdio-forward", SSH_CHANNEL_OPENING, in, out,
1294 -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1295 0, "stdio-forward", /*nonblock*/0);
1297 c->path = xstrdup(host_to_connect);
1298 c->host_port = port_to_connect;
1299 c->listening_port = 0;
1302 channel_register_fds(c, in, out, -1, 0, 1, 0);
1303 port_open_helper(c, "direct-tcpip");
1308 /* dynamic port forwarding */
1310 channel_pre_dynamic(Channel *c, fd_set *readset, fd_set *writeset)
1316 have = buffer_len(&c->input);
1317 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1318 /* buffer_dump(&c->input); */
1319 /* check if the fixed size part of the packet is in buffer. */
1322 FD_SET(c->sock, readset);
1325 /* try to guess the protocol */
1326 p = buffer_ptr(&c->input);
1329 ret = channel_decode_socks4(c, readset, writeset);
1332 ret = channel_decode_socks5(c, readset, writeset);
1340 } else if (ret == 0) {
1341 debug2("channel %d: pre_dynamic: need more", c->self);
1343 FD_SET(c->sock, readset);
1345 /* switch to the next state */
1346 c->type = SSH_CHANNEL_OPENING;
1347 port_open_helper(c, "direct-tcpip");
1351 /* This is our fake X11 server socket. */
1354 channel_post_x11_listener(Channel *c, fd_set *readset, fd_set *writeset)
1357 struct sockaddr_storage addr;
1358 int newsock, oerrno;
1360 char buf[16384], *remote_ipaddr;
1363 if (FD_ISSET(c->sock, readset)) {
1364 debug("X11 connection requested.");
1365 addrlen = sizeof(addr);
1366 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1367 if (c->single_connection) {
1369 debug2("single_connection: closing X11 listener.");
1370 channel_close_fd(&c->sock);
1375 if (errno != EINTR && errno != EWOULDBLOCK &&
1376 errno != ECONNABORTED)
1377 error("accept: %.100s", strerror(errno));
1378 if (errno == EMFILE || errno == ENFILE)
1379 c->notbefore = monotime() + 1;
1382 set_nodelay(newsock);
1383 remote_ipaddr = get_peer_ipaddr(newsock);
1384 remote_port = get_peer_port(newsock);
1385 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1386 remote_ipaddr, remote_port);
1388 nc = channel_new("accepted x11 socket",
1389 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1390 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1392 packet_start(SSH2_MSG_CHANNEL_OPEN);
1393 packet_put_cstring("x11");
1394 packet_put_int(nc->self);
1395 packet_put_int(nc->local_window_max);
1396 packet_put_int(nc->local_maxpacket);
1397 /* originator ipaddr and port */
1398 packet_put_cstring(remote_ipaddr);
1399 if (datafellows & SSH_BUG_X11FWD) {
1400 debug2("ssh2 x11 bug compat mode");
1402 packet_put_int(remote_port);
1406 packet_start(SSH_SMSG_X11_OPEN);
1407 packet_put_int(nc->self);
1408 if (packet_get_protocol_flags() &
1409 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1410 packet_put_cstring(buf);
1413 free(remote_ipaddr);
1418 port_open_helper(Channel *c, char *rtype)
1421 char *local_ipaddr = get_local_ipaddr(c->sock);
1422 int local_port = c->sock == -1 ? 65536 : get_local_port(c->sock);
1423 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1424 int remote_port = get_peer_port(c->sock);
1426 if (remote_port == -1) {
1427 /* Fake addr/port to appease peers that validate it (Tectia) */
1428 free(remote_ipaddr);
1429 remote_ipaddr = xstrdup("127.0.0.1");
1430 remote_port = 65535;
1433 snprintf(buf, sizeof buf,
1434 "%s: listening port %d for %.100s port %d, "
1435 "connect from %.200s port %d to %.100s port %d",
1436 rtype, c->listening_port, c->path, c->host_port,
1437 remote_ipaddr, remote_port, local_ipaddr, local_port);
1439 free(c->remote_name);
1440 c->remote_name = xstrdup(buf);
1443 packet_start(SSH2_MSG_CHANNEL_OPEN);
1444 packet_put_cstring(rtype);
1445 packet_put_int(c->self);
1446 packet_put_int(c->local_window_max);
1447 packet_put_int(c->local_maxpacket);
1448 if (strcmp(rtype, "direct-tcpip") == 0) {
1449 /* target host, port */
1450 packet_put_cstring(c->path);
1451 packet_put_int(c->host_port);
1452 } else if (strcmp(rtype, "direct-streamlocal@openssh.com") == 0) {
1454 packet_put_cstring(c->path);
1455 } else if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1457 packet_put_cstring(c->path);
1459 /* listen address, port */
1460 packet_put_cstring(c->path);
1461 packet_put_int(local_port);
1463 if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1464 /* reserved for future owner/mode info */
1465 packet_put_cstring("");
1467 /* originator host and port */
1468 packet_put_cstring(remote_ipaddr);
1469 packet_put_int((u_int)remote_port);
1473 packet_start(SSH_MSG_PORT_OPEN);
1474 packet_put_int(c->self);
1475 packet_put_cstring(c->path);
1476 packet_put_int(c->host_port);
1477 if (packet_get_protocol_flags() &
1478 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1479 packet_put_cstring(c->remote_name);
1482 free(remote_ipaddr);
1487 channel_set_reuseaddr(int fd)
1492 * Set socket options.
1493 * Allow local port reuse in TIME_WAIT.
1495 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
1496 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
1500 channel_set_x11_refuse_time(u_int refuse_time)
1502 x11_refuse_time = refuse_time;
1506 * This socket is listening for connections to a forwarded TCP/IP port.
1510 channel_post_port_listener(Channel *c, fd_set *readset, fd_set *writeset)
1513 struct sockaddr_storage addr;
1514 int newsock, nextstate;
1518 if (FD_ISSET(c->sock, readset)) {
1519 debug("Connection to port %d forwarding "
1520 "to %.100s port %d requested.",
1521 c->listening_port, c->path, c->host_port);
1523 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1524 nextstate = SSH_CHANNEL_OPENING;
1525 rtype = "forwarded-tcpip";
1526 } else if (c->type == SSH_CHANNEL_RUNIX_LISTENER) {
1527 nextstate = SSH_CHANNEL_OPENING;
1528 rtype = "forwarded-streamlocal@openssh.com";
1529 } else if (c->host_port == PORT_STREAMLOCAL) {
1530 nextstate = SSH_CHANNEL_OPENING;
1531 rtype = "direct-streamlocal@openssh.com";
1532 } else if (c->host_port == 0) {
1533 nextstate = SSH_CHANNEL_DYNAMIC;
1534 rtype = "dynamic-tcpip";
1536 nextstate = SSH_CHANNEL_OPENING;
1537 rtype = "direct-tcpip";
1540 addrlen = sizeof(addr);
1541 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1543 if (errno != EINTR && errno != EWOULDBLOCK &&
1544 errno != ECONNABORTED)
1545 error("accept: %.100s", strerror(errno));
1546 if (errno == EMFILE || errno == ENFILE)
1547 c->notbefore = monotime() + 1;
1550 if (c->host_port != PORT_STREAMLOCAL)
1551 set_nodelay(newsock);
1552 nc = channel_new(rtype, nextstate, newsock, newsock, -1,
1553 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1554 nc->listening_port = c->listening_port;
1555 nc->host_port = c->host_port;
1556 if (c->path != NULL)
1557 nc->path = xstrdup(c->path);
1559 if (nextstate != SSH_CHANNEL_DYNAMIC)
1560 port_open_helper(nc, rtype);
1565 * This is the authentication agent socket listening for connections from
1570 channel_post_auth_listener(Channel *c, fd_set *readset, fd_set *writeset)
1574 struct sockaddr_storage addr;
1577 if (FD_ISSET(c->sock, readset)) {
1578 addrlen = sizeof(addr);
1579 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1581 error("accept from auth socket: %.100s",
1583 if (errno == EMFILE || errno == ENFILE)
1584 c->notbefore = monotime() + 1;
1587 nc = channel_new("accepted auth socket",
1588 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1589 c->local_window_max, c->local_maxpacket,
1590 0, "accepted auth socket", 1);
1592 packet_start(SSH2_MSG_CHANNEL_OPEN);
1593 packet_put_cstring("auth-agent@openssh.com");
1594 packet_put_int(nc->self);
1595 packet_put_int(c->local_window_max);
1596 packet_put_int(c->local_maxpacket);
1598 packet_start(SSH_SMSG_AGENT_OPEN);
1599 packet_put_int(nc->self);
1607 channel_post_connecting(Channel *c, fd_set *readset, fd_set *writeset)
1610 socklen_t sz = sizeof(err);
1612 if (FD_ISSET(c->sock, writeset)) {
1613 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1615 error("getsockopt SO_ERROR failed");
1618 debug("channel %d: connected to %s port %d",
1619 c->self, c->connect_ctx.host, c->connect_ctx.port);
1620 channel_connect_ctx_free(&c->connect_ctx);
1621 c->type = SSH_CHANNEL_OPEN;
1623 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1624 packet_put_int(c->remote_id);
1625 packet_put_int(c->self);
1626 packet_put_int(c->local_window);
1627 packet_put_int(c->local_maxpacket);
1629 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1630 packet_put_int(c->remote_id);
1631 packet_put_int(c->self);
1634 debug("channel %d: connection failed: %s",
1635 c->self, strerror(err));
1636 /* Try next address, if any */
1637 if ((sock = connect_next(&c->connect_ctx)) > 0) {
1639 c->sock = c->rfd = c->wfd = sock;
1640 channel_max_fd = channel_find_maxfd();
1643 /* Exhausted all addresses */
1644 error("connect_to %.100s port %d: failed.",
1645 c->connect_ctx.host, c->connect_ctx.port);
1646 channel_connect_ctx_free(&c->connect_ctx);
1648 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1649 packet_put_int(c->remote_id);
1650 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1651 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1652 packet_put_cstring(strerror(err));
1653 packet_put_cstring("");
1656 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1657 packet_put_int(c->remote_id);
1667 channel_handle_rfd(Channel *c, fd_set *readset, fd_set *writeset)
1669 char buf[CHAN_RBUF];
1672 force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
1673 if (c->rfd != -1 && (force || FD_ISSET(c->rfd, readset))) {
1675 len = read(c->rfd, buf, sizeof(buf));
1676 if (len < 0 && (errno == EINTR ||
1677 ((errno == EAGAIN || errno == EWOULDBLOCK) && !force)))
1679 #ifndef PTY_ZEROREAD
1682 if ((!c->isatty && len <= 0) ||
1683 (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1685 debug2("channel %d: read<=0 rfd %d len %d",
1686 c->self, c->rfd, len);
1687 if (c->type != SSH_CHANNEL_OPEN) {
1688 debug2("channel %d: not open", c->self);
1691 } else if (compat13) {
1692 buffer_clear(&c->output);
1693 c->type = SSH_CHANNEL_INPUT_DRAINING;
1694 debug2("channel %d: input draining.", c->self);
1696 chan_read_failed(c);
1700 if (c->input_filter != NULL) {
1701 if (c->input_filter(c, buf, len) == -1) {
1702 debug2("channel %d: filter stops", c->self);
1703 chan_read_failed(c);
1705 } else if (c->datagram) {
1706 buffer_put_string(&c->input, buf, len);
1708 buffer_append(&c->input, buf, len);
1716 channel_handle_wfd(Channel *c, fd_set *readset, fd_set *writeset)
1719 u_char *data = NULL, *buf;
1720 u_int dlen, olen = 0;
1723 /* Send buffered output data to the socket. */
1725 FD_ISSET(c->wfd, writeset) &&
1726 buffer_len(&c->output) > 0) {
1727 olen = buffer_len(&c->output);
1728 if (c->output_filter != NULL) {
1729 if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
1730 debug2("channel %d: filter stops", c->self);
1731 if (c->type != SSH_CHANNEL_OPEN)
1734 chan_write_failed(c);
1737 } else if (c->datagram) {
1738 buf = data = buffer_get_string(&c->output, &dlen);
1740 buf = data = buffer_ptr(&c->output);
1741 dlen = buffer_len(&c->output);
1745 /* ignore truncated writes, datagrams might get lost */
1746 len = write(c->wfd, buf, dlen);
1748 if (len < 0 && (errno == EINTR || errno == EAGAIN ||
1749 errno == EWOULDBLOCK))
1752 if (c->type != SSH_CHANNEL_OPEN)
1755 chan_write_failed(c);
1761 /* XXX: Later AIX versions can't push as much data to tty */
1762 if (compat20 && c->wfd_isatty)
1763 dlen = MIN(dlen, 8*1024);
1766 len = write(c->wfd, buf, dlen);
1768 (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK))
1771 if (c->type != SSH_CHANNEL_OPEN) {
1772 debug2("channel %d: not open", c->self);
1775 } else if (compat13) {
1776 buffer_clear(&c->output);
1777 debug2("channel %d: input draining.", c->self);
1778 c->type = SSH_CHANNEL_INPUT_DRAINING;
1780 chan_write_failed(c);
1784 #ifndef BROKEN_TCGETATTR_ICANON
1785 if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
1786 if (tcgetattr(c->wfd, &tio) == 0 &&
1787 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1789 * Simulate echo to reduce the impact of
1790 * traffic analysis. We need to match the
1791 * size of a SSH2_MSG_CHANNEL_DATA message
1792 * (4 byte channel id + buf)
1794 packet_send_ignore(4 + len);
1799 buffer_consume(&c->output, len);
1802 if (compat20 && olen > 0)
1803 c->local_consumed += olen - buffer_len(&c->output);
1808 channel_handle_efd(Channel *c, fd_set *readset, fd_set *writeset)
1810 char buf[CHAN_RBUF];
1813 /** XXX handle drain efd, too */
1815 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1816 FD_ISSET(c->efd, writeset) &&
1817 buffer_len(&c->extended) > 0) {
1818 len = write(c->efd, buffer_ptr(&c->extended),
1819 buffer_len(&c->extended));
1820 debug2("channel %d: written %d to efd %d",
1821 c->self, len, c->efd);
1822 if (len < 0 && (errno == EINTR || errno == EAGAIN ||
1823 errno == EWOULDBLOCK))
1826 debug2("channel %d: closing write-efd %d",
1828 channel_close_fd(&c->efd);
1830 buffer_consume(&c->extended, len);
1831 c->local_consumed += len;
1833 } else if (c->efd != -1 &&
1834 (c->extended_usage == CHAN_EXTENDED_READ ||
1835 c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1836 (c->detach_close || FD_ISSET(c->efd, readset))) {
1837 len = read(c->efd, buf, sizeof(buf));
1838 debug2("channel %d: read %d from efd %d",
1839 c->self, len, c->efd);
1840 if (len < 0 && (errno == EINTR || ((errno == EAGAIN ||
1841 errno == EWOULDBLOCK) && !c->detach_close)))
1844 debug2("channel %d: closing read-efd %d",
1846 channel_close_fd(&c->efd);
1848 if (c->extended_usage == CHAN_EXTENDED_IGNORE) {
1849 debug3("channel %d: discard efd",
1852 buffer_append(&c->extended, buf, len);
1860 channel_check_window(Channel *c)
1862 if (c->type == SSH_CHANNEL_OPEN &&
1863 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1864 ((c->local_window_max - c->local_window >
1865 c->local_maxpacket*3) ||
1866 c->local_window < c->local_window_max/2) &&
1867 c->local_consumed > 0) {
1868 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1869 packet_put_int(c->remote_id);
1870 packet_put_int(c->local_consumed);
1872 debug2("channel %d: window %d sent adjust %d",
1873 c->self, c->local_window,
1875 c->local_window += c->local_consumed;
1876 c->local_consumed = 0;
1882 channel_post_open(Channel *c, fd_set *readset, fd_set *writeset)
1884 channel_handle_rfd(c, readset, writeset);
1885 channel_handle_wfd(c, readset, writeset);
1888 channel_handle_efd(c, readset, writeset);
1889 channel_check_window(c);
1893 read_mux(Channel *c, u_int need)
1895 char buf[CHAN_RBUF];
1899 if (buffer_len(&c->input) < need) {
1900 rlen = need - buffer_len(&c->input);
1901 len = read(c->rfd, buf, MIN(rlen, CHAN_RBUF));
1902 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1903 return buffer_len(&c->input);
1905 debug2("channel %d: ctl read<=0 rfd %d len %d",
1906 c->self, c->rfd, len);
1907 chan_read_failed(c);
1910 buffer_append(&c->input, buf, len);
1912 return buffer_len(&c->input);
1916 channel_post_mux_client(Channel *c, fd_set *readset, fd_set *writeset)
1922 fatal("%s: entered with !compat20", __func__);
1924 if (c->rfd != -1 && !c->mux_pause && FD_ISSET(c->rfd, readset) &&
1925 (c->istate == CHAN_INPUT_OPEN ||
1926 c->istate == CHAN_INPUT_WAIT_DRAIN)) {
1928 * Don't not read past the precise end of packets to
1929 * avoid disrupting fd passing.
1931 if (read_mux(c, 4) < 4) /* read header */
1933 need = get_u32(buffer_ptr(&c->input));
1934 #define CHANNEL_MUX_MAX_PACKET (256 * 1024)
1935 if (need > CHANNEL_MUX_MAX_PACKET) {
1936 debug2("channel %d: packet too big %u > %u",
1937 c->self, CHANNEL_MUX_MAX_PACKET, need);
1938 chan_rcvd_oclose(c);
1941 if (read_mux(c, need + 4) < need + 4) /* read body */
1943 if (c->mux_rcb(c) != 0) {
1944 debug("channel %d: mux_rcb failed", c->self);
1950 if (c->wfd != -1 && FD_ISSET(c->wfd, writeset) &&
1951 buffer_len(&c->output) > 0) {
1952 len = write(c->wfd, buffer_ptr(&c->output),
1953 buffer_len(&c->output));
1954 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1960 buffer_consume(&c->output, len);
1965 channel_post_mux_listener(Channel *c, fd_set *readset, fd_set *writeset)
1968 struct sockaddr_storage addr;
1974 if (!FD_ISSET(c->sock, readset))
1977 debug("multiplexing control connection");
1980 * Accept connection on control socket
1982 memset(&addr, 0, sizeof(addr));
1983 addrlen = sizeof(addr);
1984 if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
1986 error("%s accept: %s", __func__, strerror(errno));
1987 if (errno == EMFILE || errno == ENFILE)
1988 c->notbefore = monotime() + 1;
1992 if (getpeereid(newsock, &euid, &egid) < 0) {
1993 error("%s getpeereid failed: %s", __func__,
1998 if ((euid != 0) && (getuid() != euid)) {
1999 error("multiplex uid mismatch: peer euid %u != uid %u",
2000 (u_int)euid, (u_int)getuid());
2004 nc = channel_new("multiplex client", SSH_CHANNEL_MUX_CLIENT,
2005 newsock, newsock, -1, c->local_window_max,
2006 c->local_maxpacket, 0, "mux-control", 1);
2007 nc->mux_rcb = c->mux_rcb;
2008 debug3("%s: new mux channel %d fd %d", __func__,
2009 nc->self, nc->sock);
2010 /* establish state */
2012 /* mux state transitions must not elicit protocol messages */
2013 nc->flags |= CHAN_LOCAL;
2018 channel_post_output_drain_13(Channel *c, fd_set *readset, fd_set *writeset)
2022 /* Send buffered output data to the socket. */
2023 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
2024 len = write(c->sock, buffer_ptr(&c->output),
2025 buffer_len(&c->output));
2027 buffer_clear(&c->output);
2029 buffer_consume(&c->output, len);
2034 channel_handler_init_20(void)
2036 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
2037 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
2038 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2039 channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
2040 channel_pre[SSH_CHANNEL_UNIX_LISTENER] = &channel_pre_listener;
2041 channel_pre[SSH_CHANNEL_RUNIX_LISTENER] = &channel_pre_listener;
2042 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2043 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2044 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2045 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2046 channel_pre[SSH_CHANNEL_MUX_LISTENER] = &channel_pre_listener;
2047 channel_pre[SSH_CHANNEL_MUX_CLIENT] = &channel_pre_mux_client;
2049 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
2050 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2051 channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
2052 channel_post[SSH_CHANNEL_UNIX_LISTENER] = &channel_post_port_listener;
2053 channel_post[SSH_CHANNEL_RUNIX_LISTENER] = &channel_post_port_listener;
2054 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2055 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2056 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2057 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2058 channel_post[SSH_CHANNEL_MUX_LISTENER] = &channel_post_mux_listener;
2059 channel_post[SSH_CHANNEL_MUX_CLIENT] = &channel_post_mux_client;
2063 channel_handler_init_13(void)
2065 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
2066 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
2067 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2068 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2069 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2070 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
2071 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
2072 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2073 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2075 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
2076 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2077 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2078 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2079 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
2080 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2081 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2085 channel_handler_init_15(void)
2087 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
2088 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
2089 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2090 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2091 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2092 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2093 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2095 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2096 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2097 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2098 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
2099 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2100 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2104 channel_handler_init(void)
2108 for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
2109 channel_pre[i] = NULL;
2110 channel_post[i] = NULL;
2113 channel_handler_init_20();
2115 channel_handler_init_13();
2117 channel_handler_init_15();
2120 /* gc dead channels */
2122 channel_garbage_collect(Channel *c)
2126 if (c->detach_user != NULL) {
2127 if (!chan_is_dead(c, c->detach_close))
2129 debug2("channel %d: gc: notify user", c->self);
2130 c->detach_user(c->self, NULL);
2131 /* if we still have a callback */
2132 if (c->detach_user != NULL)
2134 debug2("channel %d: gc: user detached", c->self);
2136 if (!chan_is_dead(c, 1))
2138 debug2("channel %d: garbage collecting", c->self);
2143 channel_handler(chan_fn *ftab[], fd_set *readset, fd_set *writeset,
2144 time_t *unpause_secs)
2146 static int did_init = 0;
2152 channel_handler_init();
2156 if (unpause_secs != NULL)
2158 for (i = 0, oalloc = channels_alloc; i < oalloc; i++) {
2163 if (ftab == channel_pre)
2168 if (ftab[c->type] != NULL) {
2170 * Run handlers that are not paused.
2172 if (c->notbefore <= now)
2173 (*ftab[c->type])(c, readset, writeset);
2174 else if (unpause_secs != NULL) {
2176 * Collect the time that the earliest
2177 * channel comes off pause.
2179 debug3("%s: chan %d: skip for %d more seconds",
2181 (int)(c->notbefore - now));
2182 if (*unpause_secs == 0 ||
2183 (c->notbefore - now) < *unpause_secs)
2184 *unpause_secs = c->notbefore - now;
2187 channel_garbage_collect(c);
2189 if (unpause_secs != NULL && *unpause_secs != 0)
2190 debug3("%s: first channel unpauses in %d seconds",
2191 __func__, (int)*unpause_secs);
2195 * Allocate/update select bitmasks and add any bits relevant to channels in
2199 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
2200 u_int *nallocp, time_t *minwait_secs, int rekeying)
2202 u_int n, sz, nfdset;
2204 n = MAX(*maxfdp, channel_max_fd);
2206 nfdset = howmany(n+1, NFDBITS);
2207 /* Explicitly test here, because xrealloc isn't always called */
2208 if (nfdset && SIZE_MAX / nfdset < sizeof(fd_mask))
2209 fatal("channel_prepare_select: max_fd (%d) is too large", n);
2210 sz = nfdset * sizeof(fd_mask);
2212 /* perhaps check sz < nalloc/2 and shrink? */
2213 if (*readsetp == NULL || sz > *nallocp) {
2214 *readsetp = xreallocarray(*readsetp, nfdset, sizeof(fd_mask));
2215 *writesetp = xreallocarray(*writesetp, nfdset, sizeof(fd_mask));
2219 memset(*readsetp, 0, sz);
2220 memset(*writesetp, 0, sz);
2223 channel_handler(channel_pre, *readsetp, *writesetp,
2228 * After select, perform any appropriate operations for channels which have
2232 channel_after_select(fd_set *readset, fd_set *writeset)
2234 channel_handler(channel_post, readset, writeset, NULL);
2238 /* If there is data to send to the connection, enqueue some of it now. */
2240 channel_output_poll(void)
2245 for (i = 0; i < channels_alloc; i++) {
2251 * We are only interested in channels that can have buffered
2255 if (c->type != SSH_CHANNEL_OPEN &&
2256 c->type != SSH_CHANNEL_INPUT_DRAINING)
2259 if (c->type != SSH_CHANNEL_OPEN)
2263 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
2264 /* XXX is this true? */
2265 debug3("channel %d: will not send data after close", c->self);
2269 /* Get the amount of buffered data for this channel. */
2270 if ((c->istate == CHAN_INPUT_OPEN ||
2271 c->istate == CHAN_INPUT_WAIT_DRAIN) &&
2272 (len = buffer_len(&c->input)) > 0) {
2278 data = buffer_get_string(&c->input,
2280 if (dlen > c->remote_window ||
2281 dlen > c->remote_maxpacket) {
2282 debug("channel %d: datagram "
2283 "too big for channel",
2288 packet_start(SSH2_MSG_CHANNEL_DATA);
2289 packet_put_int(c->remote_id);
2290 packet_put_string(data, dlen);
2292 c->remote_window -= dlen;
2298 * Send some data for the other side over the secure
2302 if (len > c->remote_window)
2303 len = c->remote_window;
2304 if (len > c->remote_maxpacket)
2305 len = c->remote_maxpacket;
2307 if (packet_is_interactive()) {
2311 /* Keep the packets at reasonable size. */
2312 if (len > packet_get_maxsize()/2)
2313 len = packet_get_maxsize()/2;
2317 packet_start(compat20 ?
2318 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
2319 packet_put_int(c->remote_id);
2320 packet_put_string(buffer_ptr(&c->input), len);
2322 buffer_consume(&c->input, len);
2323 c->remote_window -= len;
2325 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2327 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
2329 * input-buffer is empty and read-socket shutdown:
2330 * tell peer, that we will not send more data: send IEOF.
2331 * hack for extended data: delay EOF if EFD still in use.
2333 if (CHANNEL_EFD_INPUT_ACTIVE(c))
2334 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
2335 c->self, c->efd, buffer_len(&c->extended));
2339 /* Send extended data, i.e. stderr */
2341 !(c->flags & CHAN_EOF_SENT) &&
2342 c->remote_window > 0 &&
2343 (len = buffer_len(&c->extended)) > 0 &&
2344 c->extended_usage == CHAN_EXTENDED_READ) {
2345 debug2("channel %d: rwin %u elen %u euse %d",
2346 c->self, c->remote_window, buffer_len(&c->extended),
2348 if (len > c->remote_window)
2349 len = c->remote_window;
2350 if (len > c->remote_maxpacket)
2351 len = c->remote_maxpacket;
2352 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
2353 packet_put_int(c->remote_id);
2354 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
2355 packet_put_string(buffer_ptr(&c->extended), len);
2357 buffer_consume(&c->extended, len);
2358 c->remote_window -= len;
2359 debug2("channel %d: sent ext data %d", c->self, len);
2365 /* -- protocol input */
2369 channel_input_data(int type, u_int32_t seq, void *ctxt)
2373 u_int data_len, win_len;
2376 /* Get the channel number and verify it. */
2377 id = packet_get_int();
2378 c = channel_lookup(id);
2380 packet_disconnect("Received data for nonexistent channel %d.", id);
2382 /* Ignore any data for non-open channels (might happen on close) */
2383 if (c->type != SSH_CHANNEL_OPEN &&
2384 c->type != SSH_CHANNEL_X11_OPEN)
2388 data = packet_get_string_ptr(&data_len);
2391 win_len += 4; /* string length header */
2394 * Ignore data for protocol > 1.3 if output end is no longer open.
2395 * For protocol 2 the sending side is reducing its window as it sends
2396 * data, so we must 'fake' consumption of the data in order to ensure
2397 * that window updates are sent back. Otherwise the connection might
2400 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
2402 c->local_window -= win_len;
2403 c->local_consumed += win_len;
2409 if (win_len > c->local_maxpacket) {
2410 logit("channel %d: rcvd big packet %d, maxpack %d",
2411 c->self, win_len, c->local_maxpacket);
2413 if (win_len > c->local_window) {
2414 logit("channel %d: rcvd too much data %d, win %d",
2415 c->self, win_len, c->local_window);
2418 c->local_window -= win_len;
2421 buffer_put_string(&c->output, data, data_len);
2423 buffer_append(&c->output, data, data_len);
2430 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
2434 u_int data_len, tcode;
2437 /* Get the channel number and verify it. */
2438 id = packet_get_int();
2439 c = channel_lookup(id);
2442 packet_disconnect("Received extended_data for bad channel %d.", id);
2443 if (c->type != SSH_CHANNEL_OPEN) {
2444 logit("channel %d: ext data for non open", id);
2447 if (c->flags & CHAN_EOF_RCVD) {
2448 if (datafellows & SSH_BUG_EXTEOF)
2449 debug("channel %d: accepting ext data after eof", id);
2451 packet_disconnect("Received extended_data after EOF "
2452 "on channel %d.", id);
2454 tcode = packet_get_int();
2456 c->extended_usage != CHAN_EXTENDED_WRITE ||
2457 tcode != SSH2_EXTENDED_DATA_STDERR) {
2458 logit("channel %d: bad ext data", c->self);
2461 data = packet_get_string(&data_len);
2463 if (data_len > c->local_window) {
2464 logit("channel %d: rcvd too much extended_data %d, win %d",
2465 c->self, data_len, c->local_window);
2469 debug2("channel %d: rcvd ext data %d", c->self, data_len);
2470 c->local_window -= data_len;
2471 buffer_append(&c->extended, data, data_len);
2478 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
2483 id = packet_get_int();
2485 c = channel_lookup(id);
2487 packet_disconnect("Received ieof for nonexistent channel %d.", id);
2490 /* XXX force input close */
2491 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
2492 debug("channel %d: FORCE input drain", c->self);
2493 c->istate = CHAN_INPUT_WAIT_DRAIN;
2494 if (buffer_len(&c->input) == 0)
2502 channel_input_close(int type, u_int32_t seq, void *ctxt)
2507 id = packet_get_int();
2509 c = channel_lookup(id);
2511 packet_disconnect("Received close for nonexistent channel %d.", id);
2514 * Send a confirmation that we have closed the channel and no more
2515 * data is coming for it.
2517 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
2518 packet_put_int(c->remote_id);
2522 * If the channel is in closed state, we have sent a close request,
2523 * and the other side will eventually respond with a confirmation.
2524 * Thus, we cannot free the channel here, because then there would be
2525 * no-one to receive the confirmation. The channel gets freed when
2526 * the confirmation arrives.
2528 if (c->type != SSH_CHANNEL_CLOSED) {
2530 * Not a closed channel - mark it as draining, which will
2531 * cause it to be freed later.
2533 buffer_clear(&c->input);
2534 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
2539 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
2542 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
2544 int id = packet_get_int();
2545 Channel *c = channel_lookup(id);
2549 packet_disconnect("Received oclose for nonexistent channel %d.", id);
2550 chan_rcvd_oclose(c);
2556 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
2558 int id = packet_get_int();
2559 Channel *c = channel_lookup(id);
2563 packet_disconnect("Received close confirmation for "
2564 "out-of-range channel %d.", id);
2565 if (c->type != SSH_CHANNEL_CLOSED && c->type != SSH_CHANNEL_ABANDONED)
2566 packet_disconnect("Received close confirmation for "
2567 "non-closed channel %d (type %d).", id, c->type);
2574 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
2579 id = packet_get_int();
2580 c = channel_lookup(id);
2582 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2583 packet_disconnect("Received open confirmation for "
2584 "non-opening channel %d.", id);
2585 remote_id = packet_get_int();
2586 /* Record the remote channel number and mark that the channel is now open. */
2587 c->remote_id = remote_id;
2588 c->type = SSH_CHANNEL_OPEN;
2591 c->remote_window = packet_get_int();
2592 c->remote_maxpacket = packet_get_int();
2593 if (c->open_confirm) {
2594 debug2("callback start");
2595 c->open_confirm(c->self, 1, c->open_confirm_ctx);
2596 debug2("callback done");
2598 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
2599 c->remote_window, c->remote_maxpacket);
2606 reason2txt(int reason)
2609 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
2610 return "administratively prohibited";
2611 case SSH2_OPEN_CONNECT_FAILED:
2612 return "connect failed";
2613 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
2614 return "unknown channel type";
2615 case SSH2_OPEN_RESOURCE_SHORTAGE:
2616 return "resource shortage";
2618 return "unknown reason";
2623 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
2626 char *msg = NULL, *lang = NULL;
2629 id = packet_get_int();
2630 c = channel_lookup(id);
2632 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2633 packet_disconnect("Received open failure for "
2634 "non-opening channel %d.", id);
2636 reason = packet_get_int();
2637 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2638 msg = packet_get_string(NULL);
2639 lang = packet_get_string(NULL);
2641 logit("channel %d: open failed: %s%s%s", id,
2642 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
2645 if (c->open_confirm) {
2646 debug2("callback start");
2647 c->open_confirm(c->self, 0, c->open_confirm_ctx);
2648 debug2("callback done");
2652 /* Schedule the channel for cleanup/deletion. */
2659 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
2668 /* Get the channel number and verify it. */
2669 id = packet_get_int();
2670 c = channel_lookup(id);
2673 logit("Received window adjust for non-open channel %d.", id);
2676 adjust = packet_get_int();
2678 debug2("channel %d: rcvd adjust %u", id, adjust);
2679 if ((tmp = c->remote_window + adjust) < c->remote_window)
2680 fatal("channel %d: adjust %u overflows remote window %u",
2681 id, adjust, c->remote_window);
2682 c->remote_window = tmp;
2688 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
2692 char *host, *originator_string;
2695 remote_id = packet_get_int();
2696 host = packet_get_string(NULL);
2697 host_port = packet_get_int();
2699 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2700 originator_string = packet_get_string(NULL);
2702 originator_string = xstrdup("unknown (remote did not supply name)");
2705 c = channel_connect_to_port(host, host_port,
2706 "connected socket", originator_string);
2707 free(originator_string);
2710 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2711 packet_put_int(remote_id);
2714 c->remote_id = remote_id;
2720 channel_input_status_confirm(int type, u_int32_t seq, void *ctxt)
2723 struct channel_confirm *cc;
2726 /* Reset keepalive timeout */
2727 packet_set_alive_timeouts(0);
2729 id = packet_get_int();
2732 debug2("channel_input_status_confirm: type %d id %d", type, id);
2734 if ((c = channel_lookup(id)) == NULL) {
2735 logit("channel_input_status_confirm: %d: unknown", id);
2738 if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
2740 cc->cb(type, c, cc->ctx);
2741 TAILQ_REMOVE(&c->status_confirms, cc, entry);
2742 explicit_bzero(cc, sizeof(*cc));
2747 /* -- tcp forwarding */
2750 channel_set_af(int af)
2757 * Determine whether or not a port forward listens to loopback, the
2758 * specified address or wildcard. On the client, a specified bind
2759 * address will always override gateway_ports. On the server, a
2760 * gateway_ports of 1 (``yes'') will override the client's specification
2761 * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
2762 * will bind to whatever address the client asked for.
2764 * Special-case listen_addrs are:
2766 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2767 * "" (empty string), "*" -> wildcard v4/v6
2768 * "localhost" -> loopback v4/v6
2769 * "127.0.0.1" / "::1" -> accepted even if gateway_ports isn't set
2772 channel_fwd_bind_addr(const char *listen_addr, int *wildcardp,
2773 int is_client, struct ForwardOptions *fwd_opts)
2775 const char *addr = NULL;
2778 if (listen_addr == NULL) {
2779 /* No address specified: default to gateway_ports setting */
2780 if (fwd_opts->gateway_ports)
2782 } else if (fwd_opts->gateway_ports || is_client) {
2783 if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
2784 strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
2785 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
2786 (!is_client && fwd_opts->gateway_ports == 1)) {
2789 * Notify client if they requested a specific listen
2790 * address and it was overridden.
2792 if (*listen_addr != '\0' &&
2793 strcmp(listen_addr, "0.0.0.0") != 0 &&
2794 strcmp(listen_addr, "*") != 0) {
2795 packet_send_debug("Forwarding listen address "
2796 "\"%s\" overridden by server "
2797 "GatewayPorts", listen_addr);
2799 } else if (strcmp(listen_addr, "localhost") != 0 ||
2800 strcmp(listen_addr, "127.0.0.1") == 0 ||
2801 strcmp(listen_addr, "::1") == 0) {
2802 /* Accept localhost address when GatewayPorts=yes */
2805 } else if (strcmp(listen_addr, "127.0.0.1") == 0 ||
2806 strcmp(listen_addr, "::1") == 0) {
2808 * If a specific IPv4/IPv6 localhost address has been
2809 * requested then accept it even if gateway_ports is in
2810 * effect. This allows the client to prefer IPv4 or IPv6.
2814 if (wildcardp != NULL)
2815 *wildcardp = wildcard;
2820 channel_setup_fwd_listener_tcpip(int type, struct Forward *fwd,
2821 int *allocated_listen_port, struct ForwardOptions *fwd_opts)
2824 int sock, r, success = 0, wildcard = 0, is_client;
2825 struct addrinfo hints, *ai, *aitop;
2826 const char *host, *addr;
2827 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2830 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
2832 if (is_client && fwd->connect_path != NULL) {
2833 host = fwd->connect_path;
2835 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2836 fwd->listen_host : fwd->connect_host;
2838 error("No forward host name.");
2841 if (strlen(host) >= NI_MAXHOST) {
2842 error("Forward host name too long.");
2847 /* Determine the bind address, cf. channel_fwd_bind_addr() comment */
2848 addr = channel_fwd_bind_addr(fwd->listen_host, &wildcard,
2849 is_client, fwd_opts);
2850 debug3("%s: type %d wildcard %d addr %s", __func__,
2851 type, wildcard, (addr == NULL) ? "NULL" : addr);
2854 * getaddrinfo returns a loopback address if the hostname is
2855 * set to NULL and hints.ai_flags is not AI_PASSIVE
2857 memset(&hints, 0, sizeof(hints));
2858 hints.ai_family = IPv4or6;
2859 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
2860 hints.ai_socktype = SOCK_STREAM;
2861 snprintf(strport, sizeof strport, "%d", fwd->listen_port);
2862 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
2864 /* This really shouldn't happen */
2865 packet_disconnect("getaddrinfo: fatal error: %s",
2866 ssh_gai_strerror(r));
2868 error("%s: getaddrinfo(%.64s): %s", __func__, addr,
2869 ssh_gai_strerror(r));
2873 if (allocated_listen_port != NULL)
2874 *allocated_listen_port = 0;
2875 for (ai = aitop; ai; ai = ai->ai_next) {
2876 switch (ai->ai_family) {
2878 lport_p = &((struct sockaddr_in *)ai->ai_addr)->
2882 lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
2889 * If allocating a port for -R forwards, then use the
2890 * same port for all address families.
2892 if (type == SSH_CHANNEL_RPORT_LISTENER && fwd->listen_port == 0 &&
2893 allocated_listen_port != NULL && *allocated_listen_port > 0)
2894 *lport_p = htons(*allocated_listen_port);
2896 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2897 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2898 error("%s: getnameinfo failed", __func__);
2901 /* Create a port to listen for the host. */
2902 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2904 /* this is no error since kernel may not support ipv6 */
2905 verbose("socket: %.100s", strerror(errno));
2909 channel_set_reuseaddr(sock);
2910 if (ai->ai_family == AF_INET6)
2911 sock_set_v6only(sock);
2913 debug("Local forwarding listening on %s port %s.",
2916 /* Bind the socket to the address. */
2917 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2918 /* address can be in use ipv6 address is already bound */
2920 error("bind: %.100s", strerror(errno));
2922 verbose("bind: %.100s", strerror(errno));
2927 /* Start listening for connections on the socket. */
2928 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2929 error("listen: %.100s", strerror(errno));
2935 * fwd->listen_port == 0 requests a dynamically allocated port -
2936 * record what we got.
2938 if (type == SSH_CHANNEL_RPORT_LISTENER && fwd->listen_port == 0 &&
2939 allocated_listen_port != NULL &&
2940 *allocated_listen_port == 0) {
2941 *allocated_listen_port = get_local_port(sock);
2942 debug("Allocated listen port %d",
2943 *allocated_listen_port);
2946 /* Allocate a channel number for the socket. */
2947 c = channel_new("port listener", type, sock, sock, -1,
2948 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2949 0, "port listener", 1);
2950 c->path = xstrdup(host);
2951 c->host_port = fwd->connect_port;
2952 c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
2953 if (fwd->listen_port == 0 && allocated_listen_port != NULL &&
2954 !(datafellows & SSH_BUG_DYNAMIC_RPORT))
2955 c->listening_port = *allocated_listen_port;
2957 c->listening_port = fwd->listen_port;
2961 error("%s: cannot listen to port: %d", __func__,
2963 freeaddrinfo(aitop);
2968 channel_setup_fwd_listener_streamlocal(int type, struct Forward *fwd,
2969 struct ForwardOptions *fwd_opts)
2971 struct sockaddr_un sunaddr;
2978 case SSH_CHANNEL_UNIX_LISTENER:
2979 if (fwd->connect_path != NULL) {
2980 if (strlen(fwd->connect_path) > sizeof(sunaddr.sun_path)) {
2981 error("Local connecting path too long: %s",
2985 path = fwd->connect_path;
2986 port = PORT_STREAMLOCAL;
2988 if (fwd->connect_host == NULL) {
2989 error("No forward host name.");
2992 if (strlen(fwd->connect_host) >= NI_MAXHOST) {
2993 error("Forward host name too long.");
2996 path = fwd->connect_host;
2997 port = fwd->connect_port;
3000 case SSH_CHANNEL_RUNIX_LISTENER:
3001 path = fwd->listen_path;
3002 port = PORT_STREAMLOCAL;
3005 error("%s: unexpected channel type %d", __func__, type);
3009 if (fwd->listen_path == NULL) {
3010 error("No forward path name.");
3013 if (strlen(fwd->listen_path) > sizeof(sunaddr.sun_path)) {
3014 error("Local listening path too long: %s", fwd->listen_path);
3018 debug3("%s: type %d path %s", __func__, type, fwd->listen_path);
3020 /* Start a Unix domain listener. */
3021 omask = umask(fwd_opts->streamlocal_bind_mask);
3022 sock = unix_listener(fwd->listen_path, SSH_LISTEN_BACKLOG,
3023 fwd_opts->streamlocal_bind_unlink);
3028 debug("Local forwarding listening on path %s.", fwd->listen_path);
3030 /* Allocate a channel number for the socket. */
3031 c = channel_new("unix listener", type, sock, sock, -1,
3032 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3033 0, "unix listener", 1);
3034 c->path = xstrdup(path);
3035 c->host_port = port;
3036 c->listening_port = PORT_STREAMLOCAL;
3037 c->listening_addr = xstrdup(fwd->listen_path);
3042 channel_cancel_rport_listener_tcpip(const char *host, u_short port)
3047 for (i = 0; i < channels_alloc; i++) {
3048 Channel *c = channels[i];
3049 if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
3051 if (strcmp(c->path, host) == 0 && c->listening_port == port) {
3052 debug2("%s: close channel %d", __func__, i);
3062 channel_cancel_rport_listener_streamlocal(const char *path)
3067 for (i = 0; i < channels_alloc; i++) {
3068 Channel *c = channels[i];
3069 if (c == NULL || c->type != SSH_CHANNEL_RUNIX_LISTENER)
3071 if (c->path == NULL)
3073 if (strcmp(c->path, path) == 0) {
3074 debug2("%s: close channel %d", __func__, i);
3084 channel_cancel_rport_listener(struct Forward *fwd)
3086 if (fwd->listen_path != NULL)
3087 return channel_cancel_rport_listener_streamlocal(fwd->listen_path);
3089 return channel_cancel_rport_listener_tcpip(fwd->listen_host, fwd->listen_port);
3093 channel_cancel_lport_listener_tcpip(const char *lhost, u_short lport,
3094 int cport, struct ForwardOptions *fwd_opts)
3098 const char *addr = channel_fwd_bind_addr(lhost, NULL, 1, fwd_opts);
3100 for (i = 0; i < channels_alloc; i++) {
3101 Channel *c = channels[i];
3102 if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
3104 if (c->listening_port != lport)
3106 if (cport == CHANNEL_CANCEL_PORT_STATIC) {
3107 /* skip dynamic forwardings */
3108 if (c->host_port == 0)
3111 if (c->host_port != cport)
3114 if ((c->listening_addr == NULL && addr != NULL) ||
3115 (c->listening_addr != NULL && addr == NULL))
3117 if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
3118 debug2("%s: close channel %d", __func__, i);
3128 channel_cancel_lport_listener_streamlocal(const char *path)
3134 error("%s: no path specified.", __func__);
3138 for (i = 0; i < channels_alloc; i++) {
3139 Channel *c = channels[i];
3140 if (c == NULL || c->type != SSH_CHANNEL_UNIX_LISTENER)
3142 if (c->listening_addr == NULL)
3144 if (strcmp(c->listening_addr, path) == 0) {
3145 debug2("%s: close channel %d", __func__, i);
3155 channel_cancel_lport_listener(struct Forward *fwd, int cport, struct ForwardOptions *fwd_opts)
3157 if (fwd->listen_path != NULL)
3158 return channel_cancel_lport_listener_streamlocal(fwd->listen_path);
3160 return channel_cancel_lport_listener_tcpip(fwd->listen_host, fwd->listen_port, cport, fwd_opts);
3163 /* protocol local port fwd, used by ssh (and sshd in v1) */
3165 channel_setup_local_fwd_listener(struct Forward *fwd, struct ForwardOptions *fwd_opts)
3167 if (fwd->listen_path != NULL) {
3168 return channel_setup_fwd_listener_streamlocal(
3169 SSH_CHANNEL_UNIX_LISTENER, fwd, fwd_opts);
3171 return channel_setup_fwd_listener_tcpip(SSH_CHANNEL_PORT_LISTENER,
3172 fwd, NULL, fwd_opts);
3176 /* protocol v2 remote port fwd, used by sshd */
3178 channel_setup_remote_fwd_listener(struct Forward *fwd,
3179 int *allocated_listen_port, struct ForwardOptions *fwd_opts)
3181 if (fwd->listen_path != NULL) {
3182 return channel_setup_fwd_listener_streamlocal(
3183 SSH_CHANNEL_RUNIX_LISTENER, fwd, fwd_opts);
3185 return channel_setup_fwd_listener_tcpip(
3186 SSH_CHANNEL_RPORT_LISTENER, fwd, allocated_listen_port,
3192 * Translate the requested rfwd listen host to something usable for
3196 channel_rfwd_bind_host(const char *listen_host)
3198 if (listen_host == NULL) {
3199 if (datafellows & SSH_BUG_RFWD_ADDR)
3203 } else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
3204 if (datafellows & SSH_BUG_RFWD_ADDR)
3213 * Initiate forwarding of connections to port "port" on remote host through
3214 * the secure channel to host:port from local side.
3215 * Returns handle (index) for updating the dynamic listen port with
3216 * channel_update_permitted_opens().
3219 channel_request_remote_forwarding(struct Forward *fwd)
3221 int type, success = 0, idx = -1;
3223 /* Send the forward request to the remote side. */
3225 packet_start(SSH2_MSG_GLOBAL_REQUEST);
3226 if (fwd->listen_path != NULL) {
3227 packet_put_cstring("streamlocal-forward@openssh.com");
3228 packet_put_char(1); /* boolean: want reply */
3229 packet_put_cstring(fwd->listen_path);
3231 packet_put_cstring("tcpip-forward");
3232 packet_put_char(1); /* boolean: want reply */
3233 packet_put_cstring(channel_rfwd_bind_host(fwd->listen_host));
3234 packet_put_int(fwd->listen_port);
3237 packet_write_wait();
3238 /* Assume that server accepts the request */
3240 } else if (fwd->listen_path == NULL) {
3241 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
3242 packet_put_int(fwd->listen_port);
3243 packet_put_cstring(fwd->connect_host);
3244 packet_put_int(fwd->connect_port);
3246 packet_write_wait();
3248 /* Wait for response from the remote side. */
3249 type = packet_read();
3251 case SSH_SMSG_SUCCESS:
3254 case SSH_SMSG_FAILURE:
3257 /* Unknown packet */
3258 packet_disconnect("Protocol error for port forward request:"
3259 "received packet type %d.", type);
3262 logit("Warning: Server does not support remote stream local forwarding.");
3265 /* Record that connection to this host/port is permitted. */
3266 permitted_opens = xreallocarray(permitted_opens,
3267 num_permitted_opens + 1, sizeof(*permitted_opens));
3268 idx = num_permitted_opens++;
3269 if (fwd->connect_path != NULL) {
3270 permitted_opens[idx].host_to_connect =
3271 xstrdup(fwd->connect_path);
3272 permitted_opens[idx].port_to_connect =
3275 permitted_opens[idx].host_to_connect =
3276 xstrdup(fwd->connect_host);
3277 permitted_opens[idx].port_to_connect =
3280 if (fwd->listen_path != NULL) {
3281 permitted_opens[idx].listen_host = NULL;
3282 permitted_opens[idx].listen_path =
3283 xstrdup(fwd->listen_path);
3284 permitted_opens[idx].listen_port = PORT_STREAMLOCAL;
3286 permitted_opens[idx].listen_host =
3287 fwd->listen_host ? xstrdup(fwd->listen_host) : NULL;
3288 permitted_opens[idx].listen_path = NULL;
3289 permitted_opens[idx].listen_port = fwd->listen_port;
3296 open_match(ForwardPermission *allowed_open, const char *requestedhost,
3299 if (allowed_open->host_to_connect == NULL)
3301 if (allowed_open->port_to_connect != FWD_PERMIT_ANY_PORT &&
3302 allowed_open->port_to_connect != requestedport)
3304 if (strcmp(allowed_open->host_to_connect, FWD_PERMIT_ANY_HOST) != 0 &&
3305 strcmp(allowed_open->host_to_connect, requestedhost) != 0)
3311 * Note that in the listen host/port case
3312 * we don't support FWD_PERMIT_ANY_PORT and
3313 * need to translate between the configured-host (listen_host)
3314 * and what we've sent to the remote server (channel_rfwd_bind_host)
3317 open_listen_match_tcpip(ForwardPermission *allowed_open,
3318 const char *requestedhost, u_short requestedport, int translate)
3320 const char *allowed_host;
3322 if (allowed_open->host_to_connect == NULL)
3324 if (allowed_open->listen_port != requestedport)
3326 if (!translate && allowed_open->listen_host == NULL &&
3327 requestedhost == NULL)
3329 allowed_host = translate ?
3330 channel_rfwd_bind_host(allowed_open->listen_host) :
3331 allowed_open->listen_host;
3332 if (allowed_host == NULL ||
3333 strcmp(allowed_host, requestedhost) != 0)
3339 open_listen_match_streamlocal(ForwardPermission *allowed_open,
3340 const char *requestedpath)
3342 if (allowed_open->host_to_connect == NULL)
3344 if (allowed_open->listen_port != PORT_STREAMLOCAL)
3346 if (allowed_open->listen_path == NULL ||
3347 strcmp(allowed_open->listen_path, requestedpath) != 0)
3353 * Request cancellation of remote forwarding of connection host:port from
3357 channel_request_rforward_cancel_tcpip(const char *host, u_short port)
3364 for (i = 0; i < num_permitted_opens; i++) {
3365 if (open_listen_match_tcpip(&permitted_opens[i], host, port, 0))
3368 if (i >= num_permitted_opens) {
3369 debug("%s: requested forward not found", __func__);
3372 packet_start(SSH2_MSG_GLOBAL_REQUEST);
3373 packet_put_cstring("cancel-tcpip-forward");
3375 packet_put_cstring(channel_rfwd_bind_host(host));
3376 packet_put_int(port);
3379 permitted_opens[i].listen_port = 0;
3380 permitted_opens[i].port_to_connect = 0;
3381 free(permitted_opens[i].host_to_connect);
3382 permitted_opens[i].host_to_connect = NULL;
3383 free(permitted_opens[i].listen_host);
3384 permitted_opens[i].listen_host = NULL;
3385 permitted_opens[i].listen_path = NULL;
3391 * Request cancellation of remote forwarding of Unix domain socket
3392 * path from local side.
3395 channel_request_rforward_cancel_streamlocal(const char *path)
3402 for (i = 0; i < num_permitted_opens; i++) {
3403 if (open_listen_match_streamlocal(&permitted_opens[i], path))
3406 if (i >= num_permitted_opens) {
3407 debug("%s: requested forward not found", __func__);
3410 packet_start(SSH2_MSG_GLOBAL_REQUEST);
3411 packet_put_cstring("cancel-streamlocal-forward@openssh.com");
3413 packet_put_cstring(path);
3416 permitted_opens[i].listen_port = 0;
3417 permitted_opens[i].port_to_connect = 0;
3418 free(permitted_opens[i].host_to_connect);
3419 permitted_opens[i].host_to_connect = NULL;
3420 permitted_opens[i].listen_host = NULL;
3421 free(permitted_opens[i].listen_path);
3422 permitted_opens[i].listen_path = NULL;
3428 * Request cancellation of remote forwarding of a connection from local side.
3431 channel_request_rforward_cancel(struct Forward *fwd)
3433 if (fwd->listen_path != NULL) {
3434 return (channel_request_rforward_cancel_streamlocal(
3437 return (channel_request_rforward_cancel_tcpip(fwd->listen_host,
3438 fwd->listen_port ? fwd->listen_port : fwd->allocated_port));
3443 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
3444 * listening for the port, and sends back a success reply (or disconnect
3445 * message if there was an error).
3448 channel_input_port_forward_request(int is_root, struct ForwardOptions *fwd_opts)
3453 /* Get arguments from the packet. */
3454 memset(&fwd, 0, sizeof(fwd));
3455 fwd.listen_port = packet_get_int();
3456 fwd.connect_host = packet_get_string(NULL);
3457 fwd.connect_port = packet_get_int();
3461 * Check that an unprivileged user is not trying to forward a
3464 if (fwd.listen_port < IPPORT_RESERVED && !is_root)
3466 "Requested forwarding of port %d but user is not root.",
3468 if (fwd.connect_port == 0)
3469 packet_disconnect("Dynamic forwarding denied.");
3472 /* Initiate forwarding */
3473 success = channel_setup_local_fwd_listener(&fwd, fwd_opts);
3475 /* Free the argument string. */
3476 free(fwd.connect_host);
3478 return (success ? 0 : -1);
3482 * Permits opening to any host/port if permitted_opens[] is empty. This is
3483 * usually called by the server, because the user could connect to any port
3484 * anyway, and the server has no way to know but to trust the client anyway.
3487 channel_permit_all_opens(void)
3489 if (num_permitted_opens == 0)
3490 all_opens_permitted = 1;
3494 channel_add_permitted_opens(char *host, int port)
3496 debug("allow port forwarding to host %s port %d", host, port);
3498 permitted_opens = xreallocarray(permitted_opens,
3499 num_permitted_opens + 1, sizeof(*permitted_opens));
3500 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
3501 permitted_opens[num_permitted_opens].port_to_connect = port;
3502 permitted_opens[num_permitted_opens].listen_host = NULL;
3503 permitted_opens[num_permitted_opens].listen_path = NULL;
3504 permitted_opens[num_permitted_opens].listen_port = 0;
3505 num_permitted_opens++;
3507 all_opens_permitted = 0;
3511 * Update the listen port for a dynamic remote forward, after
3512 * the actual 'newport' has been allocated. If 'newport' < 0 is
3513 * passed then they entry will be invalidated.
3516 channel_update_permitted_opens(int idx, int newport)
3518 if (idx < 0 || idx >= num_permitted_opens) {
3519 debug("channel_update_permitted_opens: index out of range:"
3520 " %d num_permitted_opens %d", idx, num_permitted_opens);
3523 debug("%s allowed port %d for forwarding to host %s port %d",
3524 newport > 0 ? "Updating" : "Removing",
3526 permitted_opens[idx].host_to_connect,
3527 permitted_opens[idx].port_to_connect);
3529 permitted_opens[idx].listen_port =
3530 (datafellows & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
3532 permitted_opens[idx].listen_port = 0;
3533 permitted_opens[idx].port_to_connect = 0;
3534 free(permitted_opens[idx].host_to_connect);
3535 permitted_opens[idx].host_to_connect = NULL;
3536 free(permitted_opens[idx].listen_host);
3537 permitted_opens[idx].listen_host = NULL;
3538 free(permitted_opens[idx].listen_path);
3539 permitted_opens[idx].listen_path = NULL;
3544 channel_add_adm_permitted_opens(char *host, int port)
3546 debug("config allows port forwarding to host %s port %d", host, port);
3548 permitted_adm_opens = xreallocarray(permitted_adm_opens,
3549 num_adm_permitted_opens + 1, sizeof(*permitted_adm_opens));
3550 permitted_adm_opens[num_adm_permitted_opens].host_to_connect
3552 permitted_adm_opens[num_adm_permitted_opens].port_to_connect = port;
3553 permitted_adm_opens[num_adm_permitted_opens].listen_host = NULL;
3554 permitted_adm_opens[num_adm_permitted_opens].listen_path = NULL;
3555 permitted_adm_opens[num_adm_permitted_opens].listen_port = 0;
3556 return ++num_adm_permitted_opens;
3560 channel_disable_adm_local_opens(void)
3562 channel_clear_adm_permitted_opens();
3563 permitted_adm_opens = xcalloc(sizeof(*permitted_adm_opens), 1);
3564 permitted_adm_opens[num_adm_permitted_opens].host_to_connect = NULL;
3565 num_adm_permitted_opens = 1;
3569 channel_clear_permitted_opens(void)
3573 for (i = 0; i < num_permitted_opens; i++) {
3574 free(permitted_opens[i].host_to_connect);
3575 free(permitted_opens[i].listen_host);
3576 free(permitted_opens[i].listen_path);
3578 free(permitted_opens);
3579 permitted_opens = NULL;
3580 num_permitted_opens = 0;
3584 channel_clear_adm_permitted_opens(void)
3588 for (i = 0; i < num_adm_permitted_opens; i++) {
3589 free(permitted_adm_opens[i].host_to_connect);
3590 free(permitted_adm_opens[i].listen_host);
3591 free(permitted_adm_opens[i].listen_path);
3593 free(permitted_adm_opens);
3594 permitted_adm_opens = NULL;
3595 num_adm_permitted_opens = 0;
3599 channel_print_adm_permitted_opens(void)
3603 printf("permitopen");
3604 if (num_adm_permitted_opens == 0) {
3608 for (i = 0; i < num_adm_permitted_opens; i++)
3609 if (permitted_adm_opens[i].host_to_connect == NULL)
3612 printf(" %s:%d", permitted_adm_opens[i].host_to_connect,
3613 permitted_adm_opens[i].port_to_connect);
3617 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
3619 permitopen_port(const char *p)
3623 if (strcmp(p, "*") == 0)
3624 return FWD_PERMIT_ANY_PORT;
3625 if ((port = a2port(p)) > 0)
3630 /* Try to start non-blocking connect to next host in cctx list */
3632 connect_next(struct channel_connect *cctx)
3634 int sock, saved_errno;
3635 struct sockaddr_un *sunaddr;
3636 char ntop[NI_MAXHOST], strport[MAX(NI_MAXSERV,sizeof(sunaddr->sun_path))];
3638 for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
3639 switch (cctx->ai->ai_family) {
3641 /* unix:pathname instead of host:port */
3642 sunaddr = (struct sockaddr_un *)cctx->ai->ai_addr;
3643 strlcpy(ntop, "unix", sizeof(ntop));
3644 strlcpy(strport, sunaddr->sun_path, sizeof(strport));
3648 if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
3649 ntop, sizeof(ntop), strport, sizeof(strport),
3650 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
3651 error("connect_next: getnameinfo failed");
3658 if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
3659 cctx->ai->ai_protocol)) == -1) {
3660 if (cctx->ai->ai_next == NULL)
3661 error("socket: %.100s", strerror(errno));
3663 verbose("socket: %.100s", strerror(errno));
3666 if (set_nonblock(sock) == -1)
3667 fatal("%s: set_nonblock(%d)", __func__, sock);
3668 if (connect(sock, cctx->ai->ai_addr,
3669 cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
3670 debug("connect_next: host %.100s ([%.100s]:%s): "
3671 "%.100s", cctx->host, ntop, strport,
3673 saved_errno = errno;
3675 errno = saved_errno;
3676 continue; /* fail -- try next */
3678 if (cctx->ai->ai_family != AF_UNIX)
3680 debug("connect_next: host %.100s ([%.100s]:%s) "
3681 "in progress, fd=%d", cctx->host, ntop, strport, sock);
3682 cctx->ai = cctx->ai->ai_next;
3689 channel_connect_ctx_free(struct channel_connect *cctx)
3693 if (cctx->aitop->ai_family == AF_UNIX)
3696 freeaddrinfo(cctx->aitop);
3698 memset(cctx, 0, sizeof(*cctx));
3701 /* Return CONNECTING channel to remote host:port or local socket path */
3703 connect_to(const char *name, int port, char *ctype, char *rname)
3705 struct addrinfo hints;
3708 char strport[NI_MAXSERV];
3709 struct channel_connect cctx;
3712 memset(&cctx, 0, sizeof(cctx));
3714 if (port == PORT_STREAMLOCAL) {
3715 struct sockaddr_un *sunaddr;
3716 struct addrinfo *ai;
3718 if (strlen(name) > sizeof(sunaddr->sun_path)) {
3719 error("%.100s: %.100s", name, strerror(ENAMETOOLONG));
3724 * Fake up a struct addrinfo for AF_UNIX connections.
3725 * channel_connect_ctx_free() must check ai_family
3726 * and use free() not freeaddirinfo() for AF_UNIX.
3728 ai = xmalloc(sizeof(*ai) + sizeof(*sunaddr));
3729 memset(ai, 0, sizeof(*ai) + sizeof(*sunaddr));
3730 ai->ai_addr = (struct sockaddr *)(ai + 1);
3731 ai->ai_addrlen = sizeof(*sunaddr);
3732 ai->ai_family = AF_UNIX;
3733 ai->ai_socktype = SOCK_STREAM;
3734 ai->ai_protocol = PF_UNSPEC;
3735 sunaddr = (struct sockaddr_un *)ai->ai_addr;
3736 sunaddr->sun_family = AF_UNIX;
3737 strlcpy(sunaddr->sun_path, name, sizeof(sunaddr->sun_path));
3740 memset(&hints, 0, sizeof(hints));
3741 hints.ai_family = IPv4or6;
3742 hints.ai_socktype = SOCK_STREAM;
3743 snprintf(strport, sizeof strport, "%d", port);
3744 if ((gaierr = getaddrinfo(name, strport, &hints, &cctx.aitop)) != 0) {
3745 error("connect_to %.100s: unknown host (%s)", name,
3746 ssh_gai_strerror(gaierr));
3751 cctx.host = xstrdup(name);
3753 cctx.ai = cctx.aitop;
3755 if ((sock = connect_next(&cctx)) == -1) {
3756 error("connect to %.100s port %d failed: %s",
3757 name, port, strerror(errno));
3758 channel_connect_ctx_free(&cctx);
3761 c = channel_new(ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
3762 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
3763 c->connect_ctx = cctx;
3768 channel_connect_by_listen_address(const char *listen_host,
3769 u_short listen_port, char *ctype, char *rname)
3773 for (i = 0; i < num_permitted_opens; i++) {
3774 if (open_listen_match_tcpip(&permitted_opens[i], listen_host,
3777 permitted_opens[i].host_to_connect,
3778 permitted_opens[i].port_to_connect, ctype, rname);
3781 error("WARNING: Server requests forwarding for unknown listen_port %d",
3787 channel_connect_by_listen_path(const char *path, char *ctype, char *rname)
3791 for (i = 0; i < num_permitted_opens; i++) {
3792 if (open_listen_match_streamlocal(&permitted_opens[i], path)) {
3794 permitted_opens[i].host_to_connect,
3795 permitted_opens[i].port_to_connect, ctype, rname);
3798 error("WARNING: Server requests forwarding for unknown path %.100s",
3803 /* Check if connecting to that port is permitted and connect. */
3805 channel_connect_to_port(const char *host, u_short port, char *ctype, char *rname)
3807 int i, permit, permit_adm = 1;
3809 permit = all_opens_permitted;
3811 for (i = 0; i < num_permitted_opens; i++)
3812 if (open_match(&permitted_opens[i], host, port)) {
3818 if (num_adm_permitted_opens > 0) {
3820 for (i = 0; i < num_adm_permitted_opens; i++)
3821 if (open_match(&permitted_adm_opens[i], host, port)) {
3827 if (!permit || !permit_adm) {
3828 logit("Received request to connect to host %.100s port %d, "
3829 "but the request was denied.", host, port);
3832 return connect_to(host, port, ctype, rname);
3835 /* Check if connecting to that path is permitted and connect. */
3837 channel_connect_to_path(const char *path, char *ctype, char *rname)
3839 int i, permit, permit_adm = 1;
3841 permit = all_opens_permitted;
3843 for (i = 0; i < num_permitted_opens; i++)
3844 if (open_match(&permitted_opens[i], path, PORT_STREAMLOCAL)) {
3850 if (num_adm_permitted_opens > 0) {
3852 for (i = 0; i < num_adm_permitted_opens; i++)
3853 if (open_match(&permitted_adm_opens[i], path, PORT_STREAMLOCAL)) {
3859 if (!permit || !permit_adm) {
3860 logit("Received request to connect to path %.100s, "
3861 "but the request was denied.", path);
3864 return connect_to(path, PORT_STREAMLOCAL, ctype, rname);
3868 channel_send_window_changes(void)
3873 for (i = 0; i < channels_alloc; i++) {
3874 if (channels[i] == NULL || !channels[i]->client_tty ||
3875 channels[i]->type != SSH_CHANNEL_OPEN)
3877 if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
3879 channel_request_start(i, "window-change", 0);
3880 packet_put_int((u_int)ws.ws_col);
3881 packet_put_int((u_int)ws.ws_row);
3882 packet_put_int((u_int)ws.ws_xpixel);
3883 packet_put_int((u_int)ws.ws_ypixel);
3888 /* -- X11 forwarding */
3891 * Creates an internet domain socket for listening for X11 connections.
3892 * Returns 0 and a suitable display number for the DISPLAY variable
3893 * stored in display_numberp , or -1 if an error occurs.
3896 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
3897 int single_connection, u_int *display_numberp, int **chanids)
3900 int display_number, sock;
3902 struct addrinfo hints, *ai, *aitop;
3903 char strport[NI_MAXSERV];
3904 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
3906 if (chanids == NULL)
3909 for (display_number = x11_display_offset;
3910 display_number < MAX_DISPLAYS;
3912 port = 6000 + display_number;
3913 memset(&hints, 0, sizeof(hints));
3914 hints.ai_family = IPv4or6;
3915 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
3916 hints.ai_socktype = SOCK_STREAM;
3917 snprintf(strport, sizeof strport, "%d", port);
3918 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
3919 error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
3922 for (ai = aitop; ai; ai = ai->ai_next) {
3923 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
3925 sock = socket(ai->ai_family, ai->ai_socktype,
3928 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)
3930 && (errno != EPFNOSUPPORT)
3933 error("socket: %.100s", strerror(errno));
3934 freeaddrinfo(aitop);
3937 debug("x11_create_display_inet: Socket family %d not supported",
3942 if (ai->ai_family == AF_INET6)
3943 sock_set_v6only(sock);
3944 if (x11_use_localhost)
3945 channel_set_reuseaddr(sock);
3946 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
3947 debug2("bind port %d: %.100s", port, strerror(errno));
3950 for (n = 0; n < num_socks; n++) {
3956 socks[num_socks++] = sock;
3957 if (num_socks == NUM_SOCKS)
3960 freeaddrinfo(aitop);
3964 if (display_number >= MAX_DISPLAYS) {
3965 error("Failed to allocate internet-domain X11 display socket.");
3968 /* Start listening for connections on the socket. */
3969 for (n = 0; n < num_socks; n++) {
3971 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
3972 error("listen: %.100s", strerror(errno));
3978 /* Allocate a channel for each socket. */
3979 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
3980 for (n = 0; n < num_socks; n++) {
3982 nc = channel_new("x11 listener",
3983 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
3984 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
3985 0, "X11 inet listener", 1);
3986 nc->single_connection = single_connection;
3987 (*chanids)[n] = nc->self;
3991 /* Return the display number for the DISPLAY environment variable. */
3992 *display_numberp = display_number;
3997 connect_local_xsocket_path(const char *pathname)
4000 struct sockaddr_un addr;
4002 sock = socket(AF_UNIX, SOCK_STREAM, 0);
4004 error("socket: %.100s", strerror(errno));
4005 memset(&addr, 0, sizeof(addr));
4006 addr.sun_family = AF_UNIX;
4007 strlcpy(addr.sun_path, pathname, sizeof addr.sun_path);
4008 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
4011 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
4016 connect_local_xsocket(u_int dnr)
4019 snprintf(buf, sizeof buf, _PATH_UNIX_X, dnr);
4020 return connect_local_xsocket_path(buf);
4024 x11_connect_display(void)
4026 u_int display_number;
4027 const char *display;
4028 char buf[1024], *cp;
4029 struct addrinfo hints, *ai, *aitop;
4030 char strport[NI_MAXSERV];
4031 int gaierr, sock = 0;
4033 /* Try to open a socket for the local X server. */
4034 display = getenv("DISPLAY");
4036 error("DISPLAY not set.");
4040 * Now we decode the value of the DISPLAY variable and make a
4041 * connection to the real X server.
4044 /* Check if the display is from launchd. */
4046 if (strncmp(display, "/tmp/launch", 11) == 0) {
4047 sock = connect_local_xsocket_path(display);
4051 /* OK, we now have a connection to the display. */
4056 * Check if it is a unix domain socket. Unix domain displays are in
4057 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
4059 if (strncmp(display, "unix:", 5) == 0 ||
4060 display[0] == ':') {
4061 /* Connect to the unix domain socket. */
4062 if (sscanf(strrchr(display, ':') + 1, "%u", &display_number) != 1) {
4063 error("Could not parse display number from DISPLAY: %.100s",
4067 /* Create a socket. */
4068 sock = connect_local_xsocket(display_number);
4072 /* OK, we now have a connection to the display. */
4076 * Connect to an inet socket. The DISPLAY value is supposedly
4077 * hostname:d[.s], where hostname may also be numeric IP address.
4079 strlcpy(buf, display, sizeof(buf));
4080 cp = strchr(buf, ':');
4082 error("Could not find ':' in DISPLAY: %.100s", display);
4086 /* buf now contains the host name. But first we parse the display number. */
4087 if (sscanf(cp + 1, "%u", &display_number) != 1) {
4088 error("Could not parse display number from DISPLAY: %.100s",
4093 /* Look up the host address */
4094 memset(&hints, 0, sizeof(hints));
4095 hints.ai_family = IPv4or6;
4096 hints.ai_socktype = SOCK_STREAM;
4097 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
4098 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
4099 error("%.100s: unknown host. (%s)", buf,
4100 ssh_gai_strerror(gaierr));
4103 for (ai = aitop; ai; ai = ai->ai_next) {
4104 /* Create a socket. */
4105 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
4107 debug2("socket: %.100s", strerror(errno));
4110 /* Connect it to the display. */
4111 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
4112 debug2("connect %.100s port %u: %.100s", buf,
4113 6000 + display_number, strerror(errno));
4120 freeaddrinfo(aitop);
4122 error("connect %.100s port %u: %.100s", buf, 6000 + display_number,
4131 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
4132 * the remote channel number. We should do whatever we want, and respond
4133 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
4138 x11_input_open(int type, u_int32_t seq, void *ctxt)
4141 int remote_id, sock = 0;
4144 debug("Received X11 open request.");
4146 remote_id = packet_get_int();
4148 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
4149 remote_host = packet_get_string(NULL);
4151 remote_host = xstrdup("unknown (remote did not supply name)");
4155 /* Obtain a connection to the real X display. */
4156 sock = x11_connect_display();
4158 /* Allocate a channel for this connection. */
4159 c = channel_new("connected x11 socket",
4160 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
4162 c->remote_id = remote_id;
4167 /* Send refusal to the remote host. */
4168 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
4169 packet_put_int(remote_id);
4171 /* Send a confirmation to the remote host. */
4172 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
4173 packet_put_int(remote_id);
4174 packet_put_int(c->self);
4180 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
4183 deny_input_open(int type, u_int32_t seq, void *ctxt)
4185 int rchan = packet_get_int();
4188 case SSH_SMSG_AGENT_OPEN:
4189 error("Warning: ssh server tried agent forwarding.");
4191 case SSH_SMSG_X11_OPEN:
4192 error("Warning: ssh server tried X11 forwarding.");
4195 error("deny_input_open: type %d", type);
4198 error("Warning: this is probably a break-in attempt by a malicious server.");
4199 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
4200 packet_put_int(rchan);
4206 * Requests forwarding of X11 connections, generates fake authentication
4207 * data, and enables authentication spoofing.
4208 * This should be called in the client only.
4211 x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
4212 const char *proto, const char *data, int want_reply)
4214 u_int data_len = (u_int) strlen(data) / 2;
4221 if (x11_saved_display == NULL)
4222 x11_saved_display = xstrdup(disp);
4223 else if (strcmp(disp, x11_saved_display) != 0) {
4224 error("x11_request_forwarding_with_spoofing: different "
4225 "$DISPLAY already forwarded");
4229 cp = strchr(disp, ':');
4231 cp = strchr(cp, '.');
4233 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
4237 if (x11_saved_proto == NULL) {
4238 /* Save protocol name. */
4239 x11_saved_proto = xstrdup(proto);
4241 * Extract real authentication data and generate fake data
4242 * of the same length.
4244 x11_saved_data = xmalloc(data_len);
4245 x11_fake_data = xmalloc(data_len);
4246 for (i = 0; i < data_len; i++) {
4247 if (sscanf(data + 2 * i, "%2x", &value) != 1)
4248 fatal("x11_request_forwarding: bad "
4249 "authentication data: %.100s", data);
4252 x11_saved_data[i] = value;
4253 x11_fake_data[i] = rnd & 0xff;
4256 x11_saved_data_len = data_len;
4257 x11_fake_data_len = data_len;
4260 /* Convert the fake data into hex. */
4261 new_data = tohex(x11_fake_data, data_len);
4263 /* Send the request packet. */
4265 channel_request_start(client_session_id, "x11-req", want_reply);
4266 packet_put_char(0); /* XXX bool single connection */
4268 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
4270 packet_put_cstring(proto);
4271 packet_put_cstring(new_data);
4272 packet_put_int(screen_number);
4274 packet_write_wait();
4279 /* -- agent forwarding */
4281 /* Sends a message to the server to request authentication fd forwarding. */
4284 auth_request_forwarding(void)
4286 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
4288 packet_write_wait();