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.
20 RCSID("$OpenBSD: channels.c,v 1.66 2000/08/19 21:55:51 markus Exp $");
36 #include <openssl/rsa.h>
37 #include <openssl/dsa.h>
41 /* Maximum number of fake X11 displays to try. */
42 #define MAX_DISPLAYS 1000
44 /* Max len of agent socket */
45 #define MAX_SOCKET_NAME 100
47 /* default window/packet sizes for tcp/x11-fwd-channel */
48 #define CHAN_TCP_WINDOW_DEFAULT (8*1024)
49 #define CHAN_TCP_PACKET_DEFAULT (CHAN_TCP_WINDOW_DEFAULT/2)
50 #define CHAN_X11_WINDOW_DEFAULT (4*1024)
51 #define CHAN_X11_PACKET_DEFAULT (CHAN_X11_WINDOW_DEFAULT/2)
54 * Pointer to an array containing all allocated channels. The array is
55 * dynamically extended as needed.
57 static Channel *channels = NULL;
60 * Size of the channel array. All slots of the array must always be
61 * initialized (at least the type field); unused slots are marked with type
64 static int channels_alloc = 0;
67 * Maximum file descriptor value used in any of the channels. This is
68 * updated in channel_allocate.
70 static int channel_max_fd_value = 0;
72 /* Name and directory of socket for authentication agent forwarding. */
73 static char *channel_forwarded_auth_socket_name = NULL;
74 static char *channel_forwarded_auth_socket_dir = NULL;
76 /* Saved X11 authentication protocol name. */
77 char *x11_saved_proto = NULL;
79 /* Saved X11 authentication data. This is the real data. */
80 char *x11_saved_data = NULL;
81 unsigned int x11_saved_data_len = 0;
84 * Fake X11 authentication data. This is what the server will be sending us;
85 * we should replace any occurrences of this by the real data.
87 char *x11_fake_data = NULL;
88 unsigned int x11_fake_data_len;
91 * Data structure for storing which hosts are permitted for forward requests.
92 * The local sides of any remote forwards are stored in this array to prevent
93 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
94 * network (which might be behind a firewall).
97 char *host_to_connect; /* Connect to 'host'. */
98 u_short port_to_connect; /* Connect to 'port'. */
99 u_short listen_port; /* Remote side should listen port number. */
102 /* List of all permitted host/port pairs to connect. */
103 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
104 /* Number of permitted host/port pairs in the array. */
105 static int num_permitted_opens = 0;
107 * If this is true, all opens are permitted. This is the case on the server
108 * on which we have to trust the client anyway, and the user could do
109 * anything after logging in anyway.
111 static int all_opens_permitted = 0;
113 /* This is set to true if both sides support SSH_PROTOFLAG_HOST_IN_FWD_OPEN. */
114 static int have_hostname_in_open = 0;
116 /* Sets specific protocol options. */
119 channel_set_options(int hostname_in_open)
121 have_hostname_in_open = hostname_in_open;
125 * Permits opening to any host/port in SSH_MSG_PORT_OPEN. This is usually
126 * called by the server, because the user could connect to any port anyway,
127 * and the server has no way to know but to trust the client anyway.
131 channel_permit_all_opens()
133 all_opens_permitted = 1;
136 /* lookup channel by id */
139 channel_lookup(int id)
142 if (id < 0 || id > channels_alloc) {
143 log("channel_lookup: %d: bad id", id);
147 if (c->type == SSH_CHANNEL_FREE) {
148 log("channel_lookup: %d: bad id: channel free", id);
155 * Register filedescriptors for a channel, used when allocating a channel or
156 * when the channel consumer/producer is ready, e.g. shell exec'd
160 channel_register_fds(Channel *c, int rfd, int wfd, int efd, int extusage)
162 /* Update the maximum file descriptor value. */
163 if (rfd > channel_max_fd_value)
164 channel_max_fd_value = rfd;
165 if (wfd > channel_max_fd_value)
166 channel_max_fd_value = wfd;
167 if (efd > channel_max_fd_value)
168 channel_max_fd_value = efd;
169 /* XXX set close-on-exec -markus */
173 c->sock = (rfd == wfd) ? rfd : -1;
175 c->extended_usage = extusage;
185 * Allocate a new channel object and set its type and socket. This will cause
186 * remote_name to be freed.
190 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
191 int window, int maxpack, int extusage, char *remote_name)
196 /* Do initial allocation if this is the first call. */
197 if (channels_alloc == 0) {
200 channels = xmalloc(channels_alloc * sizeof(Channel));
201 for (i = 0; i < channels_alloc; i++)
202 channels[i].type = SSH_CHANNEL_FREE;
204 * Kludge: arrange a call to channel_stop_listening if we
205 * terminate with fatal().
207 fatal_add_cleanup((void (*) (void *)) channel_stop_listening, NULL);
209 /* Try to find a free slot where to put the new channel. */
210 for (found = -1, i = 0; i < channels_alloc; i++)
211 if (channels[i].type == SSH_CHANNEL_FREE) {
212 /* Found a free slot. */
217 /* There are no free slots. Take last+1 slot and expand the array. */
218 found = channels_alloc;
219 channels_alloc += 10;
220 debug("channel: expanding %d", channels_alloc);
221 channels = xrealloc(channels, channels_alloc * sizeof(Channel));
222 for (i = found; i < channels_alloc; i++)
223 channels[i].type = SSH_CHANNEL_FREE;
225 /* Initialize and return new channel number. */
226 c = &channels[found];
227 buffer_init(&c->input);
228 buffer_init(&c->output);
229 buffer_init(&c->extended);
230 chan_init_iostates(c);
231 channel_register_fds(c, rfd, wfd, efd, extusage);
235 c->local_window = window;
236 c->local_window_max = window;
237 c->local_consumed = 0;
238 c->local_maxpacket = maxpack;
240 c->remote_name = remote_name;
241 c->remote_window = 0;
242 c->remote_maxpacket = 0;
246 c->dettach_user = NULL;
247 c->input_filter = NULL;
248 debug("channel %d: new [%s]", found, remote_name);
251 /* old interface XXX */
253 channel_allocate(int type, int sock, char *remote_name)
255 return channel_new("", type, sock, sock, -1, 0, 0, 0, remote_name);
259 /* Close all channel fd/socket. */
262 channel_close_fds(Channel *c)
282 /* Free the channel and close its fd/socket. */
287 Channel *c = channel_lookup(id);
289 packet_disconnect("channel free: bad local channel %d", id);
290 debug("channel_free: channel %d: status: %s", id, channel_open_message());
291 if (c->dettach_user != NULL) {
292 debug("channel_free: channel %d: dettaching channel user", id);
293 c->dettach_user(c->self, NULL);
296 shutdown(c->sock, SHUT_RDWR);
297 channel_close_fds(c);
298 buffer_free(&c->input);
299 buffer_free(&c->output);
300 buffer_free(&c->extended);
301 c->type = SSH_CHANNEL_FREE;
302 if (c->remote_name) {
303 xfree(c->remote_name);
304 c->remote_name = NULL;
309 * 'channel_pre*' are called just before select() to add any bits relevant to
310 * channels in the select bitmasks.
313 * 'channel_post*': perform any appropriate operations for channels which
314 * have events pending.
316 typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
317 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
318 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
321 channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
323 FD_SET(c->sock, readset);
327 channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
329 if (buffer_len(&c->input) < packet_get_maxsize())
330 FD_SET(c->sock, readset);
331 if (buffer_len(&c->output) > 0)
332 FD_SET(c->sock, writeset);
336 channel_pre_open_15(Channel *c, fd_set * readset, fd_set * writeset)
338 /* test whether sockets are 'alive' for read/write */
339 if (c->istate == CHAN_INPUT_OPEN)
340 if (buffer_len(&c->input) < packet_get_maxsize())
341 FD_SET(c->sock, readset);
342 if (c->ostate == CHAN_OUTPUT_OPEN ||
343 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
344 if (buffer_len(&c->output) > 0) {
345 FD_SET(c->sock, writeset);
346 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
353 channel_pre_open_20(Channel *c, fd_set * readset, fd_set * writeset)
355 if (c->istate == CHAN_INPUT_OPEN &&
356 c->remote_window > 0 &&
357 buffer_len(&c->input) < c->remote_window)
358 FD_SET(c->rfd, readset);
359 if (c->ostate == CHAN_OUTPUT_OPEN ||
360 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
361 if (buffer_len(&c->output) > 0) {
362 FD_SET(c->wfd, writeset);
363 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
367 /** XXX check close conditions, too */
369 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
370 buffer_len(&c->extended) > 0)
371 FD_SET(c->efd, writeset);
372 else if (c->extended_usage == CHAN_EXTENDED_READ &&
373 buffer_len(&c->extended) < c->remote_window)
374 FD_SET(c->efd, readset);
379 channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
381 if (buffer_len(&c->input) == 0) {
382 packet_start(SSH_MSG_CHANNEL_CLOSE);
383 packet_put_int(c->remote_id);
385 c->type = SSH_CHANNEL_CLOSED;
386 debug("Closing channel %d after input drain.", c->self);
391 channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
393 if (buffer_len(&c->output) == 0)
394 channel_free(c->self);
396 FD_SET(c->sock, writeset);
400 * This is a special state for X11 authentication spoofing. An opened X11
401 * connection (when authentication spoofing is being done) remains in this
402 * state until the first packet has been completely read. The authentication
403 * data in that packet is then substituted by the real data if it matches the
404 * fake data, and the channel is put into normal mode.
405 * XXX All this happens at the client side.
408 x11_open_helper(Channel *c)
411 unsigned int proto_len, data_len;
413 /* Check if the fixed size part of the packet is in buffer. */
414 if (buffer_len(&c->output) < 12)
417 /* Parse the lengths of variable-length fields. */
418 ucp = (unsigned char *) buffer_ptr(&c->output);
419 if (ucp[0] == 0x42) { /* Byte order MSB first. */
420 proto_len = 256 * ucp[6] + ucp[7];
421 data_len = 256 * ucp[8] + ucp[9];
422 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
423 proto_len = ucp[6] + 256 * ucp[7];
424 data_len = ucp[8] + 256 * ucp[9];
426 debug("Initial X11 packet contains bad byte order byte: 0x%x",
431 /* Check if the whole packet is in buffer. */
432 if (buffer_len(&c->output) <
433 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
436 /* Check if authentication protocol matches. */
437 if (proto_len != strlen(x11_saved_proto) ||
438 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
439 debug("X11 connection uses different authentication protocol.");
442 /* Check if authentication data matches our fake data. */
443 if (data_len != x11_fake_data_len ||
444 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
445 x11_fake_data, x11_fake_data_len) != 0) {
446 debug("X11 auth data does not match fake data.");
449 /* Check fake data length */
450 if (x11_fake_data_len != x11_saved_data_len) {
451 error("X11 fake_data_len %d != saved_data_len %d",
452 x11_fake_data_len, x11_saved_data_len);
456 * Received authentication protocol and data match
457 * our fake data. Substitute the fake data with real
460 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
461 x11_saved_data, x11_saved_data_len);
466 channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
468 int ret = x11_open_helper(c);
470 /* Start normal processing for the channel. */
471 c->type = SSH_CHANNEL_OPEN;
472 channel_pre_open_13(c, readset, writeset);
473 } else if (ret == -1) {
475 * We have received an X11 connection that has bad
476 * authentication information.
478 log("X11 connection rejected because of wrong authentication.\r\n");
479 buffer_clear(&c->input);
480 buffer_clear(&c->output);
483 c->type = SSH_CHANNEL_CLOSED;
484 packet_start(SSH_MSG_CHANNEL_CLOSE);
485 packet_put_int(c->remote_id);
491 channel_pre_x11_open(Channel *c, fd_set * readset, fd_set * writeset)
493 int ret = x11_open_helper(c);
495 c->type = SSH_CHANNEL_OPEN;
497 channel_pre_open_20(c, readset, writeset);
499 channel_pre_open_15(c, readset, writeset);
500 } else if (ret == -1) {
501 debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
502 chan_read_failed(c); /** force close? */
503 chan_write_failed(c);
504 debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
508 /* This is our fake X11 server socket. */
510 channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
512 struct sockaddr addr;
515 char buf[16384], *remote_hostname;
518 if (FD_ISSET(c->sock, readset)) {
519 debug("X11 connection requested.");
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, "X11 connection from %.200s port %d",
529 remote_hostname, remote_port);
531 newch = channel_new("x11",
532 SSH_CHANNEL_OPENING, newsock, newsock, -1,
533 c->local_window_max, c->local_maxpacket,
536 packet_start(SSH2_MSG_CHANNEL_OPEN);
537 packet_put_cstring("x11");
538 packet_put_int(newch);
539 packet_put_int(c->local_window_max);
540 packet_put_int(c->local_maxpacket);
541 /* originator host and port */
542 packet_put_cstring(remote_hostname);
543 if (datafellows & SSH_BUG_X11FWD) {
544 debug("ssh2 x11 bug compat mode");
546 packet_put_int(remote_port);
550 packet_start(SSH_SMSG_X11_OPEN);
551 packet_put_int(newch);
552 if (have_hostname_in_open)
553 packet_put_string(buf, strlen(buf));
556 xfree(remote_hostname);
561 * This socket is listening for connections to a forwarded TCP/IP port.
564 channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
566 struct sockaddr addr;
569 char buf[1024], *remote_hostname;
572 if (FD_ISSET(c->sock, readset)) {
573 debug("Connection to port %d forwarding "
574 "to %.100s port %d requested.",
575 c->listening_port, c->path, c->host_port);
576 addrlen = sizeof(addr);
577 newsock = accept(c->sock, &addr, &addrlen);
579 error("accept: %.100s", strerror(errno));
582 remote_hostname = get_remote_hostname(newsock);
583 remote_port = get_peer_port(newsock);
584 snprintf(buf, sizeof buf,
585 "listen port %d for %.100s port %d, "
586 "connect from %.200s port %d",
587 c->listening_port, c->path, c->host_port,
588 remote_hostname, remote_port);
589 newch = channel_new("direct-tcpip",
590 SSH_CHANNEL_OPENING, newsock, newsock, -1,
591 c->local_window_max, c->local_maxpacket,
594 packet_start(SSH2_MSG_CHANNEL_OPEN);
595 packet_put_cstring("direct-tcpip");
596 packet_put_int(newch);
597 packet_put_int(c->local_window_max);
598 packet_put_int(c->local_maxpacket);
599 /* target host and port */
600 packet_put_string(c->path, strlen(c->path));
601 packet_put_int(c->host_port);
602 /* originator host and port */
603 packet_put_cstring(remote_hostname);
604 packet_put_int(remote_port);
607 packet_start(SSH_MSG_PORT_OPEN);
608 packet_put_int(newch);
609 packet_put_string(c->path, strlen(c->path));
610 packet_put_int(c->host_port);
611 if (have_hostname_in_open) {
612 packet_put_string(buf, strlen(buf));
616 xfree(remote_hostname);
621 * This is the authentication agent socket listening for connections from
625 channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
627 struct sockaddr addr;
631 if (FD_ISSET(c->sock, readset)) {
632 addrlen = sizeof(addr);
633 newsock = accept(c->sock, &addr, &addrlen);
635 error("accept from auth socket: %.100s", strerror(errno));
638 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
639 xstrdup("accepted auth socket"));
640 packet_start(SSH_SMSG_AGENT_OPEN);
641 packet_put_int(newch);
647 channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
653 FD_ISSET(c->rfd, readset)) {
654 len = read(c->rfd, buf, sizeof(buf));
655 if (len < 0 && (errno == EINTR || errno == EAGAIN))
658 debug("channel %d: read<=0 rfd %d len %d",
659 c->self, c->rfd, len);
661 buffer_consume(&c->output, buffer_len(&c->output));
662 c->type = SSH_CHANNEL_INPUT_DRAINING;
663 debug("Channel %d status set to input draining.", c->self);
669 if(c->input_filter != NULL) {
670 if (c->input_filter(c, buf, len) == -1) {
671 debug("filter stops channel %d", c->self);
675 buffer_append(&c->input, buf, len);
681 channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
685 /* Send buffered output data to the socket. */
687 FD_ISSET(c->wfd, writeset) &&
688 buffer_len(&c->output) > 0) {
689 len = write(c->wfd, buffer_ptr(&c->output),
690 buffer_len(&c->output));
691 if (len < 0 && (errno == EINTR || errno == EAGAIN))
695 buffer_consume(&c->output, buffer_len(&c->output));
696 debug("Channel %d status set to input draining.", c->self);
697 c->type = SSH_CHANNEL_INPUT_DRAINING;
699 chan_write_failed(c);
703 buffer_consume(&c->output, len);
704 if (compat20 && len > 0) {
705 c->local_consumed += len;
711 channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
716 /** XXX handle drain efd, too */
718 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
719 FD_ISSET(c->efd, writeset) &&
720 buffer_len(&c->extended) > 0) {
721 len = write(c->efd, buffer_ptr(&c->extended),
722 buffer_len(&c->extended));
723 debug("channel %d: written %d to efd %d",
724 c->self, len, c->efd);
726 buffer_consume(&c->extended, len);
727 c->local_consumed += len;
729 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
730 FD_ISSET(c->efd, readset)) {
731 len = read(c->efd, buf, sizeof(buf));
732 debug("channel %d: read %d from efd %d",
733 c->self, len, c->efd);
735 debug("channel %d: closing efd %d",
740 buffer_append(&c->extended, buf, len);
746 channel_check_window(Channel *c, fd_set * readset, fd_set * writeset)
748 if (!(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
749 c->local_window < c->local_window_max/2 &&
750 c->local_consumed > 0) {
751 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
752 packet_put_int(c->remote_id);
753 packet_put_int(c->local_consumed);
755 debug("channel %d: window %d sent adjust %d",
756 c->self, c->local_window,
758 c->local_window += c->local_consumed;
759 c->local_consumed = 0;
765 channel_post_open_1(Channel *c, fd_set * readset, fd_set * writeset)
767 channel_handle_rfd(c, readset, writeset);
768 channel_handle_wfd(c, readset, writeset);
772 channel_post_open_2(Channel *c, fd_set * readset, fd_set * writeset)
774 channel_handle_rfd(c, readset, writeset);
775 channel_handle_wfd(c, readset, writeset);
776 channel_handle_efd(c, readset, writeset);
777 channel_check_window(c, readset, writeset);
781 channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
784 /* Send buffered output data to the socket. */
785 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
786 len = write(c->sock, buffer_ptr(&c->output),
787 buffer_len(&c->output));
789 buffer_consume(&c->output, buffer_len(&c->output));
791 buffer_consume(&c->output, len);
796 channel_handler_init_20(void)
798 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_20;
799 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
800 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
801 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
803 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open_2;
804 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
805 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
809 channel_handler_init_13(void)
811 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
812 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
813 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
814 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
815 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
816 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
817 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
819 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open_1;
820 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
821 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
822 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
823 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
827 channel_handler_init_15(void)
829 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_15;
830 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
831 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
832 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
833 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
835 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
836 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
837 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
838 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open_1;
842 channel_handler_init(void)
845 for(i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
846 channel_pre[i] = NULL;
847 channel_post[i] = NULL;
850 channel_handler_init_20();
852 channel_handler_init_13();
854 channel_handler_init_15();
858 channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
860 static int did_init = 0;
865 channel_handler_init();
868 for (i = 0; i < channels_alloc; i++) {
870 if (c->type == SSH_CHANNEL_FREE)
872 if (ftab[c->type] == NULL)
874 (*ftab[c->type])(c, readset, writeset);
875 chan_delete_if_full_closed(c);
880 channel_prepare_select(fd_set * readset, fd_set * writeset)
882 channel_handler(channel_pre, readset, writeset);
886 channel_after_select(fd_set * readset, fd_set * writeset)
888 channel_handler(channel_post, readset, writeset);
891 /* If there is data to send to the connection, send some of it now. */
894 channel_output_poll()
899 for (i = 0; i < channels_alloc; i++) {
902 /* We are only interested in channels that can have buffered incoming data. */
904 if (c->type != SSH_CHANNEL_OPEN &&
905 c->type != SSH_CHANNEL_INPUT_DRAINING)
908 if (c->type != SSH_CHANNEL_OPEN)
910 if (c->istate != CHAN_INPUT_OPEN &&
911 c->istate != CHAN_INPUT_WAIT_DRAIN)
915 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
916 debug("channel: %d: no data after CLOSE", c->self);
920 /* Get the amount of buffered data for this channel. */
921 len = buffer_len(&c->input);
923 /* Send some data for the other side over the secure connection. */
925 if (len > c->remote_window)
926 len = c->remote_window;
927 if (len > c->remote_maxpacket)
928 len = c->remote_maxpacket;
930 if (packet_is_interactive()) {
934 /* Keep the packets at reasonable size. */
935 if (len > packet_get_maxsize()/2)
936 len = packet_get_maxsize()/2;
940 packet_start(compat20 ?
941 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
942 packet_put_int(c->remote_id);
943 packet_put_string(buffer_ptr(&c->input), len);
945 buffer_consume(&c->input, len);
946 c->remote_window -= len;
948 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
950 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
952 * input-buffer is empty and read-socket shutdown:
953 * tell peer, that we will not send more data: send IEOF
957 /* Send extended data, i.e. stderr */
959 c->remote_window > 0 &&
960 (len = buffer_len(&c->extended)) > 0 &&
961 c->extended_usage == CHAN_EXTENDED_READ) {
962 if (len > c->remote_window)
963 len = c->remote_window;
964 if (len > c->remote_maxpacket)
965 len = c->remote_maxpacket;
966 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
967 packet_put_int(c->remote_id);
968 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
969 packet_put_string(buffer_ptr(&c->extended), len);
971 buffer_consume(&c->extended, len);
972 c->remote_window -= len;
978 * This is called when a packet of type CHANNEL_DATA has just been received.
979 * The message type has already been consumed, but channel number and data is
984 channel_input_data(int type, int plen)
988 unsigned int data_len;
991 /* Get the channel number and verify it. */
992 id = packet_get_int();
993 c = channel_lookup(id);
995 packet_disconnect("Received data for nonexistent channel %d.", id);
997 /* Ignore any data for non-open channels (might happen on close) */
998 if (c->type != SSH_CHANNEL_OPEN &&
999 c->type != SSH_CHANNEL_X11_OPEN)
1002 /* same for protocol 1.5 if output end is no longer open */
1003 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
1007 data = packet_get_string(&data_len);
1011 if (data_len > c->local_maxpacket) {
1012 log("channel %d: rcvd big packet %d, maxpack %d",
1013 c->self, data_len, c->local_maxpacket);
1015 if (data_len > c->local_window) {
1016 log("channel %d: rcvd too much data %d, win %d",
1017 c->self, data_len, c->local_window);
1021 c->local_window -= data_len;
1023 packet_integrity_check(plen, 4 + 4 + data_len, type);
1025 buffer_append(&c->output, data, data_len);
1029 channel_input_extended_data(int type, int plen)
1034 unsigned int data_len;
1037 /* Get the channel number and verify it. */
1038 id = packet_get_int();
1039 c = channel_lookup(id);
1042 packet_disconnect("Received extended_data for bad channel %d.", id);
1043 if (c->type != SSH_CHANNEL_OPEN) {
1044 log("channel %d: ext data for non open", id);
1047 tcode = packet_get_int();
1049 c->extended_usage != CHAN_EXTENDED_WRITE ||
1050 tcode != SSH2_EXTENDED_DATA_STDERR) {
1051 log("channel %d: bad ext data", c->self);
1054 data = packet_get_string(&data_len);
1056 if (data_len > c->local_window) {
1057 log("channel %d: rcvd too much extended_data %d, win %d",
1058 c->self, data_len, c->local_window);
1062 debug("channel %d: rcvd ext data %d", c->self, data_len);
1063 c->local_window -= data_len;
1064 buffer_append(&c->extended, data, data_len);
1070 * Returns true if no channel has too much buffered data, and false if one or
1071 * more channel is overfull.
1075 channel_not_very_much_buffered_data()
1080 for (i = 0; i < channels_alloc; i++) {
1082 if (c->type == SSH_CHANNEL_OPEN) {
1083 if (!compat20 && buffer_len(&c->input) > packet_get_maxsize()) {
1084 debug("channel %d: big input buffer %d",
1085 c->self, buffer_len(&c->input));
1088 if (buffer_len(&c->output) > packet_get_maxsize()) {
1089 debug("channel %d: big output buffer %d",
1090 c->self, buffer_len(&c->output));
1099 channel_input_ieof(int type, int plen)
1104 packet_integrity_check(plen, 4, type);
1106 id = packet_get_int();
1107 c = channel_lookup(id);
1109 packet_disconnect("Received ieof for nonexistent channel %d.", id);
1114 channel_input_close(int type, int plen)
1119 packet_integrity_check(plen, 4, type);
1121 id = packet_get_int();
1122 c = channel_lookup(id);
1124 packet_disconnect("Received close for nonexistent channel %d.", id);
1127 * Send a confirmation that we have closed the channel and no more
1128 * data is coming for it.
1130 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1131 packet_put_int(c->remote_id);
1135 * If the channel is in closed state, we have sent a close request,
1136 * and the other side will eventually respond with a confirmation.
1137 * Thus, we cannot free the channel here, because then there would be
1138 * no-one to receive the confirmation. The channel gets freed when
1139 * the confirmation arrives.
1141 if (c->type != SSH_CHANNEL_CLOSED) {
1143 * Not a closed channel - mark it as draining, which will
1144 * cause it to be freed later.
1146 buffer_consume(&c->input, buffer_len(&c->input));
1147 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1151 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1153 channel_input_oclose(int type, int plen)
1155 int id = packet_get_int();
1156 Channel *c = channel_lookup(id);
1157 packet_integrity_check(plen, 4, type);
1159 packet_disconnect("Received oclose for nonexistent channel %d.", id);
1160 chan_rcvd_oclose(c);
1164 channel_input_close_confirmation(int type, int plen)
1166 int id = packet_get_int();
1167 Channel *c = channel_lookup(id);
1171 packet_disconnect("Received close confirmation for "
1172 "out-of-range channel %d.", id);
1173 if (c->type != SSH_CHANNEL_CLOSED)
1174 packet_disconnect("Received close confirmation for "
1175 "non-closed channel %d (type %d).", id, c->type);
1176 channel_free(c->self);
1180 channel_input_open_confirmation(int type, int plen)
1186 packet_integrity_check(plen, 4 + 4, type);
1188 id = packet_get_int();
1189 c = channel_lookup(id);
1191 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1192 packet_disconnect("Received open confirmation for "
1193 "non-opening channel %d.", id);
1194 remote_id = packet_get_int();
1195 /* Record the remote channel number and mark that the channel is now open. */
1196 c->remote_id = remote_id;
1197 c->type = SSH_CHANNEL_OPEN;
1200 c->remote_window = packet_get_int();
1201 c->remote_maxpacket = packet_get_int();
1203 if (c->cb_fn != NULL && c->cb_event == type) {
1204 debug("callback start");
1205 c->cb_fn(c->self, c->cb_arg);
1206 debug("callback done");
1208 debug("channel %d: open confirm rwindow %d rmax %d", c->self,
1209 c->remote_window, c->remote_maxpacket);
1214 channel_input_open_failure(int type, int plen)
1220 packet_integrity_check(plen, 4, type);
1222 id = packet_get_int();
1223 c = channel_lookup(id);
1225 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1226 packet_disconnect("Received open failure for "
1227 "non-opening channel %d.", id);
1229 int reason = packet_get_int();
1230 char *msg = packet_get_string(NULL);
1231 char *lang = packet_get_string(NULL);
1232 log("channel_open_failure: %d: reason %d: %s", id, reason, msg);
1237 /* Free the channel. This will also close the socket. */
1242 channel_input_channel_request(int type, int plen)
1247 id = packet_get_int();
1248 c = channel_lookup(id);
1251 (c->type != SSH_CHANNEL_OPEN && c->type != SSH_CHANNEL_LARVAL))
1252 packet_disconnect("Received request for "
1253 "non-open channel %d.", id);
1254 if (c->cb_fn != NULL && c->cb_event == type) {
1255 debug("callback start");
1256 c->cb_fn(c->self, c->cb_arg);
1257 debug("callback done");
1259 char *service = packet_get_string(NULL);
1260 debug("channel: %d rcvd request for %s", c->self, service);
1261 debug("cb_fn %p cb_event %d", c->cb_fn , c->cb_event);
1267 channel_input_window_adjust(int type, int plen)
1275 /* Get the channel number and verify it. */
1276 id = packet_get_int();
1277 c = channel_lookup(id);
1279 if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
1280 log("Received window adjust for "
1281 "non-open channel %d.", id);
1284 adjust = packet_get_int();
1286 debug("channel %d: rcvd adjust %d", id, adjust);
1287 c->remote_window += adjust;
1291 * Stops listening for channels, and removes any unix domain sockets that we
1296 channel_stop_listening()
1299 for (i = 0; i < channels_alloc; i++) {
1300 switch (channels[i].type) {
1301 case SSH_CHANNEL_AUTH_SOCKET:
1302 close(channels[i].sock);
1303 remove(channels[i].path);
1306 case SSH_CHANNEL_PORT_LISTENER:
1307 case SSH_CHANNEL_X11_LISTENER:
1308 close(channels[i].sock);
1318 * Closes the sockets/fds of all channels. This is used to close extra file
1319 * descriptors after a fork.
1326 for (i = 0; i < channels_alloc; i++)
1327 if (channels[i].type != SSH_CHANNEL_FREE)
1328 channel_close_fds(&channels[i]);
1331 /* Returns the maximum file descriptor number used by the channels. */
1336 return channel_max_fd_value;
1339 /* Returns true if any channel is still open. */
1342 channel_still_open()
1345 for (i = 0; i < channels_alloc; i++)
1346 switch (channels[i].type) {
1347 case SSH_CHANNEL_FREE:
1348 case SSH_CHANNEL_X11_LISTENER:
1349 case SSH_CHANNEL_PORT_LISTENER:
1350 case SSH_CHANNEL_CLOSED:
1351 case SSH_CHANNEL_AUTH_SOCKET:
1353 case SSH_CHANNEL_LARVAL:
1355 fatal("cannot happen: SSH_CHANNEL_LARVAL");
1357 case SSH_CHANNEL_OPENING:
1358 case SSH_CHANNEL_OPEN:
1359 case SSH_CHANNEL_X11_OPEN:
1361 case SSH_CHANNEL_INPUT_DRAINING:
1362 case SSH_CHANNEL_OUTPUT_DRAINING:
1364 fatal("cannot happen: OUT_DRAIN");
1367 fatal("channel_still_open: bad channel type %d", channels[i].type);
1374 * Returns a message describing the currently open forwarded connections,
1375 * suitable for sending to the client. The message contains crlf pairs for
1380 channel_open_message()
1386 buffer_init(&buffer);
1387 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
1388 buffer_append(&buffer, buf, strlen(buf));
1389 for (i = 0; i < channels_alloc; i++) {
1390 Channel *c = &channels[i];
1392 case SSH_CHANNEL_FREE:
1393 case SSH_CHANNEL_X11_LISTENER:
1394 case SSH_CHANNEL_PORT_LISTENER:
1395 case SSH_CHANNEL_CLOSED:
1396 case SSH_CHANNEL_AUTH_SOCKET:
1398 case SSH_CHANNEL_LARVAL:
1399 case SSH_CHANNEL_OPENING:
1400 case SSH_CHANNEL_OPEN:
1401 case SSH_CHANNEL_X11_OPEN:
1402 case SSH_CHANNEL_INPUT_DRAINING:
1403 case SSH_CHANNEL_OUTPUT_DRAINING:
1404 snprintf(buf, sizeof buf, " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
1405 c->self, c->remote_name,
1406 c->type, c->remote_id,
1407 c->istate, buffer_len(&c->input),
1408 c->ostate, buffer_len(&c->output),
1410 buffer_append(&buffer, buf, strlen(buf));
1413 fatal("channel_open_message: bad channel type %d", c->type);
1417 buffer_append(&buffer, "\0", 1);
1418 cp = xstrdup(buffer_ptr(&buffer));
1419 buffer_free(&buffer);
1424 * Initiate forwarding of connections to local port "port" through the secure
1425 * channel to host:port from remote side.
1429 channel_request_local_forwarding(u_short port, const char *host,
1430 u_short host_port, int gateway_ports)
1432 int success, ch, sock, on = 1;
1433 struct addrinfo hints, *ai, *aitop;
1434 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1435 struct linger linger;
1437 if (strlen(host) > sizeof(channels[0].path) - 1)
1438 packet_disconnect("Forward host name too long.");
1441 * getaddrinfo returns a loopback address if the hostname is
1442 * set to NULL and hints.ai_flags is not AI_PASSIVE
1444 memset(&hints, 0, sizeof(hints));
1445 hints.ai_family = IPv4or6;
1446 hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
1447 hints.ai_socktype = SOCK_STREAM;
1448 snprintf(strport, sizeof strport, "%d", port);
1449 if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
1450 packet_disconnect("getaddrinfo: fatal error");
1453 for (ai = aitop; ai; ai = ai->ai_next) {
1454 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1456 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1457 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1458 error("channel_request_local_forwarding: getnameinfo failed");
1461 /* Create a port to listen for the host. */
1462 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1464 /* this is no error since kernel may not support ipv6 */
1465 verbose("socket: %.100s", strerror(errno));
1469 * Set socket options. We would like the socket to disappear
1470 * as soon as it has been closed for whatever reason.
1472 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
1474 linger.l_linger = 5;
1475 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
1476 debug("Local forwarding listening on %s port %s.", ntop, strport);
1478 /* Bind the socket to the address. */
1479 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1480 /* address can be in use ipv6 address is already bound */
1482 error("bind: %.100s", strerror(errno));
1484 verbose("bind: %.100s", strerror(errno));
1489 /* Start listening for connections on the socket. */
1490 if (listen(sock, 5) < 0) {
1491 error("listen: %.100s", strerror(errno));
1495 /* Allocate a channel number for the socket. */
1497 "port listener", SSH_CHANNEL_PORT_LISTENER,
1499 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1500 0, xstrdup("port listener"));
1501 strlcpy(channels[ch].path, host, sizeof(channels[ch].path));
1502 channels[ch].host_port = host_port;
1503 channels[ch].listening_port = port;
1507 packet_disconnect("cannot listen port: %d", port);
1508 freeaddrinfo(aitop);
1512 * Initiate forwarding of connections to port "port" on remote host through
1513 * the secure channel to host:port from local side.
1517 channel_request_remote_forwarding(u_short listen_port, const char *host_to_connect,
1518 u_short port_to_connect)
1521 /* Record locally that connection to this host/port is permitted. */
1522 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
1523 fatal("channel_request_remote_forwarding: too many forwards");
1525 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
1526 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
1527 permitted_opens[num_permitted_opens].listen_port = listen_port;
1528 num_permitted_opens++;
1530 /* Send the forward request to the remote side. */
1532 const char *address_to_bind = "0.0.0.0";
1533 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1534 packet_put_cstring("tcpip-forward");
1535 packet_put_char(0); /* boolean: want reply */
1536 packet_put_cstring(address_to_bind);
1537 packet_put_int(listen_port);
1539 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1540 packet_put_int(listen_port);
1541 packet_put_cstring(host_to_connect);
1542 packet_put_int(port_to_connect);
1544 packet_write_wait();
1546 * Wait for response from the remote side. It will send a disconnect
1547 * message on failure, and we will never see it here.
1549 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1554 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
1555 * listening for the port, and sends back a success reply (or disconnect
1556 * message if there was an error). This never returns if there was an error.
1560 channel_input_port_forward_request(int is_root, int gateway_ports)
1562 u_short port, host_port;
1565 /* Get arguments from the packet. */
1566 port = packet_get_int();
1567 hostname = packet_get_string(NULL);
1568 host_port = packet_get_int();
1571 * Check that an unprivileged user is not trying to forward a
1574 if (port < IPPORT_RESERVED && !is_root)
1575 packet_disconnect("Requested forwarding of port %d but user is not root.",
1578 * Initiate forwarding,
1580 channel_request_local_forwarding(port, hostname, host_port, gateway_ports);
1582 /* Free the argument string. */
1586 /* XXX move to aux.c */
1588 channel_connect_to(const char *host, u_short host_port)
1590 struct addrinfo hints, *ai, *aitop;
1591 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1595 memset(&hints, 0, sizeof(hints));
1596 hints.ai_family = IPv4or6;
1597 hints.ai_socktype = SOCK_STREAM;
1598 snprintf(strport, sizeof strport, "%d", host_port);
1599 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
1600 error("%.100s: unknown host (%s)", host, gai_strerror(gaierr));
1603 for (ai = aitop; ai; ai = ai->ai_next) {
1604 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1606 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1607 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1608 error("channel_connect_to: getnameinfo failed");
1611 /* Create the socket. */
1612 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1614 error("socket: %.100s", strerror(errno));
1617 /* Connect to the host/port. */
1618 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1619 error("connect %.100s port %s: %.100s", ntop, strport,
1622 continue; /* fail -- try next */
1624 break; /* success */
1627 freeaddrinfo(aitop);
1629 error("connect %.100s port %d: failed.", host, host_port);
1637 * This is called after receiving PORT_OPEN message. This attempts to
1638 * connect to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION
1639 * or CHANNEL_OPEN_FAILURE.
1643 channel_input_port_open(int type, int plen)
1646 char *host, *originator_string;
1647 int remote_channel, sock = -1, newch, i, denied;
1648 unsigned int host_len, originator_len;
1650 /* Get remote channel number. */
1651 remote_channel = packet_get_int();
1653 /* Get host name to connect to. */
1654 host = packet_get_string(&host_len);
1656 /* Get port to connect to. */
1657 host_port = packet_get_int();
1659 /* Get remote originator name. */
1660 if (have_hostname_in_open) {
1661 originator_string = packet_get_string(&originator_len);
1662 originator_len += 4; /* size of packet_int */
1664 originator_string = xstrdup("unknown (remote did not supply name)");
1665 originator_len = 0; /* no originator supplied */
1668 packet_integrity_check(plen,
1669 4 + 4 + host_len + 4 + originator_len, SSH_MSG_PORT_OPEN);
1671 /* Check if opening that port is permitted. */
1673 if (!all_opens_permitted) {
1674 /* Go trough all permitted ports. */
1675 for (i = 0; i < num_permitted_opens; i++)
1676 if (permitted_opens[i].port_to_connect == host_port &&
1677 strcmp(permitted_opens[i].host_to_connect, host) == 0)
1680 /* Check if we found the requested port among those permitted. */
1681 if (i >= num_permitted_opens) {
1682 /* The port is not permitted. */
1683 log("Received request to connect to %.100s:%d, but the request was denied.",
1688 sock = denied ? -1 : channel_connect_to(host, host_port);
1690 /* Allocate a channel for this connection. */
1691 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, originator_string);
1692 channels[newch].remote_id = remote_channel;
1694 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1695 packet_put_int(remote_channel);
1696 packet_put_int(newch);
1699 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1700 packet_put_int(remote_channel);
1707 * Creates an internet domain socket for listening for X11 connections.
1708 * Returns a suitable value for the DISPLAY variable, or NULL if an error
1712 #define NUM_SOCKS 10
1715 x11_create_display_inet(int screen_number, int x11_display_offset)
1717 int display_number, sock;
1719 struct addrinfo hints, *ai, *aitop;
1720 char strport[NI_MAXSERV];
1721 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
1723 char hostname[MAXHOSTNAMELEN];
1725 for (display_number = x11_display_offset;
1726 display_number < MAX_DISPLAYS;
1728 port = 6000 + display_number;
1729 memset(&hints, 0, sizeof(hints));
1730 hints.ai_family = IPv4or6;
1731 hints.ai_flags = AI_PASSIVE; /* XXX loopback only ? */
1732 hints.ai_socktype = SOCK_STREAM;
1733 snprintf(strport, sizeof strport, "%d", port);
1734 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
1735 error("getaddrinfo: %.100s", gai_strerror(gaierr));
1738 for (ai = aitop; ai; ai = ai->ai_next) {
1739 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1741 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1743 if (errno != EINVAL) {
1744 error("socket: %.100s", strerror(errno));
1747 debug("Socket family %d not supported [X11 disp create]", ai->ai_family);
1751 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1752 debug("bind port %d: %.100s", port, strerror(errno));
1753 shutdown(sock, SHUT_RDWR);
1759 for (n = 0; n < num_socks; n++) {
1760 shutdown(socks[n], SHUT_RDWR);
1766 socks[num_socks++] = sock;
1767 #ifndef DONT_TRY_OTHER_AF
1768 if (num_socks == NUM_SOCKS)
1777 if (display_number >= MAX_DISPLAYS) {
1778 error("Failed to allocate internet-domain X11 display socket.");
1781 /* Start listening for connections on the socket. */
1782 for (n = 0; n < num_socks; n++) {
1784 if (listen(sock, 5) < 0) {
1785 error("listen: %.100s", strerror(errno));
1786 shutdown(sock, SHUT_RDWR);
1792 /* Set up a suitable value for the DISPLAY variable. */
1794 if (gethostname(hostname, sizeof(hostname)) < 0)
1795 fatal("gethostname: %.100s", strerror(errno));
1797 #ifdef IPADDR_IN_DISPLAY
1799 * HPUX detects the local hostname in the DISPLAY variable and tries
1800 * to set up a shared memory connection to the server, which it
1801 * incorrectly supposes to be local.
1803 * The workaround - as used in later $$H and other programs - is
1804 * is to set display to the host's IP address.
1808 struct in_addr my_addr;
1810 he = gethostbyname(hostname);
1812 error("[X11-broken-fwd-hostname-workaround] Could not get "
1813 "IP address for hostname %s.", hostname);
1815 packet_send_debug("[X11-broken-fwd-hostname-workaround]"
1816 "Could not get IP address for hostname %s.", hostname);
1818 shutdown(sock, SHUT_RDWR);
1824 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
1826 /* Set DISPLAY to <ip address>:screen.display */
1827 snprintf(display, sizeof(display), "%.50s:%d.%d", inet_ntoa(my_addr),
1828 display_number, screen_number);
1830 #else /* IPADDR_IN_DISPLAY */
1831 /* Just set DISPLAY to hostname:screen.display */
1832 snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
1833 display_number, screen_number);
1834 #endif /* IPADDR_IN_DISPLAY */
1836 /* Allocate a channel for each socket. */
1837 for (n = 0; n < num_socks; n++) {
1839 (void) channel_new("x11 listener",
1840 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
1841 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
1842 0, xstrdup("X11 inet listener"));
1845 /* Return a suitable value for the DISPLAY environment variable. */
1846 return xstrdup(display);
1850 #define X_UNIX_PATH "/tmp/.X11-unix/X"
1855 connect_local_xsocket(unsigned int dnr)
1857 static const char *const x_sockets[] = {
1859 "/var/X/.X11-unix/X" "%u",
1860 "/usr/spool/sockets/X11/" "%u",
1864 struct sockaddr_un addr;
1865 const char *const * path;
1867 for (path = x_sockets; *path; ++path) {
1868 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1870 error("socket: %.100s", strerror(errno));
1871 memset(&addr, 0, sizeof(addr));
1872 addr.sun_family = AF_UNIX;
1873 snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
1874 if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
1878 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
1883 x11_connect_display(void)
1885 int display_number, sock = 0;
1886 const char *display;
1887 char buf[1024], *cp;
1888 struct addrinfo hints, *ai, *aitop;
1889 char strport[NI_MAXSERV];
1892 /* Try to open a socket for the local X server. */
1893 display = getenv("DISPLAY");
1895 error("DISPLAY not set.");
1899 * Now we decode the value of the DISPLAY variable and make a
1900 * connection to the real X server.
1904 * Check if it is a unix domain socket. Unix domain displays are in
1905 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
1907 if (strncmp(display, "unix:", 5) == 0 ||
1908 display[0] == ':') {
1909 /* Connect to the unix domain socket. */
1910 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
1911 error("Could not parse display number from DISPLAY: %.100s",
1915 /* Create a socket. */
1916 sock = connect_local_xsocket(display_number);
1920 /* OK, we now have a connection to the display. */
1924 * Connect to an inet socket. The DISPLAY value is supposedly
1925 * hostname:d[.s], where hostname may also be numeric IP address.
1927 strncpy(buf, display, sizeof(buf));
1928 buf[sizeof(buf) - 1] = 0;
1929 cp = strchr(buf, ':');
1931 error("Could not find ':' in DISPLAY: %.100s", display);
1935 /* buf now contains the host name. But first we parse the display number. */
1936 if (sscanf(cp + 1, "%d", &display_number) != 1) {
1937 error("Could not parse display number from DISPLAY: %.100s",
1942 /* Look up the host address */
1943 memset(&hints, 0, sizeof(hints));
1944 hints.ai_family = IPv4or6;
1945 hints.ai_socktype = SOCK_STREAM;
1946 snprintf(strport, sizeof strport, "%d", 6000 + display_number);
1947 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
1948 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
1951 for (ai = aitop; ai; ai = ai->ai_next) {
1952 /* Create a socket. */
1953 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1955 debug("socket: %.100s", strerror(errno));
1958 /* Connect it to the display. */
1959 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1960 debug("connect %.100s port %d: %.100s", buf,
1961 6000 + display_number, strerror(errno));
1968 freeaddrinfo(aitop);
1970 error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
1978 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
1979 * the remote channel number. We should do whatever we want, and respond
1980 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
1984 x11_input_open(int type, int plen)
1986 int remote_channel, sock = 0, newch;
1988 unsigned int remote_len;
1990 /* Get remote channel number. */
1991 remote_channel = packet_get_int();
1993 /* Get remote originator name. */
1994 if (have_hostname_in_open) {
1995 remote_host = packet_get_string(&remote_len);
1998 remote_host = xstrdup("unknown (remote did not supply name)");
2002 debug("Received X11 open request.");
2003 packet_integrity_check(plen, 4 + remote_len, SSH_SMSG_X11_OPEN);
2005 /* Obtain a connection to the real X display. */
2006 sock = x11_connect_display();
2008 /* Send refusal to the remote host. */
2009 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2010 packet_put_int(remote_channel);
2013 /* Allocate a channel for this connection. */
2014 newch = channel_allocate(
2015 (x11_saved_proto == NULL) ?
2016 SSH_CHANNEL_OPEN : SSH_CHANNEL_X11_OPEN,
2018 channels[newch].remote_id = remote_channel;
2020 /* Send a confirmation to the remote host. */
2021 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2022 packet_put_int(remote_channel);
2023 packet_put_int(newch);
2029 * Requests forwarding of X11 connections, generates fake authentication
2030 * data, and enables authentication spoofing.
2034 x11_request_forwarding_with_spoofing(int client_session_id,
2035 const char *proto, const char *data)
2037 unsigned int data_len = (unsigned int) strlen(data) / 2;
2038 unsigned int i, value;
2044 cp = getenv("DISPLAY");
2046 cp = strchr(cp, ':');
2048 cp = strchr(cp, '.');
2050 screen_number = atoi(cp + 1);
2054 /* Save protocol name. */
2055 x11_saved_proto = xstrdup(proto);
2058 * Extract real authentication data and generate fake data of the
2061 x11_saved_data = xmalloc(data_len);
2062 x11_fake_data = xmalloc(data_len);
2063 for (i = 0; i < data_len; i++) {
2064 if (sscanf(data + 2 * i, "%2x", &value) != 1)
2065 fatal("x11_request_forwarding: bad authentication data: %.100s", data);
2067 rand = arc4random();
2068 x11_saved_data[i] = value;
2069 x11_fake_data[i] = rand & 0xff;
2072 x11_saved_data_len = data_len;
2073 x11_fake_data_len = data_len;
2075 /* Convert the fake data into hex. */
2076 new_data = xmalloc(2 * data_len + 1);
2077 for (i = 0; i < data_len; i++)
2078 sprintf(new_data + 2 * i, "%02x", (unsigned char) x11_fake_data[i]);
2080 /* Send the request packet. */
2082 channel_request_start(client_session_id, "x11-req", 0);
2083 packet_put_char(0); /* XXX bool single connection */
2085 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
2087 packet_put_cstring(proto);
2088 packet_put_cstring(new_data);
2089 packet_put_int(screen_number);
2091 packet_write_wait();
2095 /* Sends a message to the server to request authentication fd forwarding. */
2098 auth_request_forwarding()
2100 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
2102 packet_write_wait();
2106 * Returns the name of the forwarded authentication socket. Returns NULL if
2107 * there is no forwarded authentication socket. The returned value points to
2112 auth_get_socket_name()
2114 return channel_forwarded_auth_socket_name;
2117 /* removes the agent forwarding socket */
2120 cleanup_socket(void)
2122 remove(channel_forwarded_auth_socket_name);
2123 rmdir(channel_forwarded_auth_socket_dir);
2127 * This is called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
2128 * This starts forwarding authentication requests.
2132 auth_input_request_forwarding(struct passwd * pw)
2135 struct sockaddr_un sunaddr;
2137 if (auth_get_socket_name() != NULL)
2138 fatal("Protocol error: authentication forwarding requested twice.");
2140 /* Temporarily drop privileged uid for mkdir/bind. */
2141 temporarily_use_uid(pw->pw_uid);
2143 /* Allocate a buffer for the socket name, and format the name. */
2144 channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
2145 channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
2146 strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
2148 /* Create private directory for socket */
2149 if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL) {
2150 packet_send_debug("Agent forwarding disabled: mkdtemp() failed: %.100s",
2153 xfree(channel_forwarded_auth_socket_name);
2154 xfree(channel_forwarded_auth_socket_dir);
2155 channel_forwarded_auth_socket_name = NULL;
2156 channel_forwarded_auth_socket_dir = NULL;
2159 snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME, "%s/agent.%d",
2160 channel_forwarded_auth_socket_dir, (int) getpid());
2162 if (atexit(cleanup_socket) < 0) {
2165 packet_disconnect("socket: %.100s", strerror(saved));
2167 /* Create the socket. */
2168 sock = socket(AF_UNIX, SOCK_STREAM, 0);
2170 packet_disconnect("socket: %.100s", strerror(errno));
2172 /* Bind it to the name. */
2173 memset(&sunaddr, 0, sizeof(sunaddr));
2174 sunaddr.sun_family = AF_UNIX;
2175 strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
2176 sizeof(sunaddr.sun_path));
2178 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
2179 packet_disconnect("bind: %.100s", strerror(errno));
2181 /* Restore the privileged uid. */
2184 /* Start listening on the socket. */
2185 if (listen(sock, 5) < 0)
2186 packet_disconnect("listen: %.100s", strerror(errno));
2188 /* Allocate a channel for the authentication agent socket. */
2189 newch = channel_allocate(SSH_CHANNEL_AUTH_SOCKET, sock,
2190 xstrdup("auth socket"));
2191 strlcpy(channels[newch].path, channel_forwarded_auth_socket_name,
2192 sizeof(channels[newch].path));
2196 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
2199 auth_input_open_request(int type, int plen)
2201 int remch, sock, newch;
2204 packet_integrity_check(plen, 4, type);
2206 /* Read the remote channel number from the message. */
2207 remch = packet_get_int();
2210 * Get a connection to the local authentication agent (this may again
2213 sock = ssh_get_authentication_socket();
2216 * If we could not connect the agent, send an error message back to
2217 * the server. This should never happen unless the agent dies,
2218 * because authentication forwarding is only enabled if we have an
2222 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2223 packet_put_int(remch);
2227 debug("Forwarding authentication connection.");
2230 * Dummy host name. This will be freed when the channel is freed; it
2231 * will still be valid in the packet_put_string below since the
2232 * channel cannot yet be freed at that point.
2234 dummyname = xstrdup("authentication agent connection");
2236 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
2237 channels[newch].remote_id = remch;
2239 /* Send a confirmation to the remote host. */
2240 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2241 packet_put_int(remch);
2242 packet_put_int(newch);
2247 channel_start_open(int id)
2249 Channel *c = channel_lookup(id);
2251 log("channel_open: %d: bad id", id);
2254 debug("send channel open %d", id);
2255 packet_start(SSH2_MSG_CHANNEL_OPEN);
2256 packet_put_cstring(c->ctype);
2257 packet_put_int(c->self);
2258 packet_put_int(c->local_window);
2259 packet_put_int(c->local_maxpacket);
2262 channel_open(int id)
2265 channel_start_open(id);
2269 channel_request(int id, char *service, int wantconfirm)
2271 channel_request_start(id, service, wantconfirm);
2273 debug("channel request %d: %s", id, service) ;
2276 channel_request_start(int id, char *service, int wantconfirm)
2278 Channel *c = channel_lookup(id);
2280 log("channel_request: %d: bad id", id);
2283 packet_start(SSH2_MSG_CHANNEL_REQUEST);
2284 packet_put_int(c->remote_id);
2285 packet_put_cstring(service);
2286 packet_put_char(wantconfirm);
2289 channel_register_callback(int id, int mtype, channel_callback_fn *fn, void *arg)
2291 Channel *c = channel_lookup(id);
2293 log("channel_register_callback: %d: bad id", id);
2296 c->cb_event = mtype;
2301 channel_register_cleanup(int id, channel_callback_fn *fn)
2303 Channel *c = channel_lookup(id);
2305 log("channel_register_cleanup: %d: bad id", id);
2308 c->dettach_user = fn;
2311 channel_cancel_cleanup(int id)
2313 Channel *c = channel_lookup(id);
2315 log("channel_cancel_cleanup: %d: bad id", id);
2318 c->dettach_user = NULL;
2321 channel_register_filter(int id, channel_filter_fn *fn)
2323 Channel *c = channel_lookup(id);
2325 log("channel_register_filter: %d: bad id", id);
2328 c->input_filter = fn;
2332 channel_set_fds(int id, int rfd, int wfd, int efd, int extusage)
2334 Channel *c = channel_lookup(id);
2335 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
2336 fatal("channel_activate for non-larval channel %d.", id);
2338 channel_register_fds(c, rfd, wfd, efd, extusage);
2339 c->type = SSH_CHANNEL_OPEN;
2340 /* XXX window size? */
2341 c->local_window = c->local_window_max = c->local_maxpacket/2;
2342 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2343 packet_put_int(c->remote_id);
2344 packet_put_int(c->local_window);