2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * This file contains functions for generic socket connection forwarding.
6 * There is also code for initiating connection forwarding for X11 connections,
7 * arbitrary tcp/ip connections, and the authentication agent connection.
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
15 * SSH2 support added by Markus Friedl.
16 * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl. All rights reserved.
17 * Copyright (c) 1999 Dug Song. All rights reserved.
18 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted provided that the following conditions
23 * 1. Redistributions of source code must retain the above copyright
24 * notice, this list of conditions and the following disclaimer.
25 * 2. Redistributions in binary form must reproduce the above copyright
26 * notice, this list of conditions and the following disclaimer in the
27 * documentation and/or other materials provided with the distribution.
29 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 RCSID("$OpenBSD: channels.c,v 1.183 2002/09/17 07:47:02 itojun Exp $");
43 RCSID("$FreeBSD: src/crypto/openssh/channels.c,v 1.1.1.1.2.8 2003/02/03 17:31:06 des Exp $");
44 RCSID("$DragonFly: src/crypto/openssh/Attic/channels.c,v 1.2 2003/06/17 04:24:36 dillon Exp $");
58 #include "pathnames.h"
64 * Pointer to an array containing all allocated channels. The array is
65 * dynamically extended as needed.
67 static Channel **channels = NULL;
70 * Size of the channel array. All slots of the array must always be
71 * initialized (at least the type field); unused slots set to NULL
73 static int channels_alloc = 0;
76 * Maximum file descriptor value used in any of the channels. This is
77 * updated in channel_new.
79 static int channel_max_fd = 0;
82 /* -- tcp forwarding */
85 * Data structure for storing which hosts are permitted for forward requests.
86 * The local sides of any remote forwards are stored in this array to prevent
87 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
88 * network (which might be behind a firewall).
91 char *host_to_connect; /* Connect to 'host'. */
92 u_short port_to_connect; /* Connect to 'port'. */
93 u_short listen_port; /* Remote side should listen port number. */
96 /* List of all permitted host/port pairs to connect. */
97 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
99 /* Number of permitted host/port pairs in the array. */
100 static int num_permitted_opens = 0;
102 * If this is true, all opens are permitted. This is the case on the server
103 * on which we have to trust the client anyway, and the user could do
104 * anything after logging in anyway.
106 static int all_opens_permitted = 0;
109 /* -- X11 forwarding */
111 /* Maximum number of fake X11 displays to try. */
112 #define MAX_DISPLAYS 1000
114 /* Saved X11 authentication protocol name. */
115 static char *x11_saved_proto = NULL;
117 /* Saved X11 authentication data. This is the real data. */
118 static char *x11_saved_data = NULL;
119 static u_int x11_saved_data_len = 0;
122 * Fake X11 authentication data. This is what the server will be sending us;
123 * we should replace any occurrences of this by the real data.
125 static char *x11_fake_data = NULL;
126 static u_int x11_fake_data_len;
129 /* -- agent forwarding */
133 /* AF_UNSPEC or AF_INET or AF_INET6 */
134 static int IPv4or6 = AF_UNSPEC;
137 static void port_open_helper(Channel *c, char *rtype);
139 /* -- channel core */
142 channel_lookup(int id)
146 if (id < 0 || id >= channels_alloc) {
147 log("channel_lookup: %d: bad id", id);
152 log("channel_lookup: %d: bad id: channel free", id);
159 * Register filedescriptors for a channel, used when allocating a channel or
160 * when the channel consumer/producer is ready, e.g. shell exec'd
164 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
165 int extusage, int nonblock)
167 /* Update the maximum file descriptor value. */
168 channel_max_fd = MAX(channel_max_fd, rfd);
169 channel_max_fd = MAX(channel_max_fd, wfd);
170 channel_max_fd = MAX(channel_max_fd, efd);
172 /* XXX set close-on-exec -markus */
176 c->sock = (rfd == wfd) ? rfd : -1;
178 c->extended_usage = extusage;
180 /* XXX ugly hack: nonblock is only set by the server */
181 if (nonblock && isatty(c->rfd)) {
182 debug("channel %d: rfd %d isatty", c->self, c->rfd);
184 if (!isatty(c->wfd)) {
185 error("channel %d: wfd %d is not a tty?",
191 c->wfd_isatty = isatty(c->wfd);
193 /* enable nonblocking mode */
205 * Allocate a new channel object and set its type and socket. This will cause
206 * remote_name to be freed.
210 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
211 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
216 /* Do initial allocation if this is the first call. */
217 if (channels_alloc == 0) {
219 channels = xmalloc(channels_alloc * sizeof(Channel *));
220 for (i = 0; i < channels_alloc; i++)
222 fatal_add_cleanup((void (*) (void *)) channel_free_all, NULL);
224 /* Try to find a free slot where to put the new channel. */
225 for (found = -1, i = 0; i < channels_alloc; i++)
226 if (channels[i] == NULL) {
227 /* Found a free slot. */
232 /* There are no free slots. Take last+1 slot and expand the array. */
233 found = channels_alloc;
234 channels_alloc += 10;
235 if (channels_alloc > 10000)
236 fatal("channel_new: internal error: channels_alloc %d "
237 "too big.", channels_alloc);
238 debug2("channel: expanding %d", channels_alloc);
239 channels = xrealloc(channels, channels_alloc * sizeof(Channel *));
240 for (i = found; i < channels_alloc; i++)
243 /* Initialize and return new channel. */
244 c = channels[found] = xmalloc(sizeof(Channel));
245 memset(c, 0, sizeof(Channel));
246 buffer_init(&c->input);
247 buffer_init(&c->output);
248 buffer_init(&c->extended);
249 c->ostate = CHAN_OUTPUT_OPEN;
250 c->istate = CHAN_INPUT_OPEN;
252 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
256 c->local_window = window;
257 c->local_window_max = window;
258 c->local_consumed = 0;
259 c->local_maxpacket = maxpack;
261 c->remote_name = remote_name;
262 c->remote_window = 0;
263 c->remote_maxpacket = 0;
265 c->single_connection = 0;
266 c->detach_user = NULL;
268 c->input_filter = NULL;
269 debug("channel %d: new [%s]", found, remote_name);
274 channel_find_maxfd(void)
279 for (i = 0; i < channels_alloc; i++) {
282 max = MAX(max, c->rfd);
283 max = MAX(max, c->wfd);
284 max = MAX(max, c->efd);
291 channel_close_fd(int *fdp)
293 int ret = 0, fd = *fdp;
298 if (fd == channel_max_fd)
299 channel_max_fd = channel_find_maxfd();
304 /* Close all channel fd/socket. */
307 channel_close_fds(Channel *c)
309 debug3("channel_close_fds: channel %d: r %d w %d e %d",
310 c->self, c->rfd, c->wfd, c->efd);
312 channel_close_fd(&c->sock);
313 channel_close_fd(&c->rfd);
314 channel_close_fd(&c->wfd);
315 channel_close_fd(&c->efd);
318 /* Free the channel and close its fd/socket. */
321 channel_free(Channel *c)
326 for (n = 0, i = 0; i < channels_alloc; i++)
329 debug("channel_free: channel %d: %s, nchannels %d", c->self,
330 c->remote_name ? c->remote_name : "???", n);
332 s = channel_open_message();
333 debug3("channel_free: status: %s", s);
337 shutdown(c->sock, SHUT_RDWR);
338 channel_close_fds(c);
339 buffer_free(&c->input);
340 buffer_free(&c->output);
341 buffer_free(&c->extended);
342 if (c->remote_name) {
343 xfree(c->remote_name);
344 c->remote_name = NULL;
346 channels[c->self] = NULL;
351 channel_free_all(void)
355 for (i = 0; i < channels_alloc; i++)
356 if (channels[i] != NULL)
357 channel_free(channels[i]);
361 * Closes the sockets/fds of all channels. This is used to close extra file
362 * descriptors after a fork.
366 channel_close_all(void)
370 for (i = 0; i < channels_alloc; i++)
371 if (channels[i] != NULL)
372 channel_close_fds(channels[i]);
376 * Stop listening to channels.
380 channel_stop_listening(void)
385 for (i = 0; i < channels_alloc; i++) {
389 case SSH_CHANNEL_AUTH_SOCKET:
390 case SSH_CHANNEL_PORT_LISTENER:
391 case SSH_CHANNEL_RPORT_LISTENER:
392 case SSH_CHANNEL_X11_LISTENER:
393 channel_close_fd(&c->sock);
402 * Returns true if no channel has too much buffered data, and false if one or
403 * more channel is overfull.
407 channel_not_very_much_buffered_data(void)
412 for (i = 0; i < channels_alloc; i++) {
414 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
417 buffer_len(&c->input) > packet_get_maxsize()) {
418 debug("channel %d: big input buffer %d",
419 c->self, buffer_len(&c->input));
423 if (buffer_len(&c->output) > packet_get_maxsize()) {
424 debug("channel %d: big output buffer %d > %d",
425 c->self, buffer_len(&c->output),
426 packet_get_maxsize());
434 /* Returns true if any channel is still open. */
437 channel_still_open(void)
442 for (i = 0; i < channels_alloc; i++) {
447 case SSH_CHANNEL_X11_LISTENER:
448 case SSH_CHANNEL_PORT_LISTENER:
449 case SSH_CHANNEL_RPORT_LISTENER:
450 case SSH_CHANNEL_CLOSED:
451 case SSH_CHANNEL_AUTH_SOCKET:
452 case SSH_CHANNEL_DYNAMIC:
453 case SSH_CHANNEL_CONNECTING:
454 case SSH_CHANNEL_ZOMBIE:
456 case SSH_CHANNEL_LARVAL:
458 fatal("cannot happen: SSH_CHANNEL_LARVAL");
460 case SSH_CHANNEL_OPENING:
461 case SSH_CHANNEL_OPEN:
462 case SSH_CHANNEL_X11_OPEN:
464 case SSH_CHANNEL_INPUT_DRAINING:
465 case SSH_CHANNEL_OUTPUT_DRAINING:
467 fatal("cannot happen: OUT_DRAIN");
470 fatal("channel_still_open: bad channel type %d", c->type);
477 /* Returns the id of an open channel suitable for keepaliving */
480 channel_find_open(void)
485 for (i = 0; i < channels_alloc; i++) {
490 case SSH_CHANNEL_CLOSED:
491 case SSH_CHANNEL_DYNAMIC:
492 case SSH_CHANNEL_X11_LISTENER:
493 case SSH_CHANNEL_PORT_LISTENER:
494 case SSH_CHANNEL_RPORT_LISTENER:
495 case SSH_CHANNEL_OPENING:
496 case SSH_CHANNEL_CONNECTING:
497 case SSH_CHANNEL_ZOMBIE:
499 case SSH_CHANNEL_LARVAL:
500 case SSH_CHANNEL_AUTH_SOCKET:
501 case SSH_CHANNEL_OPEN:
502 case SSH_CHANNEL_X11_OPEN:
504 case SSH_CHANNEL_INPUT_DRAINING:
505 case SSH_CHANNEL_OUTPUT_DRAINING:
507 fatal("cannot happen: OUT_DRAIN");
510 fatal("channel_find_open: bad channel type %d", c->type);
519 * Returns a message describing the currently open forwarded connections,
520 * suitable for sending to the client. The message contains crlf pairs for
525 channel_open_message(void)
532 buffer_init(&buffer);
533 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
534 buffer_append(&buffer, buf, strlen(buf));
535 for (i = 0; i < channels_alloc; i++) {
540 case SSH_CHANNEL_X11_LISTENER:
541 case SSH_CHANNEL_PORT_LISTENER:
542 case SSH_CHANNEL_RPORT_LISTENER:
543 case SSH_CHANNEL_CLOSED:
544 case SSH_CHANNEL_AUTH_SOCKET:
545 case SSH_CHANNEL_ZOMBIE:
547 case SSH_CHANNEL_LARVAL:
548 case SSH_CHANNEL_OPENING:
549 case SSH_CHANNEL_CONNECTING:
550 case SSH_CHANNEL_DYNAMIC:
551 case SSH_CHANNEL_OPEN:
552 case SSH_CHANNEL_X11_OPEN:
553 case SSH_CHANNEL_INPUT_DRAINING:
554 case SSH_CHANNEL_OUTPUT_DRAINING:
555 snprintf(buf, sizeof buf, " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
556 c->self, c->remote_name,
557 c->type, c->remote_id,
558 c->istate, buffer_len(&c->input),
559 c->ostate, buffer_len(&c->output),
561 buffer_append(&buffer, buf, strlen(buf));
564 fatal("channel_open_message: bad channel type %d", c->type);
568 buffer_append(&buffer, "\0", 1);
569 cp = xstrdup(buffer_ptr(&buffer));
570 buffer_free(&buffer);
575 channel_send_open(int id)
577 Channel *c = channel_lookup(id);
580 log("channel_send_open: %d: bad id", id);
583 debug("send channel open %d", id);
584 packet_start(SSH2_MSG_CHANNEL_OPEN);
585 packet_put_cstring(c->ctype);
586 packet_put_int(c->self);
587 packet_put_int(c->local_window);
588 packet_put_int(c->local_maxpacket);
593 channel_request_start(int local_id, char *service, int wantconfirm)
595 Channel *c = channel_lookup(local_id);
598 log("channel_request_start: %d: unknown channel id", local_id);
601 debug("channel request %d: %s", local_id, service) ;
602 packet_start(SSH2_MSG_CHANNEL_REQUEST);
603 packet_put_int(c->remote_id);
604 packet_put_cstring(service);
605 packet_put_char(wantconfirm);
608 channel_register_confirm(int id, channel_callback_fn *fn)
610 Channel *c = channel_lookup(id);
613 log("channel_register_comfirm: %d: bad id", id);
619 channel_register_cleanup(int id, channel_callback_fn *fn)
621 Channel *c = channel_lookup(id);
624 log("channel_register_cleanup: %d: bad id", id);
630 channel_cancel_cleanup(int id)
632 Channel *c = channel_lookup(id);
635 log("channel_cancel_cleanup: %d: bad id", id);
638 c->detach_user = NULL;
641 channel_register_filter(int id, channel_filter_fn *fn)
643 Channel *c = channel_lookup(id);
646 log("channel_register_filter: %d: bad id", id);
649 c->input_filter = fn;
653 channel_set_fds(int id, int rfd, int wfd, int efd,
654 int extusage, int nonblock, u_int window_max)
656 Channel *c = channel_lookup(id);
658 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
659 fatal("channel_activate for non-larval channel %d.", id);
660 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
661 c->type = SSH_CHANNEL_OPEN;
662 c->local_window = c->local_window_max = window_max;
663 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
664 packet_put_int(c->remote_id);
665 packet_put_int(c->local_window);
670 * 'channel_pre*' are called just before select() to add any bits relevant to
671 * channels in the select bitmasks.
674 * 'channel_post*': perform any appropriate operations for channels which
675 * have events pending.
677 typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
678 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
679 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
682 channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
684 FD_SET(c->sock, readset);
688 channel_pre_connecting(Channel *c, fd_set * readset, fd_set * writeset)
690 debug3("channel %d: waiting for connection", c->self);
691 FD_SET(c->sock, writeset);
695 channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
697 if (buffer_len(&c->input) < packet_get_maxsize())
698 FD_SET(c->sock, readset);
699 if (buffer_len(&c->output) > 0)
700 FD_SET(c->sock, writeset);
704 channel_pre_open(Channel *c, fd_set * readset, fd_set * writeset)
706 u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
708 if (c->istate == CHAN_INPUT_OPEN &&
710 buffer_len(&c->input) < limit)
711 FD_SET(c->rfd, readset);
712 if (c->ostate == CHAN_OUTPUT_OPEN ||
713 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
714 if (buffer_len(&c->output) > 0) {
715 FD_SET(c->wfd, writeset);
716 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
717 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
718 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
719 c->self, c->efd, buffer_len(&c->extended));
724 /** XXX check close conditions, too */
725 if (compat20 && c->efd != -1) {
726 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
727 buffer_len(&c->extended) > 0)
728 FD_SET(c->efd, writeset);
729 else if (!(c->flags & CHAN_EOF_SENT) &&
730 c->extended_usage == CHAN_EXTENDED_READ &&
731 buffer_len(&c->extended) < c->remote_window)
732 FD_SET(c->efd, readset);
737 channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
739 if (buffer_len(&c->input) == 0) {
740 packet_start(SSH_MSG_CHANNEL_CLOSE);
741 packet_put_int(c->remote_id);
743 c->type = SSH_CHANNEL_CLOSED;
744 debug("channel %d: closing after input drain.", c->self);
749 channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
751 if (buffer_len(&c->output) == 0)
754 FD_SET(c->sock, writeset);
758 * This is a special state for X11 authentication spoofing. An opened X11
759 * connection (when authentication spoofing is being done) remains in this
760 * state until the first packet has been completely read. The authentication
761 * data in that packet is then substituted by the real data if it matches the
762 * fake data, and the channel is put into normal mode.
763 * XXX All this happens at the client side.
764 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
767 x11_open_helper(Buffer *b)
770 u_int proto_len, data_len;
772 /* Check if the fixed size part of the packet is in buffer. */
773 if (buffer_len(b) < 12)
776 /* Parse the lengths of variable-length fields. */
778 if (ucp[0] == 0x42) { /* Byte order MSB first. */
779 proto_len = 256 * ucp[6] + ucp[7];
780 data_len = 256 * ucp[8] + ucp[9];
781 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
782 proto_len = ucp[6] + 256 * ucp[7];
783 data_len = ucp[8] + 256 * ucp[9];
785 debug("Initial X11 packet contains bad byte order byte: 0x%x",
790 /* Check if the whole packet is in buffer. */
792 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
795 /* Check if authentication protocol matches. */
796 if (proto_len != strlen(x11_saved_proto) ||
797 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
798 debug("X11 connection uses different authentication protocol.");
801 /* Check if authentication data matches our fake data. */
802 if (data_len != x11_fake_data_len ||
803 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
804 x11_fake_data, x11_fake_data_len) != 0) {
805 debug("X11 auth data does not match fake data.");
808 /* Check fake data length */
809 if (x11_fake_data_len != x11_saved_data_len) {
810 error("X11 fake_data_len %d != saved_data_len %d",
811 x11_fake_data_len, x11_saved_data_len);
815 * Received authentication protocol and data match
816 * our fake data. Substitute the fake data with real
819 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
820 x11_saved_data, x11_saved_data_len);
825 channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
827 int ret = x11_open_helper(&c->output);
830 /* Start normal processing for the channel. */
831 c->type = SSH_CHANNEL_OPEN;
832 channel_pre_open_13(c, readset, writeset);
833 } else if (ret == -1) {
835 * We have received an X11 connection that has bad
836 * authentication information.
838 log("X11 connection rejected because of wrong authentication.");
839 buffer_clear(&c->input);
840 buffer_clear(&c->output);
841 channel_close_fd(&c->sock);
843 c->type = SSH_CHANNEL_CLOSED;
844 packet_start(SSH_MSG_CHANNEL_CLOSE);
845 packet_put_int(c->remote_id);
851 channel_pre_x11_open(Channel *c, fd_set * readset, fd_set * writeset)
853 int ret = x11_open_helper(&c->output);
855 /* c->force_drain = 1; */
858 c->type = SSH_CHANNEL_OPEN;
859 channel_pre_open(c, readset, writeset);
860 } else if (ret == -1) {
861 log("X11 connection rejected because of wrong authentication.");
862 debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
864 buffer_clear(&c->input);
866 buffer_clear(&c->output);
867 /* for proto v1, the peer will send an IEOF */
869 chan_write_failed(c);
871 c->type = SSH_CHANNEL_OPEN;
872 debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
876 /* try to decode a socks4 header */
878 channel_decode_socks4(Channel *c, fd_set * readset, fd_set * writeset)
881 int len, have, i, found;
887 struct in_addr dest_addr;
890 debug2("channel %d: decode socks4", c->self);
892 have = buffer_len(&c->input);
893 len = sizeof(s4_req);
896 p = buffer_ptr(&c->input);
897 for (found = 0, i = len; i < have; i++) {
903 /* the peer is probably sending garbage */
904 debug("channel %d: decode socks4: too long",
911 buffer_get(&c->input, (char *)&s4_req.version, 1);
912 buffer_get(&c->input, (char *)&s4_req.command, 1);
913 buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
914 buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
915 have = buffer_len(&c->input);
916 p = buffer_ptr(&c->input);
918 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
920 fatal("channel %d: decode socks4: len %d > have %d",
922 strlcpy(username, p, sizeof(username));
923 buffer_consume(&c->input, len);
924 buffer_consume(&c->input, 1); /* trailing '\0' */
926 host = inet_ntoa(s4_req.dest_addr);
927 strlcpy(c->path, host, sizeof(c->path));
928 c->host_port = ntohs(s4_req.dest_port);
930 debug("channel %d: dynamic request: socks4 host %s port %u command %u",
931 c->self, host, c->host_port, s4_req.command);
933 if (s4_req.command != 1) {
934 debug("channel %d: cannot handle: socks4 cn %d",
935 c->self, s4_req.command);
938 s4_rsp.version = 0; /* vn: 0 for reply */
939 s4_rsp.command = 90; /* cd: req granted */
940 s4_rsp.dest_port = 0; /* ignored */
941 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
942 buffer_append(&c->output, (char *)&s4_rsp, sizeof(s4_rsp));
946 /* dynamic port forwarding */
948 channel_pre_dynamic(Channel *c, fd_set * readset, fd_set * writeset)
953 have = buffer_len(&c->input);
955 debug2("channel %d: pre_dynamic: have %d", c->self, have);
956 /* buffer_dump(&c->input); */
957 /* check if the fixed size part of the packet is in buffer. */
960 FD_SET(c->sock, readset);
963 /* try to guess the protocol */
964 p = buffer_ptr(&c->input);
967 ret = channel_decode_socks4(c, readset, writeset);
975 } else if (ret == 0) {
976 debug2("channel %d: pre_dynamic: need more", c->self);
978 FD_SET(c->sock, readset);
980 /* switch to the next state */
981 c->type = SSH_CHANNEL_OPENING;
982 port_open_helper(c, "direct-tcpip");
986 /* This is our fake X11 server socket. */
988 channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
991 struct sockaddr addr;
994 char buf[16384], *remote_ipaddr;
997 if (FD_ISSET(c->sock, readset)) {
998 debug("X11 connection requested.");
999 addrlen = sizeof(addr);
1000 newsock = accept(c->sock, &addr, &addrlen);
1001 if (c->single_connection) {
1002 debug("single_connection: closing X11 listener.");
1003 channel_close_fd(&c->sock);
1007 error("accept: %.100s", strerror(errno));
1010 set_nodelay(newsock);
1011 remote_ipaddr = get_peer_ipaddr(newsock);
1012 remote_port = get_peer_port(newsock);
1013 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1014 remote_ipaddr, remote_port);
1016 nc = channel_new("accepted x11 socket",
1017 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1018 c->local_window_max, c->local_maxpacket,
1019 0, xstrdup(buf), 1);
1021 packet_start(SSH2_MSG_CHANNEL_OPEN);
1022 packet_put_cstring("x11");
1023 packet_put_int(nc->self);
1024 packet_put_int(nc->local_window_max);
1025 packet_put_int(nc->local_maxpacket);
1026 /* originator ipaddr and port */
1027 packet_put_cstring(remote_ipaddr);
1028 if (datafellows & SSH_BUG_X11FWD) {
1029 debug("ssh2 x11 bug compat mode");
1031 packet_put_int(remote_port);
1035 packet_start(SSH_SMSG_X11_OPEN);
1036 packet_put_int(nc->self);
1037 if (packet_get_protocol_flags() &
1038 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1039 packet_put_cstring(buf);
1042 xfree(remote_ipaddr);
1047 port_open_helper(Channel *c, char *rtype)
1051 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1052 u_short remote_port = get_peer_port(c->sock);
1054 direct = (strcmp(rtype, "direct-tcpip") == 0);
1056 snprintf(buf, sizeof buf,
1057 "%s: listening port %d for %.100s port %d, "
1058 "connect from %.200s port %d",
1059 rtype, c->listening_port, c->path, c->host_port,
1060 remote_ipaddr, remote_port);
1062 xfree(c->remote_name);
1063 c->remote_name = xstrdup(buf);
1066 packet_start(SSH2_MSG_CHANNEL_OPEN);
1067 packet_put_cstring(rtype);
1068 packet_put_int(c->self);
1069 packet_put_int(c->local_window_max);
1070 packet_put_int(c->local_maxpacket);
1072 /* target host, port */
1073 packet_put_cstring(c->path);
1074 packet_put_int(c->host_port);
1076 /* listen address, port */
1077 packet_put_cstring(c->path);
1078 packet_put_int(c->listening_port);
1080 /* originator host and port */
1081 packet_put_cstring(remote_ipaddr);
1082 packet_put_int(remote_port);
1085 packet_start(SSH_MSG_PORT_OPEN);
1086 packet_put_int(c->self);
1087 packet_put_cstring(c->path);
1088 packet_put_int(c->host_port);
1089 if (packet_get_protocol_flags() &
1090 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1091 packet_put_cstring(c->remote_name);
1094 xfree(remote_ipaddr);
1098 * This socket is listening for connections to a forwarded TCP/IP port.
1101 channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
1104 struct sockaddr addr;
1105 int newsock, nextstate;
1109 if (FD_ISSET(c->sock, readset)) {
1110 debug("Connection to port %d forwarding "
1111 "to %.100s port %d requested.",
1112 c->listening_port, c->path, c->host_port);
1114 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1115 nextstate = SSH_CHANNEL_OPENING;
1116 rtype = "forwarded-tcpip";
1118 if (c->host_port == 0) {
1119 nextstate = SSH_CHANNEL_DYNAMIC;
1120 rtype = "dynamic-tcpip";
1122 nextstate = SSH_CHANNEL_OPENING;
1123 rtype = "direct-tcpip";
1127 addrlen = sizeof(addr);
1128 newsock = accept(c->sock, &addr, &addrlen);
1130 error("accept: %.100s", strerror(errno));
1133 set_nodelay(newsock);
1134 nc = channel_new(rtype,
1135 nextstate, newsock, newsock, -1,
1136 c->local_window_max, c->local_maxpacket,
1137 0, xstrdup(rtype), 1);
1138 nc->listening_port = c->listening_port;
1139 nc->host_port = c->host_port;
1140 strlcpy(nc->path, c->path, sizeof(nc->path));
1142 if (nextstate == SSH_CHANNEL_DYNAMIC) {
1144 * do not call the channel_post handler until
1145 * this flag has been reset by a pre-handler.
1146 * otherwise the FD_ISSET calls might overflow
1150 port_open_helper(nc, rtype);
1156 * This is the authentication agent socket listening for connections from
1160 channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
1165 struct sockaddr addr;
1168 if (FD_ISSET(c->sock, readset)) {
1169 addrlen = sizeof(addr);
1170 newsock = accept(c->sock, &addr, &addrlen);
1172 error("accept from auth socket: %.100s", strerror(errno));
1175 name = xstrdup("accepted auth socket");
1176 nc = channel_new("accepted auth socket",
1177 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1178 c->local_window_max, c->local_maxpacket,
1181 packet_start(SSH2_MSG_CHANNEL_OPEN);
1182 packet_put_cstring("auth-agent@openssh.com");
1183 packet_put_int(nc->self);
1184 packet_put_int(c->local_window_max);
1185 packet_put_int(c->local_maxpacket);
1187 packet_start(SSH_SMSG_AGENT_OPEN);
1188 packet_put_int(nc->self);
1195 channel_post_connecting(Channel *c, fd_set * readset, fd_set * writeset)
1198 socklen_t sz = sizeof(err);
1200 if (FD_ISSET(c->sock, writeset)) {
1201 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1203 error("getsockopt SO_ERROR failed");
1206 debug("channel %d: connected", c->self);
1207 c->type = SSH_CHANNEL_OPEN;
1209 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1210 packet_put_int(c->remote_id);
1211 packet_put_int(c->self);
1212 packet_put_int(c->local_window);
1213 packet_put_int(c->local_maxpacket);
1215 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1216 packet_put_int(c->remote_id);
1217 packet_put_int(c->self);
1220 debug("channel %d: not connected: %s",
1221 c->self, strerror(err));
1223 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1224 packet_put_int(c->remote_id);
1225 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1226 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1227 packet_put_cstring(strerror(err));
1228 packet_put_cstring("");
1231 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1232 packet_put_int(c->remote_id);
1241 channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
1247 FD_ISSET(c->rfd, readset)) {
1248 len = read(c->rfd, buf, sizeof(buf));
1249 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1252 debug("channel %d: read<=0 rfd %d len %d",
1253 c->self, c->rfd, len);
1254 if (c->type != SSH_CHANNEL_OPEN) {
1255 debug("channel %d: not open", c->self);
1258 } else if (compat13) {
1259 buffer_clear(&c->output);
1260 c->type = SSH_CHANNEL_INPUT_DRAINING;
1261 debug("channel %d: input draining.", c->self);
1263 chan_read_failed(c);
1267 if (c->input_filter != NULL) {
1268 if (c->input_filter(c, buf, len) == -1) {
1269 debug("channel %d: filter stops", c->self);
1270 chan_read_failed(c);
1273 buffer_append(&c->input, buf, len);
1279 channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
1286 /* Send buffered output data to the socket. */
1288 FD_ISSET(c->wfd, writeset) &&
1289 buffer_len(&c->output) > 0) {
1290 data = buffer_ptr(&c->output);
1291 dlen = buffer_len(&c->output);
1293 /* XXX: Later AIX versions can't push as much data to tty */
1294 if (compat20 && c->wfd_isatty && dlen > 8*1024)
1297 len = write(c->wfd, data, dlen);
1298 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1301 if (c->type != SSH_CHANNEL_OPEN) {
1302 debug("channel %d: not open", c->self);
1305 } else if (compat13) {
1306 buffer_clear(&c->output);
1307 debug("channel %d: input draining.", c->self);
1308 c->type = SSH_CHANNEL_INPUT_DRAINING;
1310 chan_write_failed(c);
1314 if (compat20 && c->isatty && dlen >= 1 && data[0] != '\r') {
1315 if (tcgetattr(c->wfd, &tio) == 0 &&
1316 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1318 * Simulate echo to reduce the impact of
1319 * traffic analysis. We need to match the
1320 * size of a SSH2_MSG_CHANNEL_DATA message
1321 * (4 byte channel id + data)
1323 packet_send_ignore(4 + len);
1327 buffer_consume(&c->output, len);
1328 if (compat20 && len > 0) {
1329 c->local_consumed += len;
1335 channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
1340 /** XXX handle drain efd, too */
1342 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1343 FD_ISSET(c->efd, writeset) &&
1344 buffer_len(&c->extended) > 0) {
1345 len = write(c->efd, buffer_ptr(&c->extended),
1346 buffer_len(&c->extended));
1347 debug2("channel %d: written %d to efd %d",
1348 c->self, len, c->efd);
1349 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1352 debug2("channel %d: closing write-efd %d",
1354 channel_close_fd(&c->efd);
1356 buffer_consume(&c->extended, len);
1357 c->local_consumed += len;
1359 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
1360 FD_ISSET(c->efd, readset)) {
1361 len = read(c->efd, buf, sizeof(buf));
1362 debug2("channel %d: read %d from efd %d",
1363 c->self, len, c->efd);
1364 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1367 debug2("channel %d: closing read-efd %d",
1369 channel_close_fd(&c->efd);
1371 buffer_append(&c->extended, buf, len);
1378 channel_check_window(Channel *c)
1380 if (c->type == SSH_CHANNEL_OPEN &&
1381 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1382 c->local_window < c->local_window_max/2 &&
1383 c->local_consumed > 0) {
1384 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1385 packet_put_int(c->remote_id);
1386 packet_put_int(c->local_consumed);
1388 debug2("channel %d: window %d sent adjust %d",
1389 c->self, c->local_window,
1391 c->local_window += c->local_consumed;
1392 c->local_consumed = 0;
1398 channel_post_open(Channel *c, fd_set * readset, fd_set * writeset)
1402 channel_handle_rfd(c, readset, writeset);
1403 channel_handle_wfd(c, readset, writeset);
1406 channel_handle_efd(c, readset, writeset);
1407 channel_check_window(c);
1411 channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
1415 /* Send buffered output data to the socket. */
1416 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1417 len = write(c->sock, buffer_ptr(&c->output),
1418 buffer_len(&c->output));
1420 buffer_clear(&c->output);
1422 buffer_consume(&c->output, len);
1427 channel_handler_init_20(void)
1429 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1430 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1431 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1432 channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
1433 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1434 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1435 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1436 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1438 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1439 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1440 channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
1441 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1442 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1443 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1444 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1448 channel_handler_init_13(void)
1450 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
1451 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
1452 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1453 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1454 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1455 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
1456 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
1457 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1458 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1460 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1461 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1462 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1463 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1464 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
1465 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1466 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1470 channel_handler_init_15(void)
1472 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1473 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1474 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1475 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1476 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1477 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1478 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1480 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1481 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1482 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1483 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1484 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1485 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1489 channel_handler_init(void)
1493 for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1494 channel_pre[i] = NULL;
1495 channel_post[i] = NULL;
1498 channel_handler_init_20();
1500 channel_handler_init_13();
1502 channel_handler_init_15();
1505 /* gc dead channels */
1507 channel_garbage_collect(Channel *c)
1511 if (c->detach_user != NULL) {
1512 if (!chan_is_dead(c, 0))
1514 debug("channel %d: gc: notify user", c->self);
1515 c->detach_user(c->self, NULL);
1516 /* if we still have a callback */
1517 if (c->detach_user != NULL)
1519 debug("channel %d: gc: user detached", c->self);
1521 if (!chan_is_dead(c, 1))
1523 debug("channel %d: garbage collecting", c->self);
1528 channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
1530 static int did_init = 0;
1535 channel_handler_init();
1538 for (i = 0; i < channels_alloc; i++) {
1542 if (ftab[c->type] != NULL)
1543 (*ftab[c->type])(c, readset, writeset);
1544 channel_garbage_collect(c);
1549 * Allocate/update select bitmasks and add any bits relevant to channels in
1553 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1554 int *nallocp, int rekeying)
1559 n = MAX(*maxfdp, channel_max_fd);
1561 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1562 /* perhaps check sz < nalloc/2 and shrink? */
1563 if (*readsetp == NULL || sz > *nallocp) {
1564 *readsetp = xrealloc(*readsetp, sz);
1565 *writesetp = xrealloc(*writesetp, sz);
1569 memset(*readsetp, 0, sz);
1570 memset(*writesetp, 0, sz);
1573 channel_handler(channel_pre, *readsetp, *writesetp);
1577 * After select, perform any appropriate operations for channels which have
1581 channel_after_select(fd_set * readset, fd_set * writeset)
1583 channel_handler(channel_post, readset, writeset);
1587 /* If there is data to send to the connection, enqueue some of it now. */
1590 channel_output_poll(void)
1596 for (i = 0; i < channels_alloc; i++) {
1602 * We are only interested in channels that can have buffered
1606 if (c->type != SSH_CHANNEL_OPEN &&
1607 c->type != SSH_CHANNEL_INPUT_DRAINING)
1610 if (c->type != SSH_CHANNEL_OPEN)
1614 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1615 /* XXX is this true? */
1616 debug3("channel %d: will not send data after close", c->self);
1620 /* Get the amount of buffered data for this channel. */
1621 if ((c->istate == CHAN_INPUT_OPEN ||
1622 c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1623 (len = buffer_len(&c->input)) > 0) {
1625 * Send some data for the other side over the secure
1629 if (len > c->remote_window)
1630 len = c->remote_window;
1631 if (len > c->remote_maxpacket)
1632 len = c->remote_maxpacket;
1634 if (packet_is_interactive()) {
1638 /* Keep the packets at reasonable size. */
1639 if (len > packet_get_maxsize()/2)
1640 len = packet_get_maxsize()/2;
1644 packet_start(compat20 ?
1645 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1646 packet_put_int(c->remote_id);
1647 packet_put_string(buffer_ptr(&c->input), len);
1649 buffer_consume(&c->input, len);
1650 c->remote_window -= len;
1652 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1654 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1656 * input-buffer is empty and read-socket shutdown:
1657 * tell peer, that we will not send more data: send IEOF.
1658 * hack for extended data: delay EOF if EFD still in use.
1660 if (CHANNEL_EFD_INPUT_ACTIVE(c))
1661 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
1662 c->self, c->efd, buffer_len(&c->extended));
1666 /* Send extended data, i.e. stderr */
1668 !(c->flags & CHAN_EOF_SENT) &&
1669 c->remote_window > 0 &&
1670 (len = buffer_len(&c->extended)) > 0 &&
1671 c->extended_usage == CHAN_EXTENDED_READ) {
1672 debug2("channel %d: rwin %u elen %u euse %d",
1673 c->self, c->remote_window, buffer_len(&c->extended),
1675 if (len > c->remote_window)
1676 len = c->remote_window;
1677 if (len > c->remote_maxpacket)
1678 len = c->remote_maxpacket;
1679 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
1680 packet_put_int(c->remote_id);
1681 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
1682 packet_put_string(buffer_ptr(&c->extended), len);
1684 buffer_consume(&c->extended, len);
1685 c->remote_window -= len;
1686 debug2("channel %d: sent ext data %d", c->self, len);
1692 /* -- protocol input */
1695 channel_input_data(int type, u_int32_t seq, void *ctxt)
1702 /* Get the channel number and verify it. */
1703 id = packet_get_int();
1704 c = channel_lookup(id);
1706 packet_disconnect("Received data for nonexistent channel %d.", id);
1708 /* Ignore any data for non-open channels (might happen on close) */
1709 if (c->type != SSH_CHANNEL_OPEN &&
1710 c->type != SSH_CHANNEL_X11_OPEN)
1713 /* same for protocol 1.5 if output end is no longer open */
1714 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
1718 data = packet_get_string(&data_len);
1721 if (data_len > c->local_maxpacket) {
1722 log("channel %d: rcvd big packet %d, maxpack %d",
1723 c->self, data_len, c->local_maxpacket);
1725 if (data_len > c->local_window) {
1726 log("channel %d: rcvd too much data %d, win %d",
1727 c->self, data_len, c->local_window);
1731 c->local_window -= data_len;
1734 buffer_append(&c->output, data, data_len);
1739 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
1743 u_int data_len, tcode;
1746 /* Get the channel number and verify it. */
1747 id = packet_get_int();
1748 c = channel_lookup(id);
1751 packet_disconnect("Received extended_data for bad channel %d.", id);
1752 if (c->type != SSH_CHANNEL_OPEN) {
1753 log("channel %d: ext data for non open", id);
1756 if (c->flags & CHAN_EOF_RCVD) {
1757 if (datafellows & SSH_BUG_EXTEOF)
1758 debug("channel %d: accepting ext data after eof", id);
1760 packet_disconnect("Received extended_data after EOF "
1761 "on channel %d.", id);
1763 tcode = packet_get_int();
1765 c->extended_usage != CHAN_EXTENDED_WRITE ||
1766 tcode != SSH2_EXTENDED_DATA_STDERR) {
1767 log("channel %d: bad ext data", c->self);
1770 data = packet_get_string(&data_len);
1772 if (data_len > c->local_window) {
1773 log("channel %d: rcvd too much extended_data %d, win %d",
1774 c->self, data_len, c->local_window);
1778 debug2("channel %d: rcvd ext data %d", c->self, data_len);
1779 c->local_window -= data_len;
1780 buffer_append(&c->extended, data, data_len);
1785 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
1790 id = packet_get_int();
1792 c = channel_lookup(id);
1794 packet_disconnect("Received ieof for nonexistent channel %d.", id);
1797 /* XXX force input close */
1798 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
1799 debug("channel %d: FORCE input drain", c->self);
1800 c->istate = CHAN_INPUT_WAIT_DRAIN;
1801 if (buffer_len(&c->input) == 0)
1808 channel_input_close(int type, u_int32_t seq, void *ctxt)
1813 id = packet_get_int();
1815 c = channel_lookup(id);
1817 packet_disconnect("Received close for nonexistent channel %d.", id);
1820 * Send a confirmation that we have closed the channel and no more
1821 * data is coming for it.
1823 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1824 packet_put_int(c->remote_id);
1828 * If the channel is in closed state, we have sent a close request,
1829 * and the other side will eventually respond with a confirmation.
1830 * Thus, we cannot free the channel here, because then there would be
1831 * no-one to receive the confirmation. The channel gets freed when
1832 * the confirmation arrives.
1834 if (c->type != SSH_CHANNEL_CLOSED) {
1836 * Not a closed channel - mark it as draining, which will
1837 * cause it to be freed later.
1839 buffer_clear(&c->input);
1840 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1844 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1846 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
1848 int id = packet_get_int();
1849 Channel *c = channel_lookup(id);
1853 packet_disconnect("Received oclose for nonexistent channel %d.", id);
1854 chan_rcvd_oclose(c);
1858 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
1860 int id = packet_get_int();
1861 Channel *c = channel_lookup(id);
1865 packet_disconnect("Received close confirmation for "
1866 "out-of-range channel %d.", id);
1867 if (c->type != SSH_CHANNEL_CLOSED)
1868 packet_disconnect("Received close confirmation for "
1869 "non-closed channel %d (type %d).", id, c->type);
1874 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
1879 id = packet_get_int();
1880 c = channel_lookup(id);
1882 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1883 packet_disconnect("Received open confirmation for "
1884 "non-opening channel %d.", id);
1885 remote_id = packet_get_int();
1886 /* Record the remote channel number and mark that the channel is now open. */
1887 c->remote_id = remote_id;
1888 c->type = SSH_CHANNEL_OPEN;
1891 c->remote_window = packet_get_int();
1892 c->remote_maxpacket = packet_get_int();
1894 debug2("callback start");
1895 c->confirm(c->self, NULL);
1896 debug2("callback done");
1898 debug("channel %d: open confirm rwindow %u rmax %u", c->self,
1899 c->remote_window, c->remote_maxpacket);
1905 reason2txt(int reason)
1908 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
1909 return "administratively prohibited";
1910 case SSH2_OPEN_CONNECT_FAILED:
1911 return "connect failed";
1912 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
1913 return "unknown channel type";
1914 case SSH2_OPEN_RESOURCE_SHORTAGE:
1915 return "resource shortage";
1917 return "unknown reason";
1921 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
1924 char *msg = NULL, *lang = NULL;
1927 id = packet_get_int();
1928 c = channel_lookup(id);
1930 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1931 packet_disconnect("Received open failure for "
1932 "non-opening channel %d.", id);
1934 reason = packet_get_int();
1935 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1936 msg = packet_get_string(NULL);
1937 lang = packet_get_string(NULL);
1939 log("channel %d: open failed: %s%s%s", id,
1940 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
1947 /* Free the channel. This will also close the socket. */
1952 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
1961 /* Get the channel number and verify it. */
1962 id = packet_get_int();
1963 c = channel_lookup(id);
1965 if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
1966 log("Received window adjust for "
1967 "non-open channel %d.", id);
1970 adjust = packet_get_int();
1972 debug2("channel %d: rcvd adjust %u", id, adjust);
1973 c->remote_window += adjust;
1977 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
1981 char *host, *originator_string;
1982 int remote_id, sock = -1;
1984 remote_id = packet_get_int();
1985 host = packet_get_string(NULL);
1986 host_port = packet_get_int();
1988 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
1989 originator_string = packet_get_string(NULL);
1991 originator_string = xstrdup("unknown (remote did not supply name)");
1994 sock = channel_connect_to(host, host_port);
1996 c = channel_new("connected socket",
1997 SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
1998 originator_string, 1);
1999 c->remote_id = remote_id;
2002 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2003 packet_put_int(remote_id);
2010 /* -- tcp forwarding */
2013 channel_set_af(int af)
2019 channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port,
2020 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2023 int success, sock, on = 1;
2024 struct addrinfo hints, *ai, *aitop;
2026 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2029 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2030 listen_addr : host_to_connect;
2033 error("No forward host name.");
2036 if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
2037 error("Forward host name too long.");
2042 * getaddrinfo returns a loopback address if the hostname is
2043 * set to NULL and hints.ai_flags is not AI_PASSIVE
2045 memset(&hints, 0, sizeof(hints));
2046 hints.ai_family = IPv4or6;
2047 hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
2048 hints.ai_socktype = SOCK_STREAM;
2049 snprintf(strport, sizeof strport, "%d", listen_port);
2050 if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
2051 packet_disconnect("getaddrinfo: fatal error");
2053 for (ai = aitop; ai; ai = ai->ai_next) {
2054 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2056 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2057 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2058 error("channel_setup_fwd_listener: getnameinfo failed");
2061 /* Create a port to listen for the host. */
2062 sock = socket(ai->ai_family, SOCK_STREAM, 0);
2064 /* this is no error since kernel may not support ipv6 */
2065 verbose("socket: %.100s", strerror(errno));
2069 * Set socket options.
2070 * Allow local port reuse in TIME_WAIT.
2072 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on,
2074 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
2076 debug("Local forwarding listening on %s port %s.", ntop, strport);
2078 /* Bind the socket to the address. */
2079 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2080 /* address can be in use ipv6 address is already bound */
2082 error("bind: %.100s", strerror(errno));
2084 verbose("bind: %.100s", strerror(errno));
2089 /* Start listening for connections on the socket. */
2090 if (listen(sock, 5) < 0) {
2091 error("listen: %.100s", strerror(errno));
2095 /* Allocate a channel number for the socket. */
2096 c = channel_new("port listener", type, sock, sock, -1,
2097 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2098 0, xstrdup("port listener"), 1);
2099 strlcpy(c->path, host, sizeof(c->path));
2100 c->host_port = port_to_connect;
2101 c->listening_port = listen_port;
2105 error("channel_setup_fwd_listener: cannot listen to port: %d",
2107 freeaddrinfo(aitop);
2111 /* protocol local port fwd, used by ssh (and sshd in v1) */
2113 channel_setup_local_fwd_listener(u_short listen_port,
2114 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2116 return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
2117 NULL, listen_port, host_to_connect, port_to_connect, gateway_ports);
2120 /* protocol v2 remote port fwd, used by sshd */
2122 channel_setup_remote_fwd_listener(const char *listen_address,
2123 u_short listen_port, int gateway_ports)
2125 return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
2126 listen_address, listen_port, NULL, 0, gateway_ports);
2130 * Initiate forwarding of connections to port "port" on remote host through
2131 * the secure channel to host:port from local side.
2135 channel_request_remote_forwarding(u_short listen_port,
2136 const char *host_to_connect, u_short port_to_connect)
2138 int type, success = 0;
2140 /* Record locally that connection to this host/port is permitted. */
2141 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2142 fatal("channel_request_remote_forwarding: too many forwards");
2144 /* Send the forward request to the remote side. */
2146 const char *address_to_bind = "0.0.0.0";
2147 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2148 packet_put_cstring("tcpip-forward");
2149 packet_put_char(1); /* boolean: want reply */
2150 packet_put_cstring(address_to_bind);
2151 packet_put_int(listen_port);
2153 packet_write_wait();
2154 /* Assume that server accepts the request */
2157 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
2158 packet_put_int(listen_port);
2159 packet_put_cstring(host_to_connect);
2160 packet_put_int(port_to_connect);
2162 packet_write_wait();
2164 /* Wait for response from the remote side. */
2165 type = packet_read();
2167 case SSH_SMSG_SUCCESS:
2170 case SSH_SMSG_FAILURE:
2171 log("Warning: Server denied remote port forwarding.");
2174 /* Unknown packet */
2175 packet_disconnect("Protocol error for port forward request:"
2176 "received packet type %d.", type);
2180 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
2181 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
2182 permitted_opens[num_permitted_opens].listen_port = listen_port;
2183 num_permitted_opens++;
2188 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
2189 * listening for the port, and sends back a success reply (or disconnect
2190 * message if there was an error). This never returns if there was an error.
2194 channel_input_port_forward_request(int is_root, int gateway_ports)
2196 u_short port, host_port;
2199 /* Get arguments from the packet. */
2200 port = packet_get_int();
2201 hostname = packet_get_string(NULL);
2202 host_port = packet_get_int();
2206 * Check that an unprivileged user is not trying to forward a
2209 if (port < IPPORT_RESERVED && !is_root)
2210 packet_disconnect("Requested forwarding of port %d but user is not root.",
2213 /* Initiate forwarding */
2214 channel_setup_local_fwd_listener(port, hostname, host_port, gateway_ports);
2216 /* Free the argument string. */
2221 * Permits opening to any host/port if permitted_opens[] is empty. This is
2222 * usually called by the server, because the user could connect to any port
2223 * anyway, and the server has no way to know but to trust the client anyway.
2226 channel_permit_all_opens(void)
2228 if (num_permitted_opens == 0)
2229 all_opens_permitted = 1;
2233 channel_add_permitted_opens(char *host, int port)
2235 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2236 fatal("channel_request_remote_forwarding: too many forwards");
2237 debug("allow port forwarding to host %s port %d", host, port);
2239 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
2240 permitted_opens[num_permitted_opens].port_to_connect = port;
2241 num_permitted_opens++;
2243 all_opens_permitted = 0;
2247 channel_clear_permitted_opens(void)
2251 for (i = 0; i < num_permitted_opens; i++)
2252 xfree(permitted_opens[i].host_to_connect);
2253 num_permitted_opens = 0;
2258 /* return socket to remote host, port */
2260 connect_to(const char *host, u_short port)
2262 struct addrinfo hints, *ai, *aitop;
2263 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2267 memset(&hints, 0, sizeof(hints));
2268 hints.ai_family = IPv4or6;
2269 hints.ai_socktype = SOCK_STREAM;
2270 snprintf(strport, sizeof strport, "%d", port);
2271 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
2272 error("connect_to %.100s: unknown host (%s)", host,
2273 gai_strerror(gaierr));
2276 for (ai = aitop; ai; ai = ai->ai_next) {
2277 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2279 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2280 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2281 error("connect_to: getnameinfo failed");
2284 sock = socket(ai->ai_family, SOCK_STREAM, 0);
2286 error("socket: %.100s", strerror(errno));
2289 if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0)
2290 fatal("connect_to: F_SETFL: %s", strerror(errno));
2291 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
2292 errno != EINPROGRESS) {
2293 error("connect_to %.100s port %s: %.100s", ntop, strport,
2296 continue; /* fail -- try next */
2298 break; /* success */
2301 freeaddrinfo(aitop);
2303 error("connect_to %.100s port %d: failed.", host, port);
2312 channel_connect_by_listen_address(u_short listen_port)
2316 for (i = 0; i < num_permitted_opens; i++)
2317 if (permitted_opens[i].listen_port == listen_port)
2319 permitted_opens[i].host_to_connect,
2320 permitted_opens[i].port_to_connect);
2321 error("WARNING: Server requests forwarding for unknown listen_port %d",
2326 /* Check if connecting to that port is permitted and connect. */
2328 channel_connect_to(const char *host, u_short port)
2332 permit = all_opens_permitted;
2334 for (i = 0; i < num_permitted_opens; i++)
2335 if (permitted_opens[i].port_to_connect == port &&
2336 strcmp(permitted_opens[i].host_to_connect, host) == 0)
2341 log("Received request to connect to host %.100s port %d, "
2342 "but the request was denied.", host, port);
2345 return connect_to(host, port);
2348 /* -- X11 forwarding */
2351 * Creates an internet domain socket for listening for X11 connections.
2352 * Returns 0 and a suitable display number for the DISPLAY variable
2353 * stored in display_numberp , or -1 if an error occurs.
2356 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
2357 int single_connection, u_int *display_numberp)
2360 int display_number, sock;
2362 struct addrinfo hints, *ai, *aitop;
2363 char strport[NI_MAXSERV];
2364 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
2366 for (display_number = x11_display_offset;
2367 display_number < MAX_DISPLAYS;
2369 port = 6000 + display_number;
2370 memset(&hints, 0, sizeof(hints));
2371 hints.ai_family = IPv4or6;
2372 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
2373 hints.ai_socktype = SOCK_STREAM;
2374 snprintf(strport, sizeof strport, "%d", port);
2375 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
2376 error("getaddrinfo: %.100s", gai_strerror(gaierr));
2379 for (ai = aitop; ai; ai = ai->ai_next) {
2380 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2382 sock = socket(ai->ai_family, SOCK_STREAM, 0);
2384 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) {
2385 error("socket: %.100s", strerror(errno));
2388 debug("x11_create_display_inet: Socket family %d not supported",
2394 if (ai->ai_family == AF_INET6) {
2396 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0)
2397 error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno));
2400 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2401 debug("bind port %d: %.100s", port, strerror(errno));
2407 for (n = 0; n < num_socks; n++) {
2413 socks[num_socks++] = sock;
2414 #ifndef DONT_TRY_OTHER_AF
2415 if (num_socks == NUM_SOCKS)
2418 if (x11_use_localhost) {
2419 if (num_socks == NUM_SOCKS)
2426 freeaddrinfo(aitop);
2430 if (display_number >= MAX_DISPLAYS) {
2431 error("Failed to allocate internet-domain X11 display socket.");
2434 /* Start listening for connections on the socket. */
2435 for (n = 0; n < num_socks; n++) {
2437 if (listen(sock, 5) < 0) {
2438 error("listen: %.100s", strerror(errno));
2444 /* Allocate a channel for each socket. */
2445 for (n = 0; n < num_socks; n++) {
2447 nc = channel_new("x11 listener",
2448 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
2449 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2450 0, xstrdup("X11 inet listener"), 1);
2451 nc->single_connection = single_connection;
2454 /* Return the display number for the DISPLAY environment variable. */
2455 *display_numberp = display_number;
2460 connect_local_xsocket(u_int dnr)
2463 struct sockaddr_un addr;
2465 sock = socket(AF_UNIX, SOCK_STREAM, 0);
2467 error("socket: %.100s", strerror(errno));
2468 memset(&addr, 0, sizeof(addr));
2469 addr.sun_family = AF_UNIX;
2470 snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
2471 if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
2474 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
2479 x11_connect_display(void)
2481 int display_number, sock = 0;
2482 const char *display;
2483 char buf[1024], *cp;
2484 struct addrinfo hints, *ai, *aitop;
2485 char strport[NI_MAXSERV];
2488 /* Try to open a socket for the local X server. */
2489 display = getenv("DISPLAY");
2491 error("DISPLAY not set.");
2495 * Now we decode the value of the DISPLAY variable and make a
2496 * connection to the real X server.
2500 * Check if it is a unix domain socket. Unix domain displays are in
2501 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
2503 if (strncmp(display, "unix:", 5) == 0 ||
2504 display[0] == ':') {
2505 /* Connect to the unix domain socket. */
2506 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
2507 error("Could not parse display number from DISPLAY: %.100s",
2511 /* Create a socket. */
2512 sock = connect_local_xsocket(display_number);
2516 /* OK, we now have a connection to the display. */
2520 * Connect to an inet socket. The DISPLAY value is supposedly
2521 * hostname:d[.s], where hostname may also be numeric IP address.
2523 strlcpy(buf, display, sizeof(buf));
2524 cp = strchr(buf, ':');
2526 error("Could not find ':' in DISPLAY: %.100s", display);
2530 /* buf now contains the host name. But first we parse the display number. */
2531 if (sscanf(cp + 1, "%d", &display_number) != 1) {
2532 error("Could not parse display number from DISPLAY: %.100s",
2537 /* Look up the host address */
2538 memset(&hints, 0, sizeof(hints));
2539 hints.ai_family = IPv4or6;
2540 hints.ai_socktype = SOCK_STREAM;
2541 snprintf(strport, sizeof strport, "%d", 6000 + display_number);
2542 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
2543 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
2546 for (ai = aitop; ai; ai = ai->ai_next) {
2547 /* Create a socket. */
2548 sock = socket(ai->ai_family, SOCK_STREAM, 0);
2550 debug("socket: %.100s", strerror(errno));
2553 /* Connect it to the display. */
2554 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2555 debug("connect %.100s port %d: %.100s", buf,
2556 6000 + display_number, strerror(errno));
2563 freeaddrinfo(aitop);
2565 error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
2574 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
2575 * the remote channel number. We should do whatever we want, and respond
2576 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
2580 x11_input_open(int type, u_int32_t seq, void *ctxt)
2583 int remote_id, sock = 0;
2586 debug("Received X11 open request.");
2588 remote_id = packet_get_int();
2590 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2591 remote_host = packet_get_string(NULL);
2593 remote_host = xstrdup("unknown (remote did not supply name)");
2597 /* Obtain a connection to the real X display. */
2598 sock = x11_connect_display();
2600 /* Allocate a channel for this connection. */
2601 c = channel_new("connected x11 socket",
2602 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
2604 c->remote_id = remote_id;
2608 /* Send refusal to the remote host. */
2609 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2610 packet_put_int(remote_id);
2612 /* Send a confirmation to the remote host. */
2613 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2614 packet_put_int(remote_id);
2615 packet_put_int(c->self);
2620 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
2622 deny_input_open(int type, u_int32_t seq, void *ctxt)
2624 int rchan = packet_get_int();
2627 case SSH_SMSG_AGENT_OPEN:
2628 error("Warning: ssh server tried agent forwarding.");
2630 case SSH_SMSG_X11_OPEN:
2631 error("Warning: ssh server tried X11 forwarding.");
2634 error("deny_input_open: type %d", type);
2637 error("Warning: this is probably a break in attempt by a malicious server.");
2638 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2639 packet_put_int(rchan);
2644 * Requests forwarding of X11 connections, generates fake authentication
2645 * data, and enables authentication spoofing.
2646 * This should be called in the client only.
2649 x11_request_forwarding_with_spoofing(int client_session_id,
2650 const char *proto, const char *data)
2652 u_int data_len = (u_int) strlen(data) / 2;
2653 u_int i, value, len;
2659 cp = getenv("DISPLAY");
2661 cp = strchr(cp, ':');
2663 cp = strchr(cp, '.');
2665 screen_number = atoi(cp + 1);
2669 /* Save protocol name. */
2670 x11_saved_proto = xstrdup(proto);
2673 * Extract real authentication data and generate fake data of the
2676 x11_saved_data = xmalloc(data_len);
2677 x11_fake_data = xmalloc(data_len);
2678 for (i = 0; i < data_len; i++) {
2679 if (sscanf(data + 2 * i, "%2x", &value) != 1)
2680 fatal("x11_request_forwarding: bad authentication data: %.100s", data);
2682 rand = arc4random();
2683 x11_saved_data[i] = value;
2684 x11_fake_data[i] = rand & 0xff;
2687 x11_saved_data_len = data_len;
2688 x11_fake_data_len = data_len;
2690 /* Convert the fake data into hex. */
2691 len = 2 * data_len + 1;
2692 new_data = xmalloc(len);
2693 for (i = 0; i < data_len; i++)
2694 snprintf(new_data + 2 * i, len - 2 * i,
2695 "%02x", (u_char) x11_fake_data[i]);
2697 /* Send the request packet. */
2699 channel_request_start(client_session_id, "x11-req", 0);
2700 packet_put_char(0); /* XXX bool single connection */
2702 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
2704 packet_put_cstring(proto);
2705 packet_put_cstring(new_data);
2706 packet_put_int(screen_number);
2708 packet_write_wait();
2713 /* -- agent forwarding */
2715 /* Sends a message to the server to request authentication fd forwarding. */
2718 auth_request_forwarding(void)
2720 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
2722 packet_write_wait();
2725 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
2728 auth_input_open_request(int type, u_int32_t seq, void *ctxt)
2731 int remote_id, sock;
2734 /* Read the remote channel number from the message. */
2735 remote_id = packet_get_int();
2739 * Get a connection to the local authentication agent (this may again
2742 sock = ssh_get_authentication_socket();
2745 * If we could not connect the agent, send an error message back to
2746 * the server. This should never happen unless the agent dies,
2747 * because authentication forwarding is only enabled if we have an
2751 name = xstrdup("authentication agent connection");
2752 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
2753 -1, 0, 0, 0, name, 1);
2754 c->remote_id = remote_id;
2758 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2759 packet_put_int(remote_id);
2761 /* Send a confirmation to the remote host. */
2762 debug("Forwarding authentication connection.");
2763 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2764 packet_put_int(remote_id);
2765 packet_put_int(c->self);