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 window/packet sizes for tcp/x11-fwd-channel */
44 #define CHAN_TCP_WINDOW_DEFAULT (8*1024)
45 #define CHAN_TCP_PACKET_DEFAULT (CHAN_TCP_WINDOW_DEFAULT/2)
46 #define CHAN_X11_WINDOW_DEFAULT (4*1024)
47 #define CHAN_X11_PACKET_DEFAULT (CHAN_X11_WINDOW_DEFAULT/2)
50 * Pointer to an array containing all allocated channels. The array is
51 * dynamically extended as needed.
53 static Channel *channels = NULL;
56 * Size of the channel array. All slots of the array must always be
57 * initialized (at least the type field); unused slots are marked with type
60 static int channels_alloc = 0;
63 * Maximum file descriptor value used in any of the channels. This is
64 * updated in channel_allocate.
66 static int channel_max_fd_value = 0;
68 /* Name and directory of socket for authentication agent forwarding. */
69 static char *channel_forwarded_auth_socket_name = NULL;
70 static char *channel_forwarded_auth_socket_dir = NULL;
72 /* Saved X11 authentication protocol name. */
73 char *x11_saved_proto = NULL;
75 /* Saved X11 authentication data. This is the real data. */
76 char *x11_saved_data = NULL;
77 unsigned int x11_saved_data_len = 0;
80 * Fake X11 authentication data. This is what the server will be sending us;
81 * we should replace any occurrences of this by the real data.
83 char *x11_fake_data = NULL;
84 unsigned int x11_fake_data_len;
87 * Data structure for storing which hosts are permitted for forward requests.
88 * The local sides of any remote forwards are stored in this array to prevent
89 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
90 * network (which might be behind a firewall).
93 char *host_to_connect; /* Connect to 'host'. */
94 u_short port_to_connect; /* Connect to 'port'. */
95 u_short listen_port; /* Remote side should listen port number. */
98 /* List of all permitted host/port pairs to connect. */
99 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
100 /* Number of permitted host/port pairs in the array. */
101 static int num_permitted_opens = 0;
103 * If this is true, all opens are permitted. This is the case on the server
104 * on which we have to trust the client anyway, and the user could do
105 * anything after logging in anyway.
107 static int all_opens_permitted = 0;
109 /* This is set to true if both sides support SSH_PROTOFLAG_HOST_IN_FWD_OPEN. */
110 static int have_hostname_in_open = 0;
112 /* Sets specific protocol options. */
115 channel_set_options(int hostname_in_open)
117 have_hostname_in_open = hostname_in_open;
121 * Permits opening to any host/port in SSH_MSG_PORT_OPEN. This is usually
122 * called by the server, because the user could connect to any port anyway,
123 * and the server has no way to know but to trust the client anyway.
127 channel_permit_all_opens()
129 all_opens_permitted = 1;
132 /* lookup channel by id */
135 channel_lookup(int id)
138 if (id < 0 && id > channels_alloc) {
139 log("channel_lookup: %d: bad id", id);
143 if (c->type == SSH_CHANNEL_FREE) {
144 log("channel_lookup: %d: bad id: channel free", id);
154 val = fcntl(fd, F_GETFL, 0);
156 error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
159 if (val & O_NONBLOCK)
161 debug("fd %d setting O_NONBLOCK", fd);
163 if (fcntl(fd, F_SETFL, val) == -1)
164 error("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd, strerror(errno));
168 * Register filedescriptors for a channel, used when allocating a channel or
169 * when the channel consumer/producer is ready, e.g. shell exec'd
173 channel_register_fds(Channel *c, int rfd, int wfd, int efd, int extusage)
175 /* Update the maximum file descriptor value. */
176 if (rfd > channel_max_fd_value)
177 channel_max_fd_value = rfd;
178 if (wfd > channel_max_fd_value)
179 channel_max_fd_value = wfd;
180 if (efd > channel_max_fd_value)
181 channel_max_fd_value = efd;
182 /* XXX set close-on-exec -markus */
186 c->sock = (rfd == wfd) ? rfd : -1;
188 c->extended_usage = extusage;
198 * Allocate a new channel object and set its type and socket. This will cause
199 * remote_name to be freed.
203 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
204 int window, int maxpack, int extusage, char *remote_name)
209 /* Do initial allocation if this is the first call. */
210 if (channels_alloc == 0) {
213 channels = xmalloc(channels_alloc * sizeof(Channel));
214 for (i = 0; i < channels_alloc; i++)
215 channels[i].type = SSH_CHANNEL_FREE;
217 * Kludge: arrange a call to channel_stop_listening if we
218 * terminate with fatal().
220 fatal_add_cleanup((void (*) (void *)) channel_stop_listening, NULL);
222 /* Try to find a free slot where to put the new channel. */
223 for (found = -1, i = 0; i < channels_alloc; i++)
224 if (channels[i].type == SSH_CHANNEL_FREE) {
225 /* Found a free slot. */
230 /* There are no free slots. Take last+1 slot and expand the array. */
231 found = channels_alloc;
232 channels_alloc += 10;
233 debug("channel: expanding %d", channels_alloc);
234 channels = xrealloc(channels, channels_alloc * sizeof(Channel));
235 for (i = found; i < channels_alloc; i++)
236 channels[i].type = SSH_CHANNEL_FREE;
238 /* Initialize and return new channel number. */
239 c = &channels[found];
240 buffer_init(&c->input);
241 buffer_init(&c->output);
242 buffer_init(&c->extended);
243 chan_init_iostates(c);
244 channel_register_fds(c, rfd, wfd, efd, extusage);
248 c->local_window = window;
249 c->local_window_max = window;
250 c->local_consumed = 0;
251 c->local_maxpacket = maxpack;
253 c->remote_name = remote_name;
254 c->remote_window = 0;
255 c->remote_maxpacket = 0;
259 c->dettach_user = NULL;
260 debug("channel %d: new [%s]", found, remote_name);
263 /* old interface XXX */
265 channel_allocate(int type, int sock, char *remote_name)
267 return channel_new("", type, sock, sock, -1, 0, 0, 0, remote_name);
271 /* Close all channel fd/socket. */
274 channel_close_fds(Channel *c)
294 /* Free the channel and close its fd/socket. */
299 Channel *c = channel_lookup(id);
301 packet_disconnect("channel free: bad local channel %d", id);
302 debug("channel_free: channel %d: status: %s", id, channel_open_message());
303 if (c->dettach_user != NULL) {
304 debug("channel_free: channel %d: dettaching channel user", id);
305 c->dettach_user(c->self, NULL);
308 shutdown(c->sock, SHUT_RDWR);
309 channel_close_fds(c);
310 buffer_free(&c->input);
311 buffer_free(&c->output);
312 buffer_free(&c->extended);
313 c->type = SSH_CHANNEL_FREE;
314 if (c->remote_name) {
315 xfree(c->remote_name);
316 c->remote_name = NULL;
321 * 'channel_pre*' are called just before select() to add any bits relevant to
322 * channels in the select bitmasks.
325 * 'channel_post*': perform any appropriate operations for channels which
326 * have events pending.
328 typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
329 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
330 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
333 channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
335 FD_SET(c->sock, readset);
339 channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
341 if (buffer_len(&c->input) < packet_get_maxsize())
342 FD_SET(c->sock, readset);
343 if (buffer_len(&c->output) > 0)
344 FD_SET(c->sock, writeset);
348 channel_pre_open_15(Channel *c, fd_set * readset, fd_set * writeset)
350 /* test whether sockets are 'alive' for read/write */
351 if (c->istate == CHAN_INPUT_OPEN)
352 if (buffer_len(&c->input) < packet_get_maxsize())
353 FD_SET(c->sock, readset);
354 if (c->ostate == CHAN_OUTPUT_OPEN ||
355 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
356 if (buffer_len(&c->output) > 0) {
357 FD_SET(c->sock, writeset);
358 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
365 channel_pre_open_20(Channel *c, fd_set * readset, fd_set * writeset)
367 if (c->istate == CHAN_INPUT_OPEN &&
368 c->remote_window > 0 &&
369 buffer_len(&c->input) < c->remote_window)
370 FD_SET(c->rfd, readset);
371 if (c->ostate == CHAN_OUTPUT_OPEN ||
372 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
373 if (buffer_len(&c->output) > 0) {
374 FD_SET(c->wfd, writeset);
375 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
379 /** XXX check close conditions, too */
381 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
382 buffer_len(&c->extended) > 0)
383 FD_SET(c->efd, writeset);
384 else if (c->extended_usage == CHAN_EXTENDED_READ &&
385 buffer_len(&c->extended) < c->remote_window)
386 FD_SET(c->efd, readset);
391 channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
393 if (buffer_len(&c->input) == 0) {
394 packet_start(SSH_MSG_CHANNEL_CLOSE);
395 packet_put_int(c->remote_id);
397 c->type = SSH_CHANNEL_CLOSED;
398 debug("Closing channel %d after input drain.", c->self);
403 channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
405 if (buffer_len(&c->output) == 0)
406 channel_free(c->self);
408 FD_SET(c->sock, writeset);
412 * This is a special state for X11 authentication spoofing. An opened X11
413 * connection (when authentication spoofing is being done) remains in this
414 * state until the first packet has been completely read. The authentication
415 * data in that packet is then substituted by the real data if it matches the
416 * fake data, and the channel is put into normal mode.
417 * XXX All this happens at the client side.
420 x11_open_helper(Channel *c)
423 unsigned int proto_len, data_len;
425 /* Check if the fixed size part of the packet is in buffer. */
426 if (buffer_len(&c->output) < 12)
429 /* Parse the lengths of variable-length fields. */
430 ucp = (unsigned char *) buffer_ptr(&c->output);
431 if (ucp[0] == 0x42) { /* Byte order MSB first. */
432 proto_len = 256 * ucp[6] + ucp[7];
433 data_len = 256 * ucp[8] + ucp[9];
434 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
435 proto_len = ucp[6] + 256 * ucp[7];
436 data_len = ucp[8] + 256 * ucp[9];
438 debug("Initial X11 packet contains bad byte order byte: 0x%x",
443 /* Check if the whole packet is in buffer. */
444 if (buffer_len(&c->output) <
445 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
448 /* Check if authentication protocol matches. */
449 if (proto_len != strlen(x11_saved_proto) ||
450 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
451 debug("X11 connection uses different authentication protocol.");
454 /* Check if authentication data matches our fake data. */
455 if (data_len != x11_fake_data_len ||
456 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
457 x11_fake_data, x11_fake_data_len) != 0) {
458 debug("X11 auth data does not match fake data.");
461 /* Check fake data length */
462 if (x11_fake_data_len != x11_saved_data_len) {
463 error("X11 fake_data_len %d != saved_data_len %d",
464 x11_fake_data_len, x11_saved_data_len);
468 * Received authentication protocol and data match
469 * our fake data. Substitute the fake data with real
472 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
473 x11_saved_data, x11_saved_data_len);
478 channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
480 int ret = x11_open_helper(c);
482 /* Start normal processing for the channel. */
483 c->type = SSH_CHANNEL_OPEN;
484 channel_pre_open_13(c, readset, writeset);
485 } else if (ret == -1) {
487 * We have received an X11 connection that has bad
488 * authentication information.
490 log("X11 connection rejected because of wrong authentication.\r\n");
491 buffer_clear(&c->input);
492 buffer_clear(&c->output);
495 c->type = SSH_CHANNEL_CLOSED;
496 packet_start(SSH_MSG_CHANNEL_CLOSE);
497 packet_put_int(c->remote_id);
503 channel_pre_x11_open(Channel *c, fd_set * readset, fd_set * writeset)
505 int ret = x11_open_helper(c);
507 c->type = SSH_CHANNEL_OPEN;
509 channel_pre_open_20(c, readset, writeset);
511 channel_pre_open_15(c, readset, writeset);
512 } else if (ret == -1) {
513 debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
514 chan_read_failed(c); /** force close? */
515 chan_write_failed(c);
516 debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
520 /* This is our fake X11 server socket. */
522 channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
524 struct sockaddr addr;
527 char buf[16384], *remote_hostname;
530 if (FD_ISSET(c->sock, readset)) {
531 debug("X11 connection requested.");
532 addrlen = sizeof(addr);
533 newsock = accept(c->sock, &addr, &addrlen);
535 error("accept: %.100s", strerror(errno));
538 remote_hostname = get_remote_hostname(newsock);
539 remote_port = get_peer_port(newsock);
540 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
541 remote_hostname, remote_port);
543 newch = channel_new("x11",
544 SSH_CHANNEL_OPENING, newsock, newsock, -1,
545 c->local_window_max, c->local_maxpacket,
548 packet_start(SSH2_MSG_CHANNEL_OPEN);
549 packet_put_cstring("x11");
550 packet_put_int(newch);
551 packet_put_int(c->local_window_max);
552 packet_put_int(c->local_maxpacket);
553 /* originator host and port */
554 packet_put_cstring(remote_hostname);
555 if (datafellows & SSH_BUG_X11FWD) {
556 debug("ssh2 x11 bug compat mode");
558 packet_put_int(remote_port);
562 packet_start(SSH_SMSG_X11_OPEN);
563 packet_put_int(newch);
564 if (have_hostname_in_open)
565 packet_put_string(buf, strlen(buf));
568 xfree(remote_hostname);
573 * This socket is listening for connections to a forwarded TCP/IP port.
576 channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
578 struct sockaddr addr;
581 char buf[1024], *remote_hostname;
584 if (FD_ISSET(c->sock, readset)) {
585 debug("Connection to port %d forwarding "
586 "to %.100s port %d requested.",
587 c->listening_port, c->path, c->host_port);
588 addrlen = sizeof(addr);
589 newsock = accept(c->sock, &addr, &addrlen);
591 error("accept: %.100s", strerror(errno));
594 remote_hostname = get_remote_hostname(newsock);
595 remote_port = get_peer_port(newsock);
596 snprintf(buf, sizeof buf,
597 "listen port %d for %.100s port %d, "
598 "connect from %.200s port %d",
599 c->listening_port, c->path, c->host_port,
600 remote_hostname, remote_port);
601 newch = channel_new("direct-tcpip",
602 SSH_CHANNEL_OPENING, newsock, newsock, -1,
603 c->local_window_max, c->local_maxpacket,
606 packet_start(SSH2_MSG_CHANNEL_OPEN);
607 packet_put_cstring("direct-tcpip");
608 packet_put_int(newch);
609 packet_put_int(c->local_window_max);
610 packet_put_int(c->local_maxpacket);
611 /* target host and port */
612 packet_put_string(c->path, strlen(c->path));
613 packet_put_int(c->host_port);
614 /* originator host and port */
615 packet_put_cstring(remote_hostname);
616 packet_put_int(remote_port);
619 packet_start(SSH_MSG_PORT_OPEN);
620 packet_put_int(newch);
621 packet_put_string(c->path, strlen(c->path));
622 packet_put_int(c->host_port);
623 if (have_hostname_in_open) {
624 packet_put_string(buf, strlen(buf));
628 xfree(remote_hostname);
633 * This is the authentication agent socket listening for connections from
637 channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
639 struct sockaddr addr;
643 if (FD_ISSET(c->sock, readset)) {
644 addrlen = sizeof(addr);
645 newsock = accept(c->sock, &addr, &addrlen);
647 error("accept from auth socket: %.100s", strerror(errno));
650 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
651 xstrdup("accepted auth socket"));
652 packet_start(SSH_SMSG_AGENT_OPEN);
653 packet_put_int(newch);
659 channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
665 FD_ISSET(c->rfd, readset)) {
666 len = read(c->rfd, buf, sizeof(buf));
667 if (len < 0 && (errno == EINTR || errno == EAGAIN))
670 debug("channel %d: read<=0 rfd %d len %d",
671 c->self, c->rfd, len);
673 buffer_consume(&c->output, buffer_len(&c->output));
674 c->type = SSH_CHANNEL_INPUT_DRAINING;
675 debug("Channel %d status set to input draining.", c->self);
681 buffer_append(&c->input, buf, len);
686 channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
690 /* Send buffered output data to the socket. */
692 FD_ISSET(c->wfd, writeset) &&
693 buffer_len(&c->output) > 0) {
694 len = write(c->wfd, buffer_ptr(&c->output),
695 buffer_len(&c->output));
696 if (len < 0 && (errno == EINTR || errno == EAGAIN))
700 buffer_consume(&c->output, buffer_len(&c->output));
701 debug("Channel %d status set to input draining.", c->self);
702 c->type = SSH_CHANNEL_INPUT_DRAINING;
704 chan_write_failed(c);
708 buffer_consume(&c->output, len);
709 if (compat20 && len > 0) {
710 c->local_consumed += len;
716 channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
721 /** XXX handle drain efd, too */
723 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
724 FD_ISSET(c->efd, writeset) &&
725 buffer_len(&c->extended) > 0) {
726 len = write(c->efd, buffer_ptr(&c->extended),
727 buffer_len(&c->extended));
728 debug("channel %d: written %d to efd %d",
729 c->self, len, c->efd);
731 buffer_consume(&c->extended, len);
732 c->local_consumed += len;
734 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
735 FD_ISSET(c->efd, readset)) {
736 len = read(c->efd, buf, sizeof(buf));
737 debug("channel %d: read %d from efd %d",
738 c->self, len, c->efd);
740 debug("channel %d: closing efd %d",
745 buffer_append(&c->extended, buf, len);
751 channel_check_window(Channel *c, fd_set * readset, fd_set * writeset)
753 if (!(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
754 c->local_window < c->local_window_max/2 &&
755 c->local_consumed > 0) {
756 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
757 packet_put_int(c->remote_id);
758 packet_put_int(c->local_consumed);
760 debug("channel %d: window %d sent adjust %d",
761 c->self, c->local_window,
763 c->local_window += c->local_consumed;
764 c->local_consumed = 0;
770 channel_post_open_1(Channel *c, fd_set * readset, fd_set * writeset)
772 channel_handle_rfd(c, readset, writeset);
773 channel_handle_wfd(c, readset, writeset);
777 channel_post_open_2(Channel *c, fd_set * readset, fd_set * writeset)
779 channel_handle_rfd(c, readset, writeset);
780 channel_handle_wfd(c, readset, writeset);
781 channel_handle_efd(c, readset, writeset);
782 channel_check_window(c, readset, writeset);
786 channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
789 /* Send buffered output data to the socket. */
790 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
791 len = write(c->sock, buffer_ptr(&c->output),
792 buffer_len(&c->output));
794 buffer_consume(&c->output, buffer_len(&c->output));
796 buffer_consume(&c->output, len);
801 channel_handler_init_20(void)
803 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_20;
804 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
805 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
806 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
808 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open_2;
809 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
810 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
814 channel_handler_init_13(void)
816 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
817 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
818 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
819 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
820 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
821 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
822 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
824 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open_1;
825 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
826 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
827 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
828 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
832 channel_handler_init_15(void)
834 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_15;
835 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
836 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
837 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
838 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
840 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
841 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
842 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
843 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open_1;
847 channel_handler_init(void)
850 for(i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
851 channel_pre[i] = NULL;
852 channel_post[i] = NULL;
855 channel_handler_init_20();
857 channel_handler_init_13();
859 channel_handler_init_15();
863 channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
865 static int did_init = 0;
870 channel_handler_init();
873 for (i = 0; i < channels_alloc; i++) {
875 if (c->type == SSH_CHANNEL_FREE)
877 if (ftab[c->type] == NULL)
879 (*ftab[c->type])(c, readset, writeset);
880 chan_delete_if_full_closed(c);
885 channel_prepare_select(fd_set * readset, fd_set * writeset)
887 channel_handler(channel_pre, readset, writeset);
891 channel_after_select(fd_set * readset, fd_set * writeset)
893 channel_handler(channel_post, readset, writeset);
896 /* If there is data to send to the connection, send some of it now. */
899 channel_output_poll()
904 for (i = 0; i < channels_alloc; i++) {
907 /* We are only interested in channels that can have buffered incoming data. */
909 if (c->type != SSH_CHANNEL_OPEN &&
910 c->type != SSH_CHANNEL_INPUT_DRAINING)
913 if (c->type != SSH_CHANNEL_OPEN)
915 if (c->istate != CHAN_INPUT_OPEN &&
916 c->istate != CHAN_INPUT_WAIT_DRAIN)
920 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
921 debug("channel: %d: no data after CLOSE", c->self);
925 /* Get the amount of buffered data for this channel. */
926 len = buffer_len(&c->input);
928 /* Send some data for the other side over the secure connection. */
930 if (len > c->remote_window)
931 len = c->remote_window;
932 if (len > c->remote_maxpacket)
933 len = c->remote_maxpacket;
935 if (packet_is_interactive()) {
939 /* Keep the packets at reasonable size. */
940 if (len > packet_get_maxsize()/2)
941 len = packet_get_maxsize()/2;
945 packet_start(compat20 ?
946 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
947 packet_put_int(c->remote_id);
948 packet_put_string(buffer_ptr(&c->input), len);
950 buffer_consume(&c->input, len);
951 c->remote_window -= len;
952 debug("channel %d: send data len %d", c->self, len);
954 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
956 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
958 * input-buffer is empty and read-socket shutdown:
959 * tell peer, that we will not send more data: send IEOF
963 /* Send extended data, i.e. stderr */
965 c->remote_window > 0 &&
966 (len = buffer_len(&c->extended)) > 0 &&
967 c->extended_usage == CHAN_EXTENDED_READ) {
968 if (len > c->remote_window)
969 len = c->remote_window;
970 if (len > c->remote_maxpacket)
971 len = c->remote_maxpacket;
972 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
973 packet_put_int(c->remote_id);
974 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
975 packet_put_string(buffer_ptr(&c->extended), len);
977 buffer_consume(&c->extended, len);
978 c->remote_window -= len;
984 * This is called when a packet of type CHANNEL_DATA has just been received.
985 * The message type has already been consumed, but channel number and data is
990 channel_input_data(int type, int plen)
994 unsigned int data_len;
997 /* Get the channel number and verify it. */
998 id = packet_get_int();
999 c = channel_lookup(id);
1001 packet_disconnect("Received data for nonexistent channel %d.", id);
1003 /* Ignore any data for non-open channels (might happen on close) */
1004 if (c->type != SSH_CHANNEL_OPEN &&
1005 c->type != SSH_CHANNEL_X11_OPEN)
1008 /* same for protocol 1.5 if output end is no longer open */
1009 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
1013 data = packet_get_string(&data_len);
1017 if (data_len > c->local_maxpacket) {
1018 log("channel %d: rcvd big packet %d, maxpack %d",
1019 c->self, data_len, c->local_maxpacket);
1021 if (data_len > c->local_window) {
1022 log("channel %d: rcvd too much data %d, win %d",
1023 c->self, data_len, c->local_window);
1027 c->local_window -= data_len;
1029 packet_integrity_check(plen, 4 + 4 + data_len, type);
1031 buffer_append(&c->output, data, data_len);
1035 channel_input_extended_data(int type, int plen)
1040 unsigned int data_len;
1043 /* Get the channel number and verify it. */
1044 id = packet_get_int();
1045 c = channel_lookup(id);
1048 packet_disconnect("Received extended_data for bad channel %d.", id);
1049 if (c->type != SSH_CHANNEL_OPEN) {
1050 log("channel %d: ext data for non open", id);
1053 tcode = packet_get_int();
1055 c->extended_usage != CHAN_EXTENDED_WRITE ||
1056 tcode != SSH2_EXTENDED_DATA_STDERR) {
1057 log("channel %d: bad ext data", c->self);
1060 data = packet_get_string(&data_len);
1062 if (data_len > c->local_window) {
1063 log("channel %d: rcvd too much extended_data %d, win %d",
1064 c->self, data_len, c->local_window);
1068 debug("channel %d: rcvd ext data %d", c->self, data_len);
1069 c->local_window -= data_len;
1070 buffer_append(&c->extended, data, data_len);
1076 * Returns true if no channel has too much buffered data, and false if one or
1077 * more channel is overfull.
1081 channel_not_very_much_buffered_data()
1086 for (i = 0; i < channels_alloc; i++) {
1088 if (c->type == SSH_CHANNEL_OPEN) {
1089 if (!compat20 && buffer_len(&c->input) > packet_get_maxsize()) {
1090 debug("channel %d: big input buffer %d",
1091 c->self, buffer_len(&c->input));
1094 if (buffer_len(&c->output) > packet_get_maxsize()) {
1095 debug("channel %d: big output buffer %d",
1096 c->self, buffer_len(&c->output));
1105 channel_input_ieof(int type, int plen)
1110 packet_integrity_check(plen, 4, type);
1112 id = packet_get_int();
1113 c = channel_lookup(id);
1115 packet_disconnect("Received ieof for nonexistent channel %d.", id);
1120 channel_input_close(int type, int plen)
1125 packet_integrity_check(plen, 4, type);
1127 id = packet_get_int();
1128 c = channel_lookup(id);
1130 packet_disconnect("Received close for nonexistent channel %d.", id);
1133 * Send a confirmation that we have closed the channel and no more
1134 * data is coming for it.
1136 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1137 packet_put_int(c->remote_id);
1141 * If the channel is in closed state, we have sent a close request,
1142 * and the other side will eventually respond with a confirmation.
1143 * Thus, we cannot free the channel here, because then there would be
1144 * no-one to receive the confirmation. The channel gets freed when
1145 * the confirmation arrives.
1147 if (c->type != SSH_CHANNEL_CLOSED) {
1149 * Not a closed channel - mark it as draining, which will
1150 * cause it to be freed later.
1152 buffer_consume(&c->input, buffer_len(&c->input));
1153 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1157 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1159 channel_input_oclose(int type, int plen)
1161 int id = packet_get_int();
1162 Channel *c = channel_lookup(id);
1163 packet_integrity_check(plen, 4, type);
1165 packet_disconnect("Received oclose for nonexistent channel %d.", id);
1166 chan_rcvd_oclose(c);
1170 channel_input_close_confirmation(int type, int plen)
1172 int id = packet_get_int();
1173 Channel *c = channel_lookup(id);
1177 packet_disconnect("Received close confirmation for "
1178 "out-of-range channel %d.", id);
1179 if (c->type != SSH_CHANNEL_CLOSED)
1180 packet_disconnect("Received close confirmation for "
1181 "non-closed channel %d (type %d).", id, c->type);
1182 channel_free(c->self);
1186 channel_input_open_confirmation(int type, int plen)
1192 packet_integrity_check(plen, 4 + 4, type);
1194 id = packet_get_int();
1195 c = channel_lookup(id);
1197 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1198 packet_disconnect("Received open confirmation for "
1199 "non-opening channel %d.", id);
1200 remote_id = packet_get_int();
1201 /* Record the remote channel number and mark that the channel is now open. */
1202 c->remote_id = remote_id;
1203 c->type = SSH_CHANNEL_OPEN;
1206 c->remote_window = packet_get_int();
1207 c->remote_maxpacket = packet_get_int();
1209 if (c->cb_fn != NULL && c->cb_event == type) {
1210 debug("callback start");
1211 c->cb_fn(c->self, c->cb_arg);
1212 debug("callback done");
1214 debug("channel %d: open confirm rwindow %d rmax %d", c->self,
1215 c->remote_window, c->remote_maxpacket);
1220 channel_input_open_failure(int type, int plen)
1226 packet_integrity_check(plen, 4, type);
1228 id = packet_get_int();
1229 c = channel_lookup(id);
1231 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1232 packet_disconnect("Received open failure for "
1233 "non-opening channel %d.", id);
1235 int reason = packet_get_int();
1236 char *msg = packet_get_string(NULL);
1237 char *lang = packet_get_string(NULL);
1238 log("channel_open_failure: %d: reason %d: %s", id, reason, msg);
1243 /* Free the channel. This will also close the socket. */
1248 channel_input_channel_request(int type, int plen)
1253 id = packet_get_int();
1254 c = channel_lookup(id);
1257 (c->type != SSH_CHANNEL_OPEN && c->type != SSH_CHANNEL_LARVAL))
1258 packet_disconnect("Received request for "
1259 "non-open channel %d.", id);
1260 if (c->cb_fn != NULL && c->cb_event == type) {
1261 debug("callback start");
1262 c->cb_fn(c->self, c->cb_arg);
1263 debug("callback done");
1265 char *service = packet_get_string(NULL);
1266 debug("channel: %d rcvd request for %s", c->self, service);
1267 debug("cb_fn %p cb_event %d", c->cb_fn , c->cb_event);
1273 channel_input_window_adjust(int type, int plen)
1281 /* Get the channel number and verify it. */
1282 id = packet_get_int();
1283 c = channel_lookup(id);
1285 if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
1286 log("Received window adjust for "
1287 "non-open channel %d.", id);
1290 adjust = packet_get_int();
1292 debug("channel %d: rcvd adjust %d", id, adjust);
1293 c->remote_window += adjust;
1297 * Stops listening for channels, and removes any unix domain sockets that we
1302 channel_stop_listening()
1305 for (i = 0; i < channels_alloc; i++) {
1306 switch (channels[i].type) {
1307 case SSH_CHANNEL_AUTH_SOCKET:
1308 close(channels[i].sock);
1309 remove(channels[i].path);
1312 case SSH_CHANNEL_PORT_LISTENER:
1313 case SSH_CHANNEL_X11_LISTENER:
1314 close(channels[i].sock);
1324 * Closes the sockets/fds of all channels. This is used to close extra file
1325 * descriptors after a fork.
1332 for (i = 0; i < channels_alloc; i++)
1333 if (channels[i].type != SSH_CHANNEL_FREE)
1334 channel_close_fds(&channels[i]);
1337 /* Returns the maximum file descriptor number used by the channels. */
1342 return channel_max_fd_value;
1345 /* Returns true if any channel is still open. */
1348 channel_still_open()
1351 for (i = 0; i < channels_alloc; i++)
1352 switch (channels[i].type) {
1353 case SSH_CHANNEL_FREE:
1354 case SSH_CHANNEL_X11_LISTENER:
1355 case SSH_CHANNEL_PORT_LISTENER:
1356 case SSH_CHANNEL_CLOSED:
1357 case SSH_CHANNEL_AUTH_SOCKET:
1359 case SSH_CHANNEL_LARVAL:
1361 fatal("cannot happen: SSH_CHANNEL_LARVAL");
1363 case SSH_CHANNEL_OPENING:
1364 case SSH_CHANNEL_OPEN:
1365 case SSH_CHANNEL_X11_OPEN:
1367 case SSH_CHANNEL_INPUT_DRAINING:
1368 case SSH_CHANNEL_OUTPUT_DRAINING:
1370 fatal("cannot happen: OUT_DRAIN");
1373 fatal("channel_still_open: bad channel type %d", channels[i].type);
1380 * Returns a message describing the currently open forwarded connections,
1381 * suitable for sending to the client. The message contains crlf pairs for
1386 channel_open_message()
1392 buffer_init(&buffer);
1393 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
1394 buffer_append(&buffer, buf, strlen(buf));
1395 for (i = 0; i < channels_alloc; i++) {
1396 Channel *c = &channels[i];
1398 case SSH_CHANNEL_FREE:
1399 case SSH_CHANNEL_X11_LISTENER:
1400 case SSH_CHANNEL_PORT_LISTENER:
1401 case SSH_CHANNEL_CLOSED:
1402 case SSH_CHANNEL_AUTH_SOCKET:
1404 case SSH_CHANNEL_LARVAL:
1405 case SSH_CHANNEL_OPENING:
1406 case SSH_CHANNEL_OPEN:
1407 case SSH_CHANNEL_X11_OPEN:
1408 case SSH_CHANNEL_INPUT_DRAINING:
1409 case SSH_CHANNEL_OUTPUT_DRAINING:
1410 snprintf(buf, sizeof buf, " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
1411 c->self, c->remote_name,
1412 c->type, c->remote_id,
1413 c->istate, buffer_len(&c->input),
1414 c->ostate, buffer_len(&c->output),
1416 buffer_append(&buffer, buf, strlen(buf));
1419 fatal("channel_open_message: bad channel type %d", c->type);
1423 buffer_append(&buffer, "\0", 1);
1424 cp = xstrdup(buffer_ptr(&buffer));
1425 buffer_free(&buffer);
1430 * Initiate forwarding of connections to local port "port" through the secure
1431 * channel to host:port from remote side.
1435 channel_request_local_forwarding(u_short port, const char *host,
1436 u_short host_port, int gateway_ports)
1438 int success, ch, sock, on = 1;
1439 struct addrinfo hints, *ai, *aitop;
1440 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1441 struct linger linger;
1443 if (strlen(host) > sizeof(channels[0].path) - 1)
1444 packet_disconnect("Forward host name too long.");
1447 * getaddrinfo returns a loopback address if the hostname is
1448 * set to NULL and hints.ai_flags is not AI_PASSIVE
1450 memset(&hints, 0, sizeof(hints));
1451 hints.ai_family = IPv4or6;
1452 hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
1453 hints.ai_socktype = SOCK_STREAM;
1454 snprintf(strport, sizeof strport, "%d", port);
1455 if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
1456 packet_disconnect("getaddrinfo: fatal error");
1459 for (ai = aitop; ai; ai = ai->ai_next) {
1460 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1462 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1463 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1464 error("channel_request_local_forwarding: getnameinfo failed");
1467 /* Create a port to listen for the host. */
1468 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1470 /* this is no error since kernel may not support ipv6 */
1471 verbose("socket: %.100s", strerror(errno));
1475 * Set socket options. We would like the socket to disappear
1476 * as soon as it has been closed for whatever reason.
1478 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
1480 linger.l_linger = 5;
1481 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
1482 debug("Local forwarding listening on %s port %s.", ntop, strport);
1484 /* Bind the socket to the address. */
1485 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1486 /* address can be in use ipv6 address is already bound */
1488 error("bind: %.100s", strerror(errno));
1490 verbose("bind: %.100s", strerror(errno));
1495 /* Start listening for connections on the socket. */
1496 if (listen(sock, 5) < 0) {
1497 error("listen: %.100s", strerror(errno));
1501 /* Allocate a channel number for the socket. */
1503 "port listener", SSH_CHANNEL_PORT_LISTENER,
1505 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1506 0, xstrdup("port listener"));
1507 strlcpy(channels[ch].path, host, sizeof(channels[ch].path));
1508 channels[ch].host_port = host_port;
1509 channels[ch].listening_port = port;
1513 packet_disconnect("cannot listen port: %d", port);
1514 freeaddrinfo(aitop);
1518 * Initiate forwarding of connections to port "port" on remote host through
1519 * the secure channel to host:port from local side.
1523 channel_request_remote_forwarding(u_short listen_port, const char *host_to_connect,
1524 u_short port_to_connect)
1527 /* Record locally that connection to this host/port is permitted. */
1528 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
1529 fatal("channel_request_remote_forwarding: too many forwards");
1531 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
1532 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
1533 permitted_opens[num_permitted_opens].listen_port = listen_port;
1534 num_permitted_opens++;
1536 /* Send the forward request to the remote side. */
1538 const char *address_to_bind = "0.0.0.0";
1539 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1540 packet_put_cstring("tcpip-forward");
1541 packet_put_char(0); /* boolean: want reply */
1542 packet_put_cstring(address_to_bind);
1543 packet_put_int(listen_port);
1545 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1546 packet_put_int(listen_port);
1547 packet_put_cstring(host_to_connect);
1548 packet_put_int(port_to_connect);
1550 packet_write_wait();
1552 * Wait for response from the remote side. It will send a disconnect
1553 * message on failure, and we will never see it here.
1555 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1560 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
1561 * listening for the port, and sends back a success reply (or disconnect
1562 * message if there was an error). This never returns if there was an error.
1566 channel_input_port_forward_request(int is_root, int gateway_ports)
1568 u_short port, host_port;
1571 /* Get arguments from the packet. */
1572 port = packet_get_int();
1573 hostname = packet_get_string(NULL);
1574 host_port = packet_get_int();
1577 * Check that an unprivileged user is not trying to forward a
1580 if (port < IPPORT_RESERVED && !is_root)
1581 packet_disconnect("Requested forwarding of port %d but user is not root.",
1584 * Initiate forwarding,
1586 channel_request_local_forwarding(port, hostname, host_port, gateway_ports);
1588 /* Free the argument string. */
1592 /* XXX move to aux.c */
1594 channel_connect_to(const char *host, u_short host_port)
1596 struct addrinfo hints, *ai, *aitop;
1597 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1601 memset(&hints, 0, sizeof(hints));
1602 hints.ai_family = IPv4or6;
1603 hints.ai_socktype = SOCK_STREAM;
1604 snprintf(strport, sizeof strport, "%d", host_port);
1605 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
1606 error("%.100s: unknown host (%s)", host, gai_strerror(gaierr));
1609 for (ai = aitop; ai; ai = ai->ai_next) {
1610 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1612 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1613 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1614 error("channel_connect_to: getnameinfo failed");
1617 /* Create the socket. */
1618 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1620 error("socket: %.100s", strerror(errno));
1623 /* Connect to the host/port. */
1624 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1625 error("connect %.100s port %s: %.100s", ntop, strport,
1628 continue; /* fail -- try next */
1630 break; /* success */
1633 freeaddrinfo(aitop);
1635 error("connect %.100s port %d: failed.", host, host_port);
1643 * This is called after receiving PORT_OPEN message. This attempts to
1644 * connect to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION
1645 * or CHANNEL_OPEN_FAILURE.
1649 channel_input_port_open(int type, int plen)
1652 char *host, *originator_string;
1653 int remote_channel, sock = -1, newch, i, denied;
1654 unsigned int host_len, originator_len;
1656 /* Get remote channel number. */
1657 remote_channel = packet_get_int();
1659 /* Get host name to connect to. */
1660 host = packet_get_string(&host_len);
1662 /* Get port to connect to. */
1663 host_port = packet_get_int();
1665 /* Get remote originator name. */
1666 if (have_hostname_in_open) {
1667 originator_string = packet_get_string(&originator_len);
1668 originator_len += 4; /* size of packet_int */
1670 originator_string = xstrdup("unknown (remote did not supply name)");
1671 originator_len = 0; /* no originator supplied */
1674 packet_integrity_check(plen,
1675 4 + 4 + host_len + 4 + originator_len, SSH_MSG_PORT_OPEN);
1677 /* Check if opening that port is permitted. */
1679 if (!all_opens_permitted) {
1680 /* Go trough all permitted ports. */
1681 for (i = 0; i < num_permitted_opens; i++)
1682 if (permitted_opens[i].port_to_connect == host_port &&
1683 strcmp(permitted_opens[i].host_to_connect, host) == 0)
1686 /* Check if we found the requested port among those permitted. */
1687 if (i >= num_permitted_opens) {
1688 /* The port is not permitted. */
1689 log("Received request to connect to %.100s:%d, but the request was denied.",
1694 sock = denied ? -1 : channel_connect_to(host, host_port);
1696 /* Allocate a channel for this connection. */
1697 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, originator_string);
1698 channels[newch].remote_id = remote_channel;
1700 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1701 packet_put_int(remote_channel);
1702 packet_put_int(newch);
1705 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1706 packet_put_int(remote_channel);
1713 * Creates an internet domain socket for listening for X11 connections.
1714 * Returns a suitable value for the DISPLAY variable, or NULL if an error
1718 #define NUM_SOCKS 10
1721 x11_create_display_inet(int screen_number, int x11_display_offset)
1723 int display_number, sock;
1725 struct addrinfo hints, *ai, *aitop;
1726 char strport[NI_MAXSERV];
1727 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
1729 char hostname[MAXHOSTNAMELEN];
1731 for (display_number = x11_display_offset;
1732 display_number < MAX_DISPLAYS;
1734 port = 6000 + display_number;
1735 memset(&hints, 0, sizeof(hints));
1736 hints.ai_family = IPv4or6;
1737 hints.ai_flags = AI_PASSIVE; /* XXX loopback only ? */
1738 hints.ai_socktype = SOCK_STREAM;
1739 snprintf(strport, sizeof strport, "%d", port);
1740 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
1741 error("getaddrinfo: %.100s", gai_strerror(gaierr));
1744 for (ai = aitop; ai; ai = ai->ai_next) {
1745 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1747 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1749 if (errno != EINVAL) {
1750 error("socket: %.100s", strerror(errno));
1753 debug("Socket family %d not supported [X11 disp create]", ai->ai_family);
1757 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1758 debug("bind port %d: %.100s", port, strerror(errno));
1759 shutdown(sock, SHUT_RDWR);
1765 for (n = 0; n < num_socks; n++) {
1766 shutdown(socks[n], SHUT_RDWR);
1772 socks[num_socks++] = sock;
1773 #ifndef DONT_TRY_OTHER_AF
1774 if (num_socks == NUM_SOCKS)
1783 if (display_number >= MAX_DISPLAYS) {
1784 error("Failed to allocate internet-domain X11 display socket.");
1787 /* Start listening for connections on the socket. */
1788 for (n = 0; n < num_socks; n++) {
1790 if (listen(sock, 5) < 0) {
1791 error("listen: %.100s", strerror(errno));
1792 shutdown(sock, SHUT_RDWR);
1798 /* Set up a suitable value for the DISPLAY variable. */
1800 if (gethostname(hostname, sizeof(hostname)) < 0)
1801 fatal("gethostname: %.100s", strerror(errno));
1803 #ifdef IPADDR_IN_DISPLAY
1805 * HPUX detects the local hostname in the DISPLAY variable and tries
1806 * to set up a shared memory connection to the server, which it
1807 * incorrectly supposes to be local.
1809 * The workaround - as used in later $$H and other programs - is
1810 * is to set display to the host's IP address.
1814 struct in_addr my_addr;
1816 he = gethostbyname(hostname);
1818 error("[X11-broken-fwd-hostname-workaround] Could not get "
1819 "IP address for hostname %s.", hostname);
1821 packet_send_debug("[X11-broken-fwd-hostname-workaround]"
1822 "Could not get IP address for hostname %s.", hostname);
1824 shutdown(sock, SHUT_RDWR);
1830 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
1832 /* Set DISPLAY to <ip address>:screen.display */
1833 snprintf(display, sizeof(display), "%.50s:%d.%d", inet_ntoa(my_addr),
1834 display_number, screen_number);
1836 #else /* IPADDR_IN_DISPLAY */
1837 /* Just set DISPLAY to hostname:screen.display */
1838 snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
1839 display_number, screen_number);
1840 #endif /* IPADDR_IN_DISPLAY */
1842 /* Allocate a channel for each socket. */
1843 for (n = 0; n < num_socks; n++) {
1845 (void) channel_new("x11 listener",
1846 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
1847 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
1848 0, xstrdup("X11 inet listener"));
1851 /* Return a suitable value for the DISPLAY environment variable. */
1852 return xstrdup(display);
1856 #define X_UNIX_PATH "/tmp/.X11-unix/X"
1861 connect_local_xsocket(unsigned int dnr)
1863 static const char *const x_sockets[] = {
1865 "/var/X/.X11-unix/X" "%u",
1866 "/usr/spool/sockets/X11/" "%u",
1870 struct sockaddr_un addr;
1871 const char *const * path;
1873 for (path = x_sockets; *path; ++path) {
1874 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1876 error("socket: %.100s", strerror(errno));
1877 memset(&addr, 0, sizeof(addr));
1878 addr.sun_family = AF_UNIX;
1879 snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
1880 if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
1884 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
1889 x11_connect_display(void)
1891 int display_number, sock = 0;
1892 const char *display;
1893 char buf[1024], *cp;
1894 struct addrinfo hints, *ai, *aitop;
1895 char strport[NI_MAXSERV];
1898 /* Try to open a socket for the local X server. */
1899 display = getenv("DISPLAY");
1901 error("DISPLAY not set.");
1905 * Now we decode the value of the DISPLAY variable and make a
1906 * connection to the real X server.
1910 * Check if it is a unix domain socket. Unix domain displays are in
1911 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
1913 if (strncmp(display, "unix:", 5) == 0 ||
1914 display[0] == ':') {
1915 /* Connect to the unix domain socket. */
1916 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
1917 error("Could not parse display number from DISPLAY: %.100s",
1921 /* Create a socket. */
1922 sock = connect_local_xsocket(display_number);
1926 /* OK, we now have a connection to the display. */
1930 * Connect to an inet socket. The DISPLAY value is supposedly
1931 * hostname:d[.s], where hostname may also be numeric IP address.
1933 strncpy(buf, display, sizeof(buf));
1934 buf[sizeof(buf) - 1] = 0;
1935 cp = strchr(buf, ':');
1937 error("Could not find ':' in DISPLAY: %.100s", display);
1941 /* buf now contains the host name. But first we parse the display number. */
1942 if (sscanf(cp + 1, "%d", &display_number) != 1) {
1943 error("Could not parse display number from DISPLAY: %.100s",
1948 /* Look up the host address */
1949 memset(&hints, 0, sizeof(hints));
1950 hints.ai_family = IPv4or6;
1951 hints.ai_socktype = SOCK_STREAM;
1952 snprintf(strport, sizeof strport, "%d", 6000 + display_number);
1953 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
1954 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
1957 for (ai = aitop; ai; ai = ai->ai_next) {
1958 /* Create a socket. */
1959 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1961 debug("socket: %.100s", strerror(errno));
1964 /* Connect it to the display. */
1965 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1966 debug("connect %.100s port %d: %.100s", buf,
1967 6000 + display_number, strerror(errno));
1974 freeaddrinfo(aitop);
1976 error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
1984 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
1985 * the remote channel number. We should do whatever we want, and respond
1986 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
1990 x11_input_open(int type, int plen)
1992 int remote_channel, sock = 0, newch;
1994 unsigned int remote_len;
1996 /* Get remote channel number. */
1997 remote_channel = packet_get_int();
1999 /* Get remote originator name. */
2000 if (have_hostname_in_open) {
2001 remote_host = packet_get_string(&remote_len);
2004 remote_host = xstrdup("unknown (remote did not supply name)");
2008 debug("Received X11 open request.");
2009 packet_integrity_check(plen, 4 + remote_len, SSH_SMSG_X11_OPEN);
2011 /* Obtain a connection to the real X display. */
2012 sock = x11_connect_display();
2014 /* Send refusal to the remote host. */
2015 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2016 packet_put_int(remote_channel);
2019 /* Allocate a channel for this connection. */
2020 newch = channel_allocate(
2021 (x11_saved_proto == NULL) ?
2022 SSH_CHANNEL_OPEN : SSH_CHANNEL_X11_OPEN,
2024 channels[newch].remote_id = remote_channel;
2026 /* Send a confirmation to the remote host. */
2027 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2028 packet_put_int(remote_channel);
2029 packet_put_int(newch);
2035 * Requests forwarding of X11 connections, generates fake authentication
2036 * data, and enables authentication spoofing.
2040 x11_request_forwarding_with_spoofing(int client_session_id,
2041 const char *proto, const char *data)
2043 unsigned int data_len = (unsigned int) strlen(data) / 2;
2044 unsigned int i, value;
2050 cp = getenv("DISPLAY");
2052 cp = strchr(cp, ':');
2054 cp = strchr(cp, '.');
2056 screen_number = atoi(cp + 1);
2060 /* Save protocol name. */
2061 x11_saved_proto = xstrdup(proto);
2064 * Extract real authentication data and generate fake data of the
2067 x11_saved_data = xmalloc(data_len);
2068 x11_fake_data = xmalloc(data_len);
2069 for (i = 0; i < data_len; i++) {
2070 if (sscanf(data + 2 * i, "%2x", &value) != 1)
2071 fatal("x11_request_forwarding: bad authentication data: %.100s", data);
2073 rand = arc4random();
2074 x11_saved_data[i] = value;
2075 x11_fake_data[i] = rand & 0xff;
2078 x11_saved_data_len = data_len;
2079 x11_fake_data_len = data_len;
2081 /* Convert the fake data into hex. */
2082 new_data = xmalloc(2 * data_len + 1);
2083 for (i = 0; i < data_len; i++)
2084 sprintf(new_data + 2 * i, "%02x", (unsigned char) x11_fake_data[i]);
2086 /* Send the request packet. */
2088 channel_request_start(client_session_id, "x11-req", 0);
2089 packet_put_char(0); /* XXX bool single connection */
2091 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
2093 packet_put_cstring(proto);
2094 packet_put_cstring(new_data);
2095 packet_put_int(screen_number);
2097 packet_write_wait();
2101 /* Sends a message to the server to request authentication fd forwarding. */
2104 auth_request_forwarding()
2106 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
2108 packet_write_wait();
2112 * Returns the name of the forwarded authentication socket. Returns NULL if
2113 * there is no forwarded authentication socket. The returned value points to
2118 auth_get_socket_name()
2120 return channel_forwarded_auth_socket_name;
2123 /* removes the agent forwarding socket */
2126 cleanup_socket(void)
2128 remove(channel_forwarded_auth_socket_name);
2129 rmdir(channel_forwarded_auth_socket_dir);
2133 * This if called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
2134 * This starts forwarding authentication requests.
2138 auth_input_request_forwarding(struct passwd * pw)
2141 struct sockaddr_un sunaddr;
2143 if (auth_get_socket_name() != NULL)
2144 fatal("Protocol error: authentication forwarding requested twice.");
2146 /* Temporarily drop privileged uid for mkdir/bind. */
2147 temporarily_use_uid(pw->pw_uid);
2149 /* Allocate a buffer for the socket name, and format the name. */
2150 channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
2151 channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
2152 strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
2154 /* Create private directory for socket */
2155 if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL)
2156 packet_disconnect("mkdtemp: %.100s", strerror(errno));
2157 snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME, "%s/agent.%d",
2158 channel_forwarded_auth_socket_dir, (int) getpid());
2160 if (atexit(cleanup_socket) < 0) {
2163 packet_disconnect("socket: %.100s", strerror(saved));
2165 /* Create the socket. */
2166 sock = socket(AF_UNIX, SOCK_STREAM, 0);
2168 packet_disconnect("socket: %.100s", strerror(errno));
2170 /* Bind it to the name. */
2171 memset(&sunaddr, 0, sizeof(sunaddr));
2172 sunaddr.sun_family = AF_UNIX;
2173 strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
2174 sizeof(sunaddr.sun_path));
2176 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
2177 packet_disconnect("bind: %.100s", strerror(errno));
2179 /* Restore the privileged uid. */
2182 /* Start listening on the socket. */
2183 if (listen(sock, 5) < 0)
2184 packet_disconnect("listen: %.100s", strerror(errno));
2186 /* Allocate a channel for the authentication agent socket. */
2187 newch = channel_allocate(SSH_CHANNEL_AUTH_SOCKET, sock,
2188 xstrdup("auth socket"));
2189 strlcpy(channels[newch].path, channel_forwarded_auth_socket_name,
2190 sizeof(channels[newch].path));
2193 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
2196 auth_input_open_request(int type, int plen)
2198 int remch, sock, newch;
2201 packet_integrity_check(plen, 4, type);
2203 /* Read the remote channel number from the message. */
2204 remch = packet_get_int();
2207 * Get a connection to the local authentication agent (this may again
2210 sock = ssh_get_authentication_socket();
2213 * If we could not connect the agent, send an error message back to
2214 * the server. This should never happen unless the agent dies,
2215 * because authentication forwarding is only enabled if we have an
2219 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2220 packet_put_int(remch);
2224 debug("Forwarding authentication connection.");
2227 * Dummy host name. This will be freed when the channel is freed; it
2228 * will still be valid in the packet_put_string below since the
2229 * channel cannot yet be freed at that point.
2231 dummyname = xstrdup("authentication agent connection");
2233 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
2234 channels[newch].remote_id = remch;
2236 /* Send a confirmation to the remote host. */
2237 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2238 packet_put_int(remch);
2239 packet_put_int(newch);
2244 channel_start_open(int id)
2246 Channel *c = channel_lookup(id);
2248 log("channel_open: %d: bad id", id);
2251 debug("send channel open %d", id);
2252 packet_start(SSH2_MSG_CHANNEL_OPEN);
2253 packet_put_cstring(c->ctype);
2254 packet_put_int(c->self);
2255 packet_put_int(c->local_window);
2256 packet_put_int(c->local_maxpacket);
2259 channel_open(int id)
2262 channel_start_open(id);
2266 channel_request(int id, char *service, int wantconfirm)
2268 channel_request_start(id, service, wantconfirm);
2270 debug("channel request %d: %s", id, service) ;
2273 channel_request_start(int id, char *service, int wantconfirm)
2275 Channel *c = channel_lookup(id);
2277 log("channel_request: %d: bad id", id);
2280 packet_start(SSH2_MSG_CHANNEL_REQUEST);
2281 packet_put_int(c->remote_id);
2282 packet_put_cstring(service);
2283 packet_put_char(wantconfirm);
2286 channel_register_callback(int id, int mtype, channel_callback_fn *fn, void *arg)
2288 Channel *c = channel_lookup(id);
2290 log("channel_register_callback: %d: bad id", id);
2293 c->cb_event = mtype;
2298 channel_register_cleanup(int id, channel_callback_fn *fn)
2300 Channel *c = channel_lookup(id);
2302 log("channel_register_cleanup: %d: bad id", id);
2305 c->dettach_user = fn;
2308 channel_cancel_cleanup(int id)
2310 Channel *c = channel_lookup(id);
2312 log("channel_cancel_cleanup: %d: bad id", id);
2315 c->dettach_user = NULL;
2319 channel_set_fds(int id, int rfd, int wfd, int efd, int extusage)
2321 Channel *c = channel_lookup(id);
2322 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
2323 fatal("channel_activate for non-larval channel %d.", id);
2325 channel_register_fds(c, rfd, wfd, efd, extusage);
2326 c->type = SSH_CHANNEL_OPEN;
2327 /* XXX window size? */
2328 c->local_window = c->local_window_max = c->local_maxpacket/2;
2329 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2330 packet_put_int(c->remote_id);
2331 packet_put_int(c->local_window);