5 * Author: Tatu Ylonen <ylo@cs.hut.fi>
7 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
10 * Created: Fri Mar 24 16:35:24 1995 ylo
12 * This file contains functions for generic socket connection forwarding.
13 * There is also code for initiating connection forwarding for X11 connections,
14 * arbitrary tcp/ip connections, and the authentication agent connection.
16 * SSH2 support added by Markus Friedl.
37 /* Maximum number of fake X11 displays to try. */
38 #define MAX_DISPLAYS 1000
40 /* Max len of agent socket */
41 #define MAX_SOCKET_NAME 100
43 /* default buffer for tcp-fwd-channel */
44 #define CHAN_WINDOW_DEFAULT (8*1024)
45 #define CHAN_PACKET_DEFAULT (CHAN_WINDOW_DEFAULT/2)
48 * Pointer to an array containing all allocated channels. The array is
49 * dynamically extended as needed.
51 static Channel *channels = NULL;
54 * Size of the channel array. All slots of the array must always be
55 * initialized (at least the type field); unused slots are marked with type
58 static int channels_alloc = 0;
61 * Maximum file descriptor value used in any of the channels. This is
62 * updated in channel_allocate.
64 static int channel_max_fd_value = 0;
66 /* Name and directory of socket for authentication agent forwarding. */
67 static char *channel_forwarded_auth_socket_name = NULL;
68 static char *channel_forwarded_auth_socket_dir = NULL;
70 /* Saved X11 authentication protocol name. */
71 char *x11_saved_proto = NULL;
73 /* Saved X11 authentication data. This is the real data. */
74 char *x11_saved_data = NULL;
75 unsigned int x11_saved_data_len = 0;
78 * Fake X11 authentication data. This is what the server will be sending us;
79 * we should replace any occurrences of this by the real data.
81 char *x11_fake_data = NULL;
82 unsigned int x11_fake_data_len;
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];
98 /* Number of permitted host/port pairs in the array. */
99 static int num_permitted_opens = 0;
101 * If this is true, all opens are permitted. This is the case on the server
102 * on which we have to trust the client anyway, and the user could do
103 * anything after logging in anyway.
105 static int all_opens_permitted = 0;
107 /* This is set to true if both sides support SSH_PROTOFLAG_HOST_IN_FWD_OPEN. */
108 static int have_hostname_in_open = 0;
110 /* Sets specific protocol options. */
113 channel_set_options(int hostname_in_open)
115 have_hostname_in_open = hostname_in_open;
119 * Permits opening to any host/port in SSH_MSG_PORT_OPEN. This is usually
120 * called by the server, because the user could connect to any port anyway,
121 * and the server has no way to know but to trust the client anyway.
125 channel_permit_all_opens()
127 all_opens_permitted = 1;
130 /* lookup channel by id */
133 channel_lookup(int id)
136 if (id < 0 && id > channels_alloc) {
137 log("channel_lookup: %d: bad id", id);
141 if (c->type == SSH_CHANNEL_FREE) {
142 log("channel_lookup: %d: bad id: channel free", id);
149 * Allocate a new channel object and set its type and socket. This will cause
150 * remote_name to be freed.
154 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
155 int window, int maxpack, int extended_usage, char *remote_name)
160 /* Update the maximum file descriptor value. */
161 if (rfd > channel_max_fd_value)
162 channel_max_fd_value = rfd;
163 if (wfd > channel_max_fd_value)
164 channel_max_fd_value = wfd;
165 if (efd > channel_max_fd_value)
166 channel_max_fd_value = efd;
167 /* XXX set close-on-exec -markus */
169 /* Do initial allocation if this is the first call. */
170 if (channels_alloc == 0) {
173 channels = xmalloc(channels_alloc * sizeof(Channel));
174 for (i = 0; i < channels_alloc; i++)
175 channels[i].type = SSH_CHANNEL_FREE;
177 * Kludge: arrange a call to channel_stop_listening if we
178 * terminate with fatal().
180 fatal_add_cleanup((void (*) (void *)) channel_stop_listening, NULL);
182 /* Try to find a free slot where to put the new channel. */
183 for (found = -1, i = 0; i < channels_alloc; i++)
184 if (channels[i].type == SSH_CHANNEL_FREE) {
185 /* Found a free slot. */
190 /* There are no free slots. Take last+1 slot and expand the array. */
191 found = channels_alloc;
192 channels_alloc += 10;
193 debug("channel: expanding %d", channels_alloc);
194 channels = xrealloc(channels, channels_alloc * sizeof(Channel));
195 for (i = found; i < channels_alloc; i++)
196 channels[i].type = SSH_CHANNEL_FREE;
198 /* Initialize and return new channel number. */
199 c = &channels[found];
200 buffer_init(&c->input);
201 buffer_init(&c->output);
202 buffer_init(&c->extended);
203 chan_init_iostates(c);
207 c->local_window = window;
208 c->local_window_max = window;
209 c->local_consumed = 0;
210 c->local_maxpacket = maxpack;
211 c->remote_window = 0;
212 c->remote_maxpacket = 0;
215 c->sock = (rfd == wfd) ? rfd : -1;
217 c->extended_usage = extended_usage;
219 c->remote_name = remote_name;
220 c->remote_window = 0;
221 c->remote_maxpacket = 0;
225 c->dettach_user = NULL;
226 debug("channel %d: new [%s]", found, remote_name);
230 channel_allocate(int type, int sock, char *remote_name)
232 return channel_new("", type, sock, sock, -1, 0, 0, 0, remote_name);
235 /* Free the channel and close its socket. */
240 Channel *c = channel_lookup(id);
242 packet_disconnect("channel free: bad local channel %d", id);
243 debug("channel_free: channel %d: status: %s", id, channel_open_message());
244 if (c->dettach_user != NULL) {
245 debug("channel_free: channel %d: dettaching channel user", id);
246 c->dettach_user(c->self, NULL);
249 shutdown(c->sock, SHUT_RDWR);
267 buffer_free(&c->input);
268 buffer_free(&c->output);
269 buffer_free(&c->extended);
270 c->type = SSH_CHANNEL_FREE;
271 if (c->remote_name) {
272 xfree(c->remote_name);
273 c->remote_name = NULL;
278 * 'channel_pre*' are called just before select() to add any bits relevant to
279 * channels in the select bitmasks.
282 * 'channel_post*': perform any appropriate operations for channels which
283 * have events pending.
285 typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
286 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
287 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
290 channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
292 FD_SET(c->sock, readset);
296 channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
298 if (buffer_len(&c->input) < packet_get_maxsize())
299 FD_SET(c->sock, readset);
300 if (buffer_len(&c->output) > 0)
301 FD_SET(c->sock, writeset);
305 channel_pre_open_15(Channel *c, fd_set * readset, fd_set * writeset)
307 /* test whether sockets are 'alive' for read/write */
308 if (c->istate == CHAN_INPUT_OPEN)
309 if (buffer_len(&c->input) < packet_get_maxsize())
310 FD_SET(c->sock, readset);
311 if (c->ostate == CHAN_OUTPUT_OPEN ||
312 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
313 if (buffer_len(&c->output) > 0) {
314 FD_SET(c->sock, writeset);
315 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
322 channel_pre_open_20(Channel *c, fd_set * readset, fd_set * writeset)
324 if (c->istate == CHAN_INPUT_OPEN &&
325 c->remote_window > 0 &&
326 buffer_len(&c->input) < c->remote_window)
327 FD_SET(c->rfd, readset);
328 if (c->ostate == CHAN_OUTPUT_OPEN ||
329 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
330 if (buffer_len(&c->output) > 0) {
331 FD_SET(c->wfd, writeset);
332 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
336 /** XXX check close conditions, too */
338 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
339 buffer_len(&c->extended) > 0)
340 FD_SET(c->efd, writeset);
341 else if (c->extended_usage == CHAN_EXTENDED_READ &&
342 buffer_len(&c->extended) < c->remote_window)
343 FD_SET(c->efd, readset);
348 channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
350 if (buffer_len(&c->input) == 0) {
351 packet_start(SSH_MSG_CHANNEL_CLOSE);
352 packet_put_int(c->remote_id);
354 c->type = SSH_CHANNEL_CLOSED;
355 debug("Closing channel %d after input drain.", c->self);
360 channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
362 if (buffer_len(&c->output) == 0)
363 channel_free(c->self);
365 FD_SET(c->sock, writeset);
369 * This is a special state for X11 authentication spoofing. An opened X11
370 * connection (when authentication spoofing is being done) remains in this
371 * state until the first packet has been completely read. The authentication
372 * data in that packet is then substituted by the real data if it matches the
373 * fake data, and the channel is put into normal mode.
376 x11_open_helper(Channel *c)
379 unsigned int proto_len, data_len;
381 /* Check if the fixed size part of the packet is in buffer. */
382 if (buffer_len(&c->output) < 12)
385 /* Parse the lengths of variable-length fields. */
386 ucp = (unsigned char *) buffer_ptr(&c->output);
387 if (ucp[0] == 0x42) { /* Byte order MSB first. */
388 proto_len = 256 * ucp[6] + ucp[7];
389 data_len = 256 * ucp[8] + ucp[9];
390 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
391 proto_len = ucp[6] + 256 * ucp[7];
392 data_len = ucp[8] + 256 * ucp[9];
394 debug("Initial X11 packet contains bad byte order byte: 0x%x",
399 /* Check if the whole packet is in buffer. */
400 if (buffer_len(&c->output) <
401 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
404 /* Check if authentication protocol matches. */
405 if (proto_len != strlen(x11_saved_proto) ||
406 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
407 debug("X11 connection uses different authentication protocol.");
410 /* Check if authentication data matches our fake data. */
411 if (data_len != x11_fake_data_len ||
412 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
413 x11_fake_data, x11_fake_data_len) != 0) {
414 debug("X11 auth data does not match fake data.");
417 /* Check fake data length */
418 if (x11_fake_data_len != x11_saved_data_len) {
419 error("X11 fake_data_len %d != saved_data_len %d",
420 x11_fake_data_len, x11_saved_data_len);
424 * Received authentication protocol and data match
425 * our fake data. Substitute the fake data with real
428 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
429 x11_saved_data, x11_saved_data_len);
434 channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
436 int ret = x11_open_helper(c);
438 /* Start normal processing for the channel. */
439 c->type = SSH_CHANNEL_OPEN;
440 channel_pre_open_13(c, readset, writeset);
441 } else if (ret == -1) {
443 * We have received an X11 connection that has bad
444 * authentication information.
446 log("X11 connection rejected because of wrong authentication.\r\n");
447 buffer_clear(&c->input);
448 buffer_clear(&c->output);
451 c->type = SSH_CHANNEL_CLOSED;
452 packet_start(SSH_MSG_CHANNEL_CLOSE);
453 packet_put_int(c->remote_id);
459 channel_pre_x11_open_15(Channel *c, fd_set * readset, fd_set * writeset)
461 int ret = x11_open_helper(c);
463 c->type = SSH_CHANNEL_OPEN;
464 channel_pre_open_15(c, readset, writeset);
465 } else if (ret == -1) {
466 debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
468 chan_write_failed(c);
469 debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
473 /* This is our fake X11 server socket. */
475 channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
477 struct sockaddr addr;
480 char buf[16384], *remote_hostname;
482 if (FD_ISSET(c->sock, readset)) {
483 debug("X11 connection requested.");
484 addrlen = sizeof(addr);
485 newsock = accept(c->sock, &addr, &addrlen);
487 error("accept: %.100s", strerror(errno));
490 remote_hostname = get_remote_hostname(newsock);
491 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
492 remote_hostname, get_peer_port(newsock));
493 xfree(remote_hostname);
494 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
496 packet_start(SSH_SMSG_X11_OPEN);
497 packet_put_int(newch);
498 if (have_hostname_in_open)
499 packet_put_string(buf, strlen(buf));
505 * This socket is listening for connections to a forwarded TCP/IP port.
508 channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
510 struct sockaddr addr;
513 char buf[1024], *remote_hostname;
516 if (FD_ISSET(c->sock, readset)) {
517 debug("Connection to port %d forwarding "
518 "to %.100s port %d requested.",
519 c->listening_port, c->path, c->host_port);
520 addrlen = sizeof(addr);
521 newsock = accept(c->sock, &addr, &addrlen);
523 error("accept: %.100s", strerror(errno));
526 remote_hostname = get_remote_hostname(newsock);
527 remote_port = get_peer_port(newsock);
528 snprintf(buf, sizeof buf,
529 "listen port %d for %.100s port %d, "
530 "connect from %.200s port %d",
531 c->listening_port, c->path, c->host_port,
532 remote_hostname, remote_port);
533 newch = channel_new("direct-tcpip",
534 SSH_CHANNEL_OPENING, newsock, newsock, -1,
535 c->local_window_max, c->local_maxpacket,
538 packet_start(SSH2_MSG_CHANNEL_OPEN);
539 packet_put_cstring("direct-tcpip");
540 packet_put_int(newch);
541 packet_put_int(c->local_window_max);
542 packet_put_int(c->local_maxpacket);
543 /* target host and port */
544 packet_put_string(c->path, strlen(c->path));
545 packet_put_int(c->host_port);
546 /* originator host and port */
547 packet_put_cstring(remote_hostname);
548 packet_put_int(remote_port);
551 packet_start(SSH_MSG_PORT_OPEN);
552 packet_put_int(newch);
553 packet_put_string(c->path, strlen(c->path));
554 packet_put_int(c->host_port);
555 if (have_hostname_in_open) {
556 packet_put_string(buf, strlen(buf));
560 xfree(remote_hostname);
565 * This is the authentication agent socket listening for connections from
569 channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
571 struct sockaddr addr;
575 if (FD_ISSET(c->sock, readset)) {
576 addrlen = sizeof(addr);
577 newsock = accept(c->sock, &addr, &addrlen);
579 error("accept from auth socket: %.100s", strerror(errno));
582 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
583 xstrdup("accepted auth socket"));
584 packet_start(SSH_SMSG_AGENT_OPEN);
585 packet_put_int(newch);
591 channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
597 FD_ISSET(c->rfd, readset)) {
598 len = read(c->rfd, buf, sizeof(buf));
600 debug("channel %d: read<0 rfd %d len %d",
601 c->self, c->rfd, len);
603 buffer_consume(&c->output, buffer_len(&c->output));
604 c->type = SSH_CHANNEL_INPUT_DRAINING;
605 debug("Channel %d status set to input draining.", c->self);
611 buffer_append(&c->input, buf, len);
616 channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
620 /* Send buffered output data to the socket. */
622 FD_ISSET(c->wfd, writeset) &&
623 buffer_len(&c->output) > 0) {
624 len = write(c->wfd, buffer_ptr(&c->output),
625 buffer_len(&c->output));
628 buffer_consume(&c->output, buffer_len(&c->output));
629 debug("Channel %d status set to input draining.", c->self);
630 c->type = SSH_CHANNEL_INPUT_DRAINING;
632 chan_write_failed(c);
636 buffer_consume(&c->output, len);
637 if (compat20 && len > 0) {
638 c->local_consumed += len;
644 channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
649 /** XXX handle drain efd, too */
651 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
652 FD_ISSET(c->efd, writeset) &&
653 buffer_len(&c->extended) > 0) {
654 len = write(c->efd, buffer_ptr(&c->extended),
655 buffer_len(&c->extended));
656 debug("channel %d: written %d to efd %d",
657 c->self, len, c->efd);
659 buffer_consume(&c->extended, len);
660 c->local_consumed += len;
662 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
663 FD_ISSET(c->efd, readset)) {
664 len = read(c->efd, buf, sizeof(buf));
665 debug("channel %d: read %d from efd %d",
666 c->self, len, c->efd);
668 debug("channel %d: closing efd %d",
673 buffer_append(&c->extended, buf, len);
679 channel_check_window(Channel *c, fd_set * readset, fd_set * writeset)
681 if (!(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
682 c->local_window < c->local_window_max/2 &&
683 c->local_consumed > 0) {
684 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
685 packet_put_int(c->remote_id);
686 packet_put_int(c->local_consumed);
688 debug("channel %d: window %d sent adjust %d",
689 c->self, c->local_window,
691 c->local_window += c->local_consumed;
692 c->local_consumed = 0;
698 channel_post_open_1(Channel *c, fd_set * readset, fd_set * writeset)
700 channel_handle_rfd(c, readset, writeset);
701 channel_handle_wfd(c, readset, writeset);
705 channel_post_open_2(Channel *c, fd_set * readset, fd_set * writeset)
707 channel_handle_rfd(c, readset, writeset);
708 channel_handle_wfd(c, readset, writeset);
709 channel_handle_efd(c, readset, writeset);
710 channel_check_window(c, readset, writeset);
714 channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
717 /* Send buffered output data to the socket. */
718 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
719 len = write(c->sock, buffer_ptr(&c->output),
720 buffer_len(&c->output));
722 buffer_consume(&c->output, buffer_len(&c->output));
724 buffer_consume(&c->output, len);
729 channel_handler_init_20(void)
731 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_20;
732 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
734 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open_2;
735 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
739 channel_handler_init_13(void)
741 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
742 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
743 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
744 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
745 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
746 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
747 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
749 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open_1;
750 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
751 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
752 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
753 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
757 channel_handler_init_15(void)
759 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_15;
760 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_15;
761 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
762 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
763 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
765 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
766 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
767 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
768 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open_1;
772 channel_handler_init(void)
775 for(i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
776 channel_pre[i] = NULL;
777 channel_post[i] = NULL;
780 channel_handler_init_20();
782 channel_handler_init_13();
784 channel_handler_init_15();
788 channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
790 static int did_init = 0;
795 channel_handler_init();
798 for (i = 0; i < channels_alloc; i++) {
800 if (c->type == SSH_CHANNEL_FREE)
802 if (ftab[c->type] == NULL)
804 (*ftab[c->type])(c, readset, writeset);
805 chan_delete_if_full_closed(c);
810 channel_prepare_select(fd_set * readset, fd_set * writeset)
812 channel_handler(channel_pre, readset, writeset);
816 channel_after_select(fd_set * readset, fd_set * writeset)
818 channel_handler(channel_post, readset, writeset);
821 /* If there is data to send to the connection, send some of it now. */
824 channel_output_poll()
829 for (i = 0; i < channels_alloc; i++) {
832 /* We are only interested in channels that can have buffered incoming data. */
834 if (c->type != SSH_CHANNEL_OPEN &&
835 c->type != SSH_CHANNEL_INPUT_DRAINING)
838 if (c->type != SSH_CHANNEL_OPEN)
840 if (c->istate != CHAN_INPUT_OPEN &&
841 c->istate != CHAN_INPUT_WAIT_DRAIN)
845 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
846 debug("channel: %d: no data after CLOSE", c->self);
850 /* Get the amount of buffered data for this channel. */
851 len = buffer_len(&c->input);
853 /* Send some data for the other side over the secure connection. */
855 if (len > c->remote_window)
856 len = c->remote_window;
857 if (len > c->remote_maxpacket)
858 len = c->remote_maxpacket;
860 if (packet_is_interactive()) {
864 /* Keep the packets at reasonable size. */
865 if (len > packet_get_maxsize()/2)
866 len = packet_get_maxsize()/2;
870 packet_start(compat20 ?
871 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
872 packet_put_int(c->remote_id);
873 packet_put_string(buffer_ptr(&c->input), len);
875 buffer_consume(&c->input, len);
876 c->remote_window -= len;
877 debug("channel %d: send data len %d", c->self, len);
879 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
881 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
883 * input-buffer is empty and read-socket shutdown:
884 * tell peer, that we will not send more data: send IEOF
888 /* Send extended data, i.e. stderr */
890 c->remote_window > 0 &&
891 (len = buffer_len(&c->extended)) > 0 &&
892 c->extended_usage == CHAN_EXTENDED_READ) {
893 if (len > c->remote_window)
894 len = c->remote_window;
895 if (len > c->remote_maxpacket)
896 len = c->remote_maxpacket;
897 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
898 packet_put_int(c->remote_id);
899 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
900 packet_put_string(buffer_ptr(&c->extended), len);
902 buffer_consume(&c->extended, len);
903 c->remote_window -= len;
909 * This is called when a packet of type CHANNEL_DATA has just been received.
910 * The message type has already been consumed, but channel number and data is
915 channel_input_data(int type, int plen)
919 unsigned int data_len;
922 /* Get the channel number and verify it. */
923 id = packet_get_int();
924 c = channel_lookup(id);
926 packet_disconnect("Received data for nonexistent channel %d.", id);
928 /* Ignore any data for non-open channels (might happen on close) */
929 if (c->type != SSH_CHANNEL_OPEN &&
930 c->type != SSH_CHANNEL_X11_OPEN)
933 /* same for protocol 1.5 if output end is no longer open */
934 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
938 data = packet_get_string(&data_len);
942 if (data_len > c->local_maxpacket) {
943 log("channel %d: rcvd big packet %d, maxpack %d",
944 c->self, data_len, c->local_maxpacket);
946 if (data_len > c->local_window) {
947 log("channel %d: rcvd too much data %d, win %d",
948 c->self, data_len, c->local_window);
952 c->local_window -= data_len;
954 packet_integrity_check(plen, 4 + 4 + data_len, type);
956 buffer_append(&c->output, data, data_len);
960 channel_input_extended_data(int type, int plen)
965 unsigned int data_len;
968 /* Get the channel number and verify it. */
969 id = packet_get_int();
970 c = channel_lookup(id);
973 packet_disconnect("Received extended_data for bad channel %d.", id);
974 if (c->type != SSH_CHANNEL_OPEN) {
975 log("channel %d: ext data for non open", id);
978 tcode = packet_get_int();
980 c->extended_usage != CHAN_EXTENDED_WRITE ||
981 tcode != SSH2_EXTENDED_DATA_STDERR) {
982 log("channel %d: bad ext data", c->self);
985 data = packet_get_string(&data_len);
987 if (data_len > c->local_window) {
988 log("channel %d: rcvd too much extended_data %d, win %d",
989 c->self, data_len, c->local_window);
993 debug("channel %d: rcvd ext data %d", c->self, data_len);
994 c->local_window -= data_len;
995 buffer_append(&c->extended, data, data_len);
1001 * Returns true if no channel has too much buffered data, and false if one or
1002 * more channel is overfull.
1006 channel_not_very_much_buffered_data()
1011 for (i = 0; i < channels_alloc; i++) {
1013 if (c->type == SSH_CHANNEL_OPEN) {
1014 if (!compat20 && buffer_len(&c->input) > packet_get_maxsize()) {
1015 debug("channel %d: big input buffer %d",
1016 c->self, buffer_len(&c->input));
1019 if (buffer_len(&c->output) > packet_get_maxsize()) {
1020 debug("channel %d: big output buffer %d",
1021 c->self, buffer_len(&c->output));
1030 channel_input_ieof(int type, int plen)
1035 packet_integrity_check(plen, 4, type);
1037 id = packet_get_int();
1038 c = channel_lookup(id);
1040 packet_disconnect("Received ieof for nonexistent channel %d.", id);
1045 channel_input_close(int type, int plen)
1050 packet_integrity_check(plen, 4, type);
1052 id = packet_get_int();
1053 c = channel_lookup(id);
1055 packet_disconnect("Received close for nonexistent channel %d.", id);
1058 * Send a confirmation that we have closed the channel and no more
1059 * data is coming for it.
1061 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1062 packet_put_int(c->remote_id);
1066 * If the channel is in closed state, we have sent a close request,
1067 * and the other side will eventually respond with a confirmation.
1068 * Thus, we cannot free the channel here, because then there would be
1069 * no-one to receive the confirmation. The channel gets freed when
1070 * the confirmation arrives.
1072 if (c->type != SSH_CHANNEL_CLOSED) {
1074 * Not a closed channel - mark it as draining, which will
1075 * cause it to be freed later.
1077 buffer_consume(&c->input, buffer_len(&c->input));
1078 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1082 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1084 channel_input_oclose(int type, int plen)
1086 int id = packet_get_int();
1087 Channel *c = channel_lookup(id);
1088 packet_integrity_check(plen, 4, type);
1090 packet_disconnect("Received oclose for nonexistent channel %d.", id);
1091 chan_rcvd_oclose(c);
1095 channel_input_close_confirmation(int type, int plen)
1097 int id = packet_get_int();
1098 Channel *c = channel_lookup(id);
1102 packet_disconnect("Received close confirmation for "
1103 "out-of-range channel %d.", id);
1104 if (c->type != SSH_CHANNEL_CLOSED)
1105 packet_disconnect("Received close confirmation for "
1106 "non-closed channel %d (type %d).", id, c->type);
1107 channel_free(c->self);
1111 channel_input_open_confirmation(int type, int plen)
1117 packet_integrity_check(plen, 4 + 4, type);
1119 id = packet_get_int();
1120 c = channel_lookup(id);
1122 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1123 packet_disconnect("Received open confirmation for "
1124 "non-opening channel %d.", id);
1125 remote_id = packet_get_int();
1126 /* Record the remote channel number and mark that the channel is now open. */
1127 c->remote_id = remote_id;
1128 c->type = SSH_CHANNEL_OPEN;
1131 c->remote_window = packet_get_int();
1132 c->remote_maxpacket = packet_get_int();
1134 if (c->cb_fn != NULL && c->cb_event == type) {
1135 debug("callback start");
1136 c->cb_fn(c->self, c->cb_arg);
1137 debug("callback done");
1139 debug("channel %d: open confirm rwindow %d rmax %d", c->self,
1140 c->remote_window, c->remote_maxpacket);
1145 channel_input_open_failure(int type, int plen)
1151 packet_integrity_check(plen, 4, type);
1153 id = packet_get_int();
1154 c = channel_lookup(id);
1156 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1157 packet_disconnect("Received open failure for "
1158 "non-opening channel %d.", id);
1160 int reason = packet_get_int();
1161 char *msg = packet_get_string(NULL);
1162 char *lang = packet_get_string(NULL);
1163 log("channel_open_failure: %d: reason %d: %s", id, reason, msg);
1168 /* Free the channel. This will also close the socket. */
1173 channel_input_channel_request(int type, int plen)
1178 id = packet_get_int();
1179 c = channel_lookup(id);
1182 (c->type != SSH_CHANNEL_OPEN && c->type != SSH_CHANNEL_LARVAL))
1183 packet_disconnect("Received request for "
1184 "non-open channel %d.", id);
1185 if (c->cb_fn != NULL && c->cb_event == type) {
1186 debug("callback start");
1187 c->cb_fn(c->self, c->cb_arg);
1188 debug("callback done");
1190 char *service = packet_get_string(NULL);
1191 debug("channel: %d rcvd request for %s", c->self, service);
1192 debug("cb_fn %p cb_event %d", c->cb_fn , c->cb_event);
1198 channel_input_window_adjust(int type, int plen)
1206 /* Get the channel number and verify it. */
1207 id = packet_get_int();
1208 c = channel_lookup(id);
1210 if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
1211 log("Received window adjust for "
1212 "non-open channel %d.", id);
1215 adjust = packet_get_int();
1217 debug("channel %d: rcvd adjust %d", id, adjust);
1218 c->remote_window += adjust;
1222 * Stops listening for channels, and removes any unix domain sockets that we
1227 channel_stop_listening()
1230 for (i = 0; i < channels_alloc; i++) {
1231 switch (channels[i].type) {
1232 case SSH_CHANNEL_AUTH_SOCKET:
1233 close(channels[i].sock);
1234 remove(channels[i].path);
1237 case SSH_CHANNEL_PORT_LISTENER:
1238 case SSH_CHANNEL_X11_LISTENER:
1239 close(channels[i].sock);
1249 * Closes the sockets of all channels. This is used to close extra file
1250 * descriptors after a fork.
1257 for (i = 0; i < channels_alloc; i++) {
1258 if (channels[i].type != SSH_CHANNEL_FREE)
1259 close(channels[i].sock);
1263 /* Returns the maximum file descriptor number used by the channels. */
1268 return channel_max_fd_value;
1271 /* Returns true if any channel is still open. */
1274 channel_still_open()
1277 for (i = 0; i < channels_alloc; i++)
1278 switch (channels[i].type) {
1279 case SSH_CHANNEL_FREE:
1280 case SSH_CHANNEL_X11_LISTENER:
1281 case SSH_CHANNEL_PORT_LISTENER:
1282 case SSH_CHANNEL_CLOSED:
1283 case SSH_CHANNEL_AUTH_SOCKET:
1285 case SSH_CHANNEL_LARVAL:
1287 fatal("cannot happen: SSH_CHANNEL_LARVAL");
1289 case SSH_CHANNEL_OPENING:
1290 case SSH_CHANNEL_OPEN:
1291 case SSH_CHANNEL_X11_OPEN:
1293 case SSH_CHANNEL_INPUT_DRAINING:
1294 case SSH_CHANNEL_OUTPUT_DRAINING:
1296 fatal("cannot happen: OUT_DRAIN");
1299 fatal("channel_still_open: bad channel type %d", channels[i].type);
1306 * Returns a message describing the currently open forwarded connections,
1307 * suitable for sending to the client. The message contains crlf pairs for
1312 channel_open_message()
1318 buffer_init(&buffer);
1319 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
1320 buffer_append(&buffer, buf, strlen(buf));
1321 for (i = 0; i < channels_alloc; i++) {
1322 Channel *c = &channels[i];
1324 case SSH_CHANNEL_FREE:
1325 case SSH_CHANNEL_X11_LISTENER:
1326 case SSH_CHANNEL_PORT_LISTENER:
1327 case SSH_CHANNEL_CLOSED:
1328 case SSH_CHANNEL_AUTH_SOCKET:
1330 case SSH_CHANNEL_LARVAL:
1331 case SSH_CHANNEL_OPENING:
1332 case SSH_CHANNEL_OPEN:
1333 case SSH_CHANNEL_X11_OPEN:
1334 case SSH_CHANNEL_INPUT_DRAINING:
1335 case SSH_CHANNEL_OUTPUT_DRAINING:
1336 snprintf(buf, sizeof buf, " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
1337 c->self, c->remote_name,
1338 c->type, c->remote_id,
1339 c->istate, buffer_len(&c->input),
1340 c->ostate, buffer_len(&c->output),
1342 buffer_append(&buffer, buf, strlen(buf));
1345 fatal("channel_open_message: bad channel type %d", c->type);
1349 buffer_append(&buffer, "\0", 1);
1350 cp = xstrdup(buffer_ptr(&buffer));
1351 buffer_free(&buffer);
1356 * Initiate forwarding of connections to local port "port" through the secure
1357 * channel to host:port from remote side.
1361 channel_request_local_forwarding(u_short port, const char *host,
1362 u_short host_port, int gateway_ports)
1364 int success, ch, sock, on = 1;
1365 struct addrinfo hints, *ai, *aitop;
1366 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1367 struct linger linger;
1369 if (strlen(host) > sizeof(channels[0].path) - 1)
1370 packet_disconnect("Forward host name too long.");
1373 * getaddrinfo returns a loopback address if the hostname is
1374 * set to NULL and hints.ai_flags is not AI_PASSIVE
1376 memset(&hints, 0, sizeof(hints));
1377 hints.ai_family = IPv4or6;
1378 hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
1379 hints.ai_socktype = SOCK_STREAM;
1380 snprintf(strport, sizeof strport, "%d", port);
1381 if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
1382 packet_disconnect("getaddrinfo: fatal error");
1385 for (ai = aitop; ai; ai = ai->ai_next) {
1386 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1388 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1389 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1390 error("channel_request_local_forwarding: getnameinfo failed");
1393 /* Create a port to listen for the host. */
1394 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1396 /* this is no error since kernel may not support ipv6 */
1397 verbose("socket: %.100s", strerror(errno));
1401 * Set socket options. We would like the socket to disappear
1402 * as soon as it has been closed for whatever reason.
1404 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
1406 linger.l_linger = 5;
1407 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
1408 debug("Local forwarding listening on %s port %s.", ntop, strport);
1410 /* Bind the socket to the address. */
1411 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1412 /* address can be in use ipv6 address is already bound */
1414 error("bind: %.100s", strerror(errno));
1416 verbose("bind: %.100s", strerror(errno));
1421 /* Start listening for connections on the socket. */
1422 if (listen(sock, 5) < 0) {
1423 error("listen: %.100s", strerror(errno));
1427 /* Allocate a channel number for the socket. */
1429 "port listener", SSH_CHANNEL_PORT_LISTENER,
1431 CHAN_WINDOW_DEFAULT, CHAN_PACKET_DEFAULT,
1432 0, xstrdup("port listener"));
1433 strlcpy(channels[ch].path, host, sizeof(channels[ch].path));
1434 channels[ch].host_port = host_port;
1435 channels[ch].listening_port = port;
1439 packet_disconnect("cannot listen port: %d", port);
1440 freeaddrinfo(aitop);
1444 * Initiate forwarding of connections to port "port" on remote host through
1445 * the secure channel to host:port from local side.
1449 channel_request_remote_forwarding(u_short listen_port, const char *host_to_connect,
1450 u_short port_to_connect)
1453 /* Record locally that connection to this host/port is permitted. */
1454 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
1455 fatal("channel_request_remote_forwarding: too many forwards");
1457 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
1458 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
1459 permitted_opens[num_permitted_opens].listen_port = listen_port;
1460 num_permitted_opens++;
1462 /* Send the forward request to the remote side. */
1464 const char *address_to_bind = "0.0.0.0";
1465 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1466 packet_put_cstring("tcpip-forward");
1467 packet_put_char(0); /* boolean: want reply */
1468 packet_put_cstring(address_to_bind);
1469 packet_put_int(listen_port);
1471 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1472 packet_put_int(port_to_connect);
1473 packet_put_cstring(host_to_connect);
1474 packet_put_int(listen_port);
1476 packet_write_wait();
1478 * Wait for response from the remote side. It will send a disconnect
1479 * message on failure, and we will never see it here.
1481 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1486 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
1487 * listening for the port, and sends back a success reply (or disconnect
1488 * message if there was an error). This never returns if there was an error.
1492 channel_input_port_forward_request(int is_root)
1494 u_short port, host_port;
1497 /* Get arguments from the packet. */
1498 port = packet_get_int();
1499 hostname = packet_get_string(NULL);
1500 host_port = packet_get_int();
1503 * Check that an unprivileged user is not trying to forward a
1506 if (port < IPPORT_RESERVED && !is_root)
1507 packet_disconnect("Requested forwarding of port %d but user is not root.",
1510 * Initiate forwarding,
1511 * bind port to localhost only (gateway ports == 0).
1513 channel_request_local_forwarding(port, hostname, host_port, 0);
1515 /* Free the argument string. */
1519 /* XXX move to aux.c */
1521 channel_connect_to(const char *host, u_short host_port)
1523 struct addrinfo hints, *ai, *aitop;
1524 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1528 memset(&hints, 0, sizeof(hints));
1529 hints.ai_family = IPv4or6;
1530 hints.ai_socktype = SOCK_STREAM;
1531 snprintf(strport, sizeof strport, "%d", host_port);
1532 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
1533 error("%.100s: unknown host (%s)", host, gai_strerror(gaierr));
1536 for (ai = aitop; ai; ai = ai->ai_next) {
1537 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1539 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1540 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1541 error("channel_connect_to: getnameinfo failed");
1544 /* Create the socket. */
1545 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1547 error("socket: %.100s", strerror(errno));
1550 /* Connect to the host/port. */
1551 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1552 error("connect %.100s port %s: %.100s", ntop, strport,
1555 continue; /* fail -- try next */
1557 break; /* success */
1560 freeaddrinfo(aitop);
1562 error("connect %.100s port %d: failed.", host, host_port);
1570 * This is called after receiving PORT_OPEN message. This attempts to
1571 * connect to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION
1572 * or CHANNEL_OPEN_FAILURE.
1576 channel_input_port_open(int type, int plen)
1579 char *host, *originator_string;
1580 int remote_channel, sock = -1, newch, i, denied;
1581 unsigned int host_len, originator_len;
1583 /* Get remote channel number. */
1584 remote_channel = packet_get_int();
1586 /* Get host name to connect to. */
1587 host = packet_get_string(&host_len);
1589 /* Get port to connect to. */
1590 host_port = packet_get_int();
1592 /* Get remote originator name. */
1593 if (have_hostname_in_open) {
1594 originator_string = packet_get_string(&originator_len);
1595 originator_len += 4; /* size of packet_int */
1597 originator_string = xstrdup("unknown (remote did not supply name)");
1598 originator_len = 0; /* no originator supplied */
1601 packet_integrity_check(plen,
1602 4 + 4 + host_len + 4 + originator_len, SSH_MSG_PORT_OPEN);
1604 /* Check if opening that port is permitted. */
1606 if (!all_opens_permitted) {
1607 /* Go trough all permitted ports. */
1608 for (i = 0; i < num_permitted_opens; i++)
1609 if (permitted_opens[i].port_to_connect == host_port &&
1610 strcmp(permitted_opens[i].host_to_connect, host) == 0)
1613 /* Check if we found the requested port among those permitted. */
1614 if (i >= num_permitted_opens) {
1615 /* The port is not permitted. */
1616 log("Received request to connect to %.100s:%d, but the request was denied.",
1621 sock = denied ? -1 : channel_connect_to(host, host_port);
1623 /* Allocate a channel for this connection. */
1624 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, originator_string);
1625 channels[newch].remote_id = remote_channel;
1627 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1628 packet_put_int(remote_channel);
1629 packet_put_int(newch);
1632 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1633 packet_put_int(remote_channel);
1640 * Creates an internet domain socket for listening for X11 connections.
1641 * Returns a suitable value for the DISPLAY variable, or NULL if an error
1645 #define NUM_SOCKS 10
1648 x11_create_display_inet(int screen_number, int x11_display_offset)
1650 int display_number, sock;
1652 struct addrinfo hints, *ai, *aitop;
1653 char strport[NI_MAXSERV];
1654 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
1656 char hostname[MAXHOSTNAMELEN];
1658 for (display_number = x11_display_offset;
1659 display_number < MAX_DISPLAYS;
1661 port = 6000 + display_number;
1662 memset(&hints, 0, sizeof(hints));
1663 hints.ai_family = IPv4or6;
1664 hints.ai_flags = AI_PASSIVE; /* XXX loopback only ? */
1665 hints.ai_socktype = SOCK_STREAM;
1666 snprintf(strport, sizeof strport, "%d", port);
1667 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
1668 error("getaddrinfo: %.100s", gai_strerror(gaierr));
1671 for (ai = aitop; ai; ai = ai->ai_next) {
1672 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1674 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1676 if (errno != EINVAL) {
1677 error("socket: %.100s", strerror(errno));
1680 debug("Socket family %d not supported [X11 disp create]", ai->ai_family);
1684 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1685 debug("bind port %d: %.100s", port, strerror(errno));
1686 shutdown(sock, SHUT_RDWR);
1692 for (n = 0; n < num_socks; n++) {
1693 shutdown(socks[n], SHUT_RDWR);
1699 socks[num_socks++] = sock;
1700 #ifndef DONT_TRY_OTHER_AF
1701 if (num_socks == NUM_SOCKS)
1710 if (display_number >= MAX_DISPLAYS) {
1711 error("Failed to allocate internet-domain X11 display socket.");
1714 /* Start listening for connections on the socket. */
1715 for (n = 0; n < num_socks; n++) {
1717 if (listen(sock, 5) < 0) {
1718 error("listen: %.100s", strerror(errno));
1719 shutdown(sock, SHUT_RDWR);
1725 /* Set up a suitable value for the DISPLAY variable. */
1727 if (gethostname(hostname, sizeof(hostname)) < 0)
1728 fatal("gethostname: %.100s", strerror(errno));
1730 #ifdef IPADDR_IN_DISPLAY
1732 * HPUX detects the local hostname in the DISPLAY variable and tries
1733 * to set up a shared memory connection to the server, which it
1734 * incorrectly supposes to be local.
1736 * The workaround - as used in later $$H and other programs - is
1737 * is to set display to the host's IP address.
1741 struct in_addr my_addr;
1743 he = gethostbyname(hostname);
1745 error("[X11-broken-fwd-hostname-workaround] Could not get "
1746 "IP address for hostname %s.", hostname);
1748 packet_send_debug("[X11-broken-fwd-hostname-workaround]"
1749 "Could not get IP address for hostname %s.", hostname);
1751 shutdown(sock, SHUT_RDWR);
1757 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
1759 /* Set DISPLAY to <ip address>:screen.display */
1760 snprintf(display, sizeof(display), "%.50s:%d.%d", inet_ntoa(my_addr),
1761 display_number, screen_number);
1763 #else /* IPADDR_IN_DISPLAY */
1764 /* Just set DISPLAY to hostname:screen.display */
1765 snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
1766 display_number, screen_number);
1767 #endif /* IPADDR_IN_DISPLAY */
1769 /* Allocate a channel for each socket. */
1770 for (n = 0; n < num_socks; n++) {
1772 (void) channel_allocate(SSH_CHANNEL_X11_LISTENER, sock,
1773 xstrdup("X11 inet listener"));
1776 /* Return a suitable value for the DISPLAY environment variable. */
1777 return xstrdup(display);
1781 #define X_UNIX_PATH "/tmp/.X11-unix/X"
1786 connect_local_xsocket(unsigned int dnr)
1788 static const char *const x_sockets[] = {
1790 "/var/X/.X11-unix/X" "%u",
1791 "/usr/spool/sockets/X11/" "%u",
1795 struct sockaddr_un addr;
1796 const char *const * path;
1798 for (path = x_sockets; *path; ++path) {
1799 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1801 error("socket: %.100s", strerror(errno));
1802 memset(&addr, 0, sizeof(addr));
1803 addr.sun_family = AF_UNIX;
1804 snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
1805 if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
1809 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
1815 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
1816 * the remote channel number. We should do whatever we want, and respond
1817 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
1821 x11_input_open(int type, int plen)
1823 int remote_channel, display_number, sock = 0, newch;
1824 const char *display;
1825 char buf[1024], *cp, *remote_host;
1826 unsigned int remote_len;
1827 struct addrinfo hints, *ai, *aitop;
1828 char strport[NI_MAXSERV];
1831 /* Get remote channel number. */
1832 remote_channel = packet_get_int();
1834 /* Get remote originator name. */
1835 if (have_hostname_in_open) {
1836 remote_host = packet_get_string(&remote_len);
1839 remote_host = xstrdup("unknown (remote did not supply name)");
1843 debug("Received X11 open request.");
1844 packet_integrity_check(plen, 4 + remote_len, SSH_SMSG_X11_OPEN);
1846 /* Try to open a socket for the local X server. */
1847 display = getenv("DISPLAY");
1849 error("DISPLAY not set.");
1853 * Now we decode the value of the DISPLAY variable and make a
1854 * connection to the real X server.
1858 * Check if it is a unix domain socket. Unix domain displays are in
1859 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
1861 if (strncmp(display, "unix:", 5) == 0 ||
1862 display[0] == ':') {
1863 /* Connect to the unix domain socket. */
1864 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
1865 error("Could not parse display number from DISPLAY: %.100s",
1869 /* Create a socket. */
1870 sock = connect_local_xsocket(display_number);
1874 /* OK, we now have a connection to the display. */
1878 * Connect to an inet socket. The DISPLAY value is supposedly
1879 * hostname:d[.s], where hostname may also be numeric IP address.
1881 strncpy(buf, display, sizeof(buf));
1882 buf[sizeof(buf) - 1] = 0;
1883 cp = strchr(buf, ':');
1885 error("Could not find ':' in DISPLAY: %.100s", display);
1889 /* buf now contains the host name. But first we parse the display number. */
1890 if (sscanf(cp + 1, "%d", &display_number) != 1) {
1891 error("Could not parse display number from DISPLAY: %.100s",
1896 /* Look up the host address */
1897 memset(&hints, 0, sizeof(hints));
1898 hints.ai_family = IPv4or6;
1899 hints.ai_socktype = SOCK_STREAM;
1900 snprintf(strport, sizeof strport, "%d", 6000 + display_number);
1901 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
1902 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
1905 for (ai = aitop; ai; ai = ai->ai_next) {
1906 /* Create a socket. */
1907 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1909 debug("socket: %.100s", strerror(errno));
1912 /* Connect it to the display. */
1913 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1914 debug("connect %.100s port %d: %.100s", buf,
1915 6000 + display_number, strerror(errno));
1922 freeaddrinfo(aitop);
1924 error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
1929 /* We have successfully obtained a connection to the real X display. */
1931 /* Allocate a channel for this connection. */
1932 if (x11_saved_proto == NULL)
1933 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, remote_host);
1935 newch = channel_allocate(SSH_CHANNEL_X11_OPEN, sock, remote_host);
1936 channels[newch].remote_id = remote_channel;
1938 /* Send a confirmation to the remote host. */
1939 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1940 packet_put_int(remote_channel);
1941 packet_put_int(newch);
1947 /* Send refusal to the remote host. */
1948 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1949 packet_put_int(remote_channel);
1954 * Requests forwarding of X11 connections, generates fake authentication
1955 * data, and enables authentication spoofing.
1959 x11_request_forwarding_with_spoofing(const char *proto, const char *data)
1961 unsigned int data_len = (unsigned int) strlen(data) / 2;
1962 unsigned int i, value;
1968 cp = getenv("DISPLAY");
1970 cp = strchr(cp, ':');
1972 cp = strchr(cp, '.');
1974 screen_number = atoi(cp + 1);
1978 /* Save protocol name. */
1979 x11_saved_proto = xstrdup(proto);
1982 * Extract real authentication data and generate fake data of the
1985 x11_saved_data = xmalloc(data_len);
1986 x11_fake_data = xmalloc(data_len);
1987 for (i = 0; i < data_len; i++) {
1988 if (sscanf(data + 2 * i, "%2x", &value) != 1)
1989 fatal("x11_request_forwarding: bad authentication data: %.100s", data);
1991 rand = arc4random();
1992 x11_saved_data[i] = value;
1993 x11_fake_data[i] = rand & 0xff;
1996 x11_saved_data_len = data_len;
1997 x11_fake_data_len = data_len;
1999 /* Convert the fake data into hex. */
2000 new_data = xmalloc(2 * data_len + 1);
2001 for (i = 0; i < data_len; i++)
2002 sprintf(new_data + 2 * i, "%02x", (unsigned char) x11_fake_data[i]);
2004 /* Send the request packet. */
2005 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
2006 packet_put_string(proto, strlen(proto));
2007 packet_put_string(new_data, strlen(new_data));
2008 packet_put_int(screen_number);
2010 packet_write_wait();
2014 /* Sends a message to the server to request authentication fd forwarding. */
2017 auth_request_forwarding()
2019 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
2021 packet_write_wait();
2025 * Returns the name of the forwarded authentication socket. Returns NULL if
2026 * there is no forwarded authentication socket. The returned value points to
2031 auth_get_socket_name()
2033 return channel_forwarded_auth_socket_name;
2036 /* removes the agent forwarding socket */
2039 cleanup_socket(void)
2041 remove(channel_forwarded_auth_socket_name);
2042 rmdir(channel_forwarded_auth_socket_dir);
2046 * This if called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
2047 * This starts forwarding authentication requests.
2051 auth_input_request_forwarding(struct passwd * pw)
2054 struct sockaddr_un sunaddr;
2056 if (auth_get_socket_name() != NULL)
2057 fatal("Protocol error: authentication forwarding requested twice.");
2059 /* Temporarily drop privileged uid for mkdir/bind. */
2060 temporarily_use_uid(pw->pw_uid);
2062 /* Allocate a buffer for the socket name, and format the name. */
2063 channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
2064 channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
2065 strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
2067 /* Create private directory for socket */
2068 if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL)
2069 packet_disconnect("mkdtemp: %.100s", strerror(errno));
2070 snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME, "%s/agent.%d",
2071 channel_forwarded_auth_socket_dir, (int) getpid());
2073 if (atexit(cleanup_socket) < 0) {
2076 packet_disconnect("socket: %.100s", strerror(saved));
2078 /* Create the socket. */
2079 sock = socket(AF_UNIX, SOCK_STREAM, 0);
2081 packet_disconnect("socket: %.100s", strerror(errno));
2083 /* Bind it to the name. */
2084 memset(&sunaddr, 0, sizeof(sunaddr));
2085 sunaddr.sun_family = AF_UNIX;
2086 strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
2087 sizeof(sunaddr.sun_path));
2089 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
2090 packet_disconnect("bind: %.100s", strerror(errno));
2092 /* Restore the privileged uid. */
2095 /* Start listening on the socket. */
2096 if (listen(sock, 5) < 0)
2097 packet_disconnect("listen: %.100s", strerror(errno));
2099 /* Allocate a channel for the authentication agent socket. */
2100 newch = channel_allocate(SSH_CHANNEL_AUTH_SOCKET, sock,
2101 xstrdup("auth socket"));
2102 strlcpy(channels[newch].path, channel_forwarded_auth_socket_name,
2103 sizeof(channels[newch].path));
2106 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
2109 auth_input_open_request(int type, int plen)
2111 int remch, sock, newch;
2114 packet_integrity_check(plen, 4, type);
2116 /* Read the remote channel number from the message. */
2117 remch = packet_get_int();
2120 * Get a connection to the local authentication agent (this may again
2123 sock = ssh_get_authentication_socket();
2126 * If we could not connect the agent, send an error message back to
2127 * the server. This should never happen unless the agent dies,
2128 * because authentication forwarding is only enabled if we have an
2132 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2133 packet_put_int(remch);
2137 debug("Forwarding authentication connection.");
2140 * Dummy host name. This will be freed when the channel is freed; it
2141 * will still be valid in the packet_put_string below since the
2142 * channel cannot yet be freed at that point.
2144 dummyname = xstrdup("authentication agent connection");
2146 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
2147 channels[newch].remote_id = remch;
2149 /* Send a confirmation to the remote host. */
2150 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2151 packet_put_int(remch);
2152 packet_put_int(newch);
2157 channel_open(int id)
2159 Channel *c = channel_lookup(id);
2161 log("channel_open: %d: bad id", id);
2164 packet_start(SSH2_MSG_CHANNEL_OPEN);
2165 packet_put_cstring(c->ctype);
2166 packet_put_int(c->self);
2167 packet_put_int(c->local_window);
2168 packet_put_int(c->local_maxpacket);
2170 debug("channel open %d", id);
2173 channel_request(int id, char *service, int wantconfirm)
2175 channel_request_start(id, service, wantconfirm);
2177 debug("channel request %d: %s", id, service) ;
2180 channel_request_start(int id, char *service, int wantconfirm)
2182 Channel *c = channel_lookup(id);
2184 log("channel_request: %d: bad id", id);
2187 packet_start(SSH2_MSG_CHANNEL_REQUEST);
2188 packet_put_int(c->remote_id);
2189 packet_put_cstring(service);
2190 packet_put_char(wantconfirm);
2193 channel_register_callback(int id, int mtype, channel_callback_fn *fn, void *arg)
2195 Channel *c = channel_lookup(id);
2197 log("channel_register_callback: %d: bad id", id);
2200 c->cb_event = mtype;
2205 channel_register_cleanup(int id, channel_callback_fn *fn)
2207 Channel *c = channel_lookup(id);
2209 log("channel_register_cleanup: %d: bad id", id);
2212 c->dettach_user = fn;
2215 channel_cancel_cleanup(int id)
2217 Channel *c = channel_lookup(id);
2219 log("channel_cancel_cleanup: %d: bad id", id);
2222 c->dettach_user = NULL;
2226 channel_set_fds(int id, int rfd, int wfd, int efd, int extusage)
2228 Channel *c = channel_lookup(id);
2229 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
2230 fatal("channel_activate for non-larval channel %d.", id);
2231 if (rfd > channel_max_fd_value)
2232 channel_max_fd_value = rfd;
2233 if (wfd > channel_max_fd_value)
2234 channel_max_fd_value = wfd;
2235 if (efd > channel_max_fd_value)
2236 channel_max_fd_value = efd;
2237 c->type = SSH_CHANNEL_OPEN;
2241 c->extended_usage = extusage;
2242 /* XXX window size? */
2243 c->local_window = c->local_window_max = c->local_maxpacket/2;
2244 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2245 packet_put_int(c->remote_id);
2246 packet_put_int(c->local_window);