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;
508 channel_pre_open_15(c, readset, writeset);
509 } else if (ret == -1) {
510 debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
511 chan_read_failed(c); /** force close? */
512 chan_write_failed(c);
513 debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
517 /* This is our fake X11 server socket. */
519 channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
521 struct sockaddr addr;
524 char buf[16384], *remote_hostname;
527 if (FD_ISSET(c->sock, readset)) {
528 debug("X11 connection requested.");
529 addrlen = sizeof(addr);
530 newsock = accept(c->sock, &addr, &addrlen);
532 error("accept: %.100s", strerror(errno));
535 remote_hostname = get_remote_hostname(newsock);
536 remote_port = get_peer_port(newsock);
537 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
538 remote_hostname, remote_port);
540 newch = channel_new("x11",
541 SSH_CHANNEL_OPENING, newsock, newsock, -1,
542 c->local_window_max, c->local_maxpacket,
545 packet_start(SSH2_MSG_CHANNEL_OPEN);
546 packet_put_cstring("x11");
547 packet_put_int(newch);
548 packet_put_int(c->local_window_max);
549 packet_put_int(c->local_maxpacket);
550 /* originator host and port */
551 packet_put_cstring(remote_hostname);
552 packet_put_int(remote_port);
555 packet_start(SSH_SMSG_X11_OPEN);
556 packet_put_int(newch);
557 if (have_hostname_in_open)
558 packet_put_string(buf, strlen(buf));
561 xfree(remote_hostname);
566 * This socket is listening for connections to a forwarded TCP/IP port.
569 channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
571 struct sockaddr addr;
574 char buf[1024], *remote_hostname;
577 if (FD_ISSET(c->sock, readset)) {
578 debug("Connection to port %d forwarding "
579 "to %.100s port %d requested.",
580 c->listening_port, c->path, c->host_port);
581 addrlen = sizeof(addr);
582 newsock = accept(c->sock, &addr, &addrlen);
584 error("accept: %.100s", strerror(errno));
587 remote_hostname = get_remote_hostname(newsock);
588 remote_port = get_peer_port(newsock);
589 snprintf(buf, sizeof buf,
590 "listen port %d for %.100s port %d, "
591 "connect from %.200s port %d",
592 c->listening_port, c->path, c->host_port,
593 remote_hostname, remote_port);
594 newch = channel_new("direct-tcpip",
595 SSH_CHANNEL_OPENING, newsock, newsock, -1,
596 c->local_window_max, c->local_maxpacket,
599 packet_start(SSH2_MSG_CHANNEL_OPEN);
600 packet_put_cstring("direct-tcpip");
601 packet_put_int(newch);
602 packet_put_int(c->local_window_max);
603 packet_put_int(c->local_maxpacket);
604 /* target host and port */
605 packet_put_string(c->path, strlen(c->path));
606 packet_put_int(c->host_port);
607 /* originator host and port */
608 packet_put_cstring(remote_hostname);
609 packet_put_int(remote_port);
612 packet_start(SSH_MSG_PORT_OPEN);
613 packet_put_int(newch);
614 packet_put_string(c->path, strlen(c->path));
615 packet_put_int(c->host_port);
616 if (have_hostname_in_open) {
617 packet_put_string(buf, strlen(buf));
621 xfree(remote_hostname);
626 * This is the authentication agent socket listening for connections from
630 channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
632 struct sockaddr addr;
636 if (FD_ISSET(c->sock, readset)) {
637 addrlen = sizeof(addr);
638 newsock = accept(c->sock, &addr, &addrlen);
640 error("accept from auth socket: %.100s", strerror(errno));
643 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
644 xstrdup("accepted auth socket"));
645 packet_start(SSH_SMSG_AGENT_OPEN);
646 packet_put_int(newch);
652 channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
658 FD_ISSET(c->rfd, readset)) {
659 len = read(c->rfd, buf, sizeof(buf));
660 if (len < 0 && (errno == EINTR || errno == EAGAIN))
663 debug("channel %d: read<=0 rfd %d len %d",
664 c->self, c->rfd, len);
666 buffer_consume(&c->output, buffer_len(&c->output));
667 c->type = SSH_CHANNEL_INPUT_DRAINING;
668 debug("Channel %d status set to input draining.", c->self);
674 buffer_append(&c->input, buf, len);
679 channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
683 /* Send buffered output data to the socket. */
685 FD_ISSET(c->wfd, writeset) &&
686 buffer_len(&c->output) > 0) {
687 len = write(c->wfd, buffer_ptr(&c->output),
688 buffer_len(&c->output));
689 if (len < 0 && (errno == EINTR || errno == EAGAIN))
693 buffer_consume(&c->output, buffer_len(&c->output));
694 debug("Channel %d status set to input draining.", c->self);
695 c->type = SSH_CHANNEL_INPUT_DRAINING;
697 chan_write_failed(c);
701 buffer_consume(&c->output, len);
702 if (compat20 && len > 0) {
703 c->local_consumed += len;
709 channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
714 /** XXX handle drain efd, too */
716 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
717 FD_ISSET(c->efd, writeset) &&
718 buffer_len(&c->extended) > 0) {
719 len = write(c->efd, buffer_ptr(&c->extended),
720 buffer_len(&c->extended));
721 debug("channel %d: written %d to efd %d",
722 c->self, len, c->efd);
724 buffer_consume(&c->extended, len);
725 c->local_consumed += len;
727 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
728 FD_ISSET(c->efd, readset)) {
729 len = read(c->efd, buf, sizeof(buf));
730 debug("channel %d: read %d from efd %d",
731 c->self, len, c->efd);
733 debug("channel %d: closing efd %d",
738 buffer_append(&c->extended, buf, len);
744 channel_check_window(Channel *c, fd_set * readset, fd_set * writeset)
746 if (!(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
747 c->local_window < c->local_window_max/2 &&
748 c->local_consumed > 0) {
749 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
750 packet_put_int(c->remote_id);
751 packet_put_int(c->local_consumed);
753 debug("channel %d: window %d sent adjust %d",
754 c->self, c->local_window,
756 c->local_window += c->local_consumed;
757 c->local_consumed = 0;
763 channel_post_open_1(Channel *c, fd_set * readset, fd_set * writeset)
765 channel_handle_rfd(c, readset, writeset);
766 channel_handle_wfd(c, readset, writeset);
770 channel_post_open_2(Channel *c, fd_set * readset, fd_set * writeset)
772 channel_handle_rfd(c, readset, writeset);
773 channel_handle_wfd(c, readset, writeset);
774 channel_handle_efd(c, readset, writeset);
775 channel_check_window(c, readset, writeset);
779 channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
782 /* Send buffered output data to the socket. */
783 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
784 len = write(c->sock, buffer_ptr(&c->output),
785 buffer_len(&c->output));
787 buffer_consume(&c->output, buffer_len(&c->output));
789 buffer_consume(&c->output, len);
794 channel_handler_init_20(void)
796 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_20;
797 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
798 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
799 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
801 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open_2;
802 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
803 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
807 channel_handler_init_13(void)
809 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
810 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
811 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
812 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
813 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
814 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
815 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
817 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open_1;
818 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
819 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
820 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
821 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
825 channel_handler_init_15(void)
827 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_15;
828 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
829 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
830 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
831 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
833 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
834 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
835 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
836 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open_1;
840 channel_handler_init(void)
843 for(i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
844 channel_pre[i] = NULL;
845 channel_post[i] = NULL;
848 channel_handler_init_20();
850 channel_handler_init_13();
852 channel_handler_init_15();
856 channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
858 static int did_init = 0;
863 channel_handler_init();
866 for (i = 0; i < channels_alloc; i++) {
868 if (c->type == SSH_CHANNEL_FREE)
870 if (ftab[c->type] == NULL)
872 (*ftab[c->type])(c, readset, writeset);
873 chan_delete_if_full_closed(c);
878 channel_prepare_select(fd_set * readset, fd_set * writeset)
880 channel_handler(channel_pre, readset, writeset);
884 channel_after_select(fd_set * readset, fd_set * writeset)
886 channel_handler(channel_post, readset, writeset);
889 /* If there is data to send to the connection, send some of it now. */
892 channel_output_poll()
897 for (i = 0; i < channels_alloc; i++) {
900 /* We are only interested in channels that can have buffered incoming data. */
902 if (c->type != SSH_CHANNEL_OPEN &&
903 c->type != SSH_CHANNEL_INPUT_DRAINING)
906 if (c->type != SSH_CHANNEL_OPEN)
908 if (c->istate != CHAN_INPUT_OPEN &&
909 c->istate != CHAN_INPUT_WAIT_DRAIN)
913 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
914 debug("channel: %d: no data after CLOSE", c->self);
918 /* Get the amount of buffered data for this channel. */
919 len = buffer_len(&c->input);
921 /* Send some data for the other side over the secure connection. */
923 if (len > c->remote_window)
924 len = c->remote_window;
925 if (len > c->remote_maxpacket)
926 len = c->remote_maxpacket;
928 if (packet_is_interactive()) {
932 /* Keep the packets at reasonable size. */
933 if (len > packet_get_maxsize()/2)
934 len = packet_get_maxsize()/2;
938 packet_start(compat20 ?
939 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
940 packet_put_int(c->remote_id);
941 packet_put_string(buffer_ptr(&c->input), len);
943 buffer_consume(&c->input, len);
944 c->remote_window -= len;
945 debug("channel %d: send data len %d", c->self, len);
947 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
949 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
951 * input-buffer is empty and read-socket shutdown:
952 * tell peer, that we will not send more data: send IEOF
956 /* Send extended data, i.e. stderr */
958 c->remote_window > 0 &&
959 (len = buffer_len(&c->extended)) > 0 &&
960 c->extended_usage == CHAN_EXTENDED_READ) {
961 if (len > c->remote_window)
962 len = c->remote_window;
963 if (len > c->remote_maxpacket)
964 len = c->remote_maxpacket;
965 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
966 packet_put_int(c->remote_id);
967 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
968 packet_put_string(buffer_ptr(&c->extended), len);
970 buffer_consume(&c->extended, len);
971 c->remote_window -= len;
977 * This is called when a packet of type CHANNEL_DATA has just been received.
978 * The message type has already been consumed, but channel number and data is
983 channel_input_data(int type, int plen)
987 unsigned int data_len;
990 /* Get the channel number and verify it. */
991 id = packet_get_int();
992 c = channel_lookup(id);
994 packet_disconnect("Received data for nonexistent channel %d.", id);
996 /* Ignore any data for non-open channels (might happen on close) */
997 if (c->type != SSH_CHANNEL_OPEN &&
998 c->type != SSH_CHANNEL_X11_OPEN)
1001 /* same for protocol 1.5 if output end is no longer open */
1002 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
1006 data = packet_get_string(&data_len);
1010 if (data_len > c->local_maxpacket) {
1011 log("channel %d: rcvd big packet %d, maxpack %d",
1012 c->self, data_len, c->local_maxpacket);
1014 if (data_len > c->local_window) {
1015 log("channel %d: rcvd too much data %d, win %d",
1016 c->self, data_len, c->local_window);
1020 c->local_window -= data_len;
1022 packet_integrity_check(plen, 4 + 4 + data_len, type);
1024 buffer_append(&c->output, data, data_len);
1028 channel_input_extended_data(int type, int plen)
1033 unsigned int data_len;
1036 /* Get the channel number and verify it. */
1037 id = packet_get_int();
1038 c = channel_lookup(id);
1041 packet_disconnect("Received extended_data for bad channel %d.", id);
1042 if (c->type != SSH_CHANNEL_OPEN) {
1043 log("channel %d: ext data for non open", id);
1046 tcode = packet_get_int();
1048 c->extended_usage != CHAN_EXTENDED_WRITE ||
1049 tcode != SSH2_EXTENDED_DATA_STDERR) {
1050 log("channel %d: bad ext data", c->self);
1053 data = packet_get_string(&data_len);
1055 if (data_len > c->local_window) {
1056 log("channel %d: rcvd too much extended_data %d, win %d",
1057 c->self, data_len, c->local_window);
1061 debug("channel %d: rcvd ext data %d", c->self, data_len);
1062 c->local_window -= data_len;
1063 buffer_append(&c->extended, data, data_len);
1069 * Returns true if no channel has too much buffered data, and false if one or
1070 * more channel is overfull.
1074 channel_not_very_much_buffered_data()
1079 for (i = 0; i < channels_alloc; i++) {
1081 if (c->type == SSH_CHANNEL_OPEN) {
1082 if (!compat20 && buffer_len(&c->input) > packet_get_maxsize()) {
1083 debug("channel %d: big input buffer %d",
1084 c->self, buffer_len(&c->input));
1087 if (buffer_len(&c->output) > packet_get_maxsize()) {
1088 debug("channel %d: big output buffer %d",
1089 c->self, buffer_len(&c->output));
1098 channel_input_ieof(int type, int plen)
1103 packet_integrity_check(plen, 4, type);
1105 id = packet_get_int();
1106 c = channel_lookup(id);
1108 packet_disconnect("Received ieof for nonexistent channel %d.", id);
1113 channel_input_close(int type, int plen)
1118 packet_integrity_check(plen, 4, type);
1120 id = packet_get_int();
1121 c = channel_lookup(id);
1123 packet_disconnect("Received close for nonexistent channel %d.", id);
1126 * Send a confirmation that we have closed the channel and no more
1127 * data is coming for it.
1129 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1130 packet_put_int(c->remote_id);
1134 * If the channel is in closed state, we have sent a close request,
1135 * and the other side will eventually respond with a confirmation.
1136 * Thus, we cannot free the channel here, because then there would be
1137 * no-one to receive the confirmation. The channel gets freed when
1138 * the confirmation arrives.
1140 if (c->type != SSH_CHANNEL_CLOSED) {
1142 * Not a closed channel - mark it as draining, which will
1143 * cause it to be freed later.
1145 buffer_consume(&c->input, buffer_len(&c->input));
1146 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1150 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1152 channel_input_oclose(int type, int plen)
1154 int id = packet_get_int();
1155 Channel *c = channel_lookup(id);
1156 packet_integrity_check(plen, 4, type);
1158 packet_disconnect("Received oclose for nonexistent channel %d.", id);
1159 chan_rcvd_oclose(c);
1163 channel_input_close_confirmation(int type, int plen)
1165 int id = packet_get_int();
1166 Channel *c = channel_lookup(id);
1170 packet_disconnect("Received close confirmation for "
1171 "out-of-range channel %d.", id);
1172 if (c->type != SSH_CHANNEL_CLOSED)
1173 packet_disconnect("Received close confirmation for "
1174 "non-closed channel %d (type %d).", id, c->type);
1175 channel_free(c->self);
1179 channel_input_open_confirmation(int type, int plen)
1185 packet_integrity_check(plen, 4 + 4, type);
1187 id = packet_get_int();
1188 c = channel_lookup(id);
1190 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1191 packet_disconnect("Received open confirmation for "
1192 "non-opening channel %d.", id);
1193 remote_id = packet_get_int();
1194 /* Record the remote channel number and mark that the channel is now open. */
1195 c->remote_id = remote_id;
1196 c->type = SSH_CHANNEL_OPEN;
1199 c->remote_window = packet_get_int();
1200 c->remote_maxpacket = packet_get_int();
1202 if (c->cb_fn != NULL && c->cb_event == type) {
1203 debug("callback start");
1204 c->cb_fn(c->self, c->cb_arg);
1205 debug("callback done");
1207 debug("channel %d: open confirm rwindow %d rmax %d", c->self,
1208 c->remote_window, c->remote_maxpacket);
1213 channel_input_open_failure(int type, int plen)
1219 packet_integrity_check(plen, 4, type);
1221 id = packet_get_int();
1222 c = channel_lookup(id);
1224 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1225 packet_disconnect("Received open failure for "
1226 "non-opening channel %d.", id);
1228 int reason = packet_get_int();
1229 char *msg = packet_get_string(NULL);
1230 char *lang = packet_get_string(NULL);
1231 log("channel_open_failure: %d: reason %d: %s", id, reason, msg);
1236 /* Free the channel. This will also close the socket. */
1241 channel_input_channel_request(int type, int plen)
1246 id = packet_get_int();
1247 c = channel_lookup(id);
1250 (c->type != SSH_CHANNEL_OPEN && c->type != SSH_CHANNEL_LARVAL))
1251 packet_disconnect("Received request for "
1252 "non-open channel %d.", id);
1253 if (c->cb_fn != NULL && c->cb_event == type) {
1254 debug("callback start");
1255 c->cb_fn(c->self, c->cb_arg);
1256 debug("callback done");
1258 char *service = packet_get_string(NULL);
1259 debug("channel: %d rcvd request for %s", c->self, service);
1260 debug("cb_fn %p cb_event %d", c->cb_fn , c->cb_event);
1266 channel_input_window_adjust(int type, int plen)
1274 /* Get the channel number and verify it. */
1275 id = packet_get_int();
1276 c = channel_lookup(id);
1278 if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
1279 log("Received window adjust for "
1280 "non-open channel %d.", id);
1283 adjust = packet_get_int();
1285 debug("channel %d: rcvd adjust %d", id, adjust);
1286 c->remote_window += adjust;
1290 * Stops listening for channels, and removes any unix domain sockets that we
1295 channel_stop_listening()
1298 for (i = 0; i < channels_alloc; i++) {
1299 switch (channels[i].type) {
1300 case SSH_CHANNEL_AUTH_SOCKET:
1301 close(channels[i].sock);
1302 remove(channels[i].path);
1305 case SSH_CHANNEL_PORT_LISTENER:
1306 case SSH_CHANNEL_X11_LISTENER:
1307 close(channels[i].sock);
1317 * Closes the sockets/fds of all channels. This is used to close extra file
1318 * descriptors after a fork.
1325 for (i = 0; i < channels_alloc; i++)
1326 if (channels[i].type != SSH_CHANNEL_FREE)
1327 channel_close_fds(&channels[i]);
1330 /* Returns the maximum file descriptor number used by the channels. */
1335 return channel_max_fd_value;
1338 /* Returns true if any channel is still open. */
1341 channel_still_open()
1344 for (i = 0; i < channels_alloc; i++)
1345 switch (channels[i].type) {
1346 case SSH_CHANNEL_FREE:
1347 case SSH_CHANNEL_X11_LISTENER:
1348 case SSH_CHANNEL_PORT_LISTENER:
1349 case SSH_CHANNEL_CLOSED:
1350 case SSH_CHANNEL_AUTH_SOCKET:
1352 case SSH_CHANNEL_LARVAL:
1354 fatal("cannot happen: SSH_CHANNEL_LARVAL");
1356 case SSH_CHANNEL_OPENING:
1357 case SSH_CHANNEL_OPEN:
1358 case SSH_CHANNEL_X11_OPEN:
1360 case SSH_CHANNEL_INPUT_DRAINING:
1361 case SSH_CHANNEL_OUTPUT_DRAINING:
1363 fatal("cannot happen: OUT_DRAIN");
1366 fatal("channel_still_open: bad channel type %d", channels[i].type);
1373 * Returns a message describing the currently open forwarded connections,
1374 * suitable for sending to the client. The message contains crlf pairs for
1379 channel_open_message()
1385 buffer_init(&buffer);
1386 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
1387 buffer_append(&buffer, buf, strlen(buf));
1388 for (i = 0; i < channels_alloc; i++) {
1389 Channel *c = &channels[i];
1391 case SSH_CHANNEL_FREE:
1392 case SSH_CHANNEL_X11_LISTENER:
1393 case SSH_CHANNEL_PORT_LISTENER:
1394 case SSH_CHANNEL_CLOSED:
1395 case SSH_CHANNEL_AUTH_SOCKET:
1397 case SSH_CHANNEL_LARVAL:
1398 case SSH_CHANNEL_OPENING:
1399 case SSH_CHANNEL_OPEN:
1400 case SSH_CHANNEL_X11_OPEN:
1401 case SSH_CHANNEL_INPUT_DRAINING:
1402 case SSH_CHANNEL_OUTPUT_DRAINING:
1403 snprintf(buf, sizeof buf, " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
1404 c->self, c->remote_name,
1405 c->type, c->remote_id,
1406 c->istate, buffer_len(&c->input),
1407 c->ostate, buffer_len(&c->output),
1409 buffer_append(&buffer, buf, strlen(buf));
1412 fatal("channel_open_message: bad channel type %d", c->type);
1416 buffer_append(&buffer, "\0", 1);
1417 cp = xstrdup(buffer_ptr(&buffer));
1418 buffer_free(&buffer);
1423 * Initiate forwarding of connections to local port "port" through the secure
1424 * channel to host:port from remote side.
1428 channel_request_local_forwarding(u_short port, const char *host,
1429 u_short host_port, int gateway_ports)
1431 int success, ch, sock, on = 1;
1432 struct addrinfo hints, *ai, *aitop;
1433 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1434 struct linger linger;
1436 if (strlen(host) > sizeof(channels[0].path) - 1)
1437 packet_disconnect("Forward host name too long.");
1440 * getaddrinfo returns a loopback address if the hostname is
1441 * set to NULL and hints.ai_flags is not AI_PASSIVE
1443 memset(&hints, 0, sizeof(hints));
1444 hints.ai_family = IPv4or6;
1445 hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
1446 hints.ai_socktype = SOCK_STREAM;
1447 snprintf(strport, sizeof strport, "%d", port);
1448 if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
1449 packet_disconnect("getaddrinfo: fatal error");
1452 for (ai = aitop; ai; ai = ai->ai_next) {
1453 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1455 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1456 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1457 error("channel_request_local_forwarding: getnameinfo failed");
1460 /* Create a port to listen for the host. */
1461 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1463 /* this is no error since kernel may not support ipv6 */
1464 verbose("socket: %.100s", strerror(errno));
1468 * Set socket options. We would like the socket to disappear
1469 * as soon as it has been closed for whatever reason.
1471 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
1473 linger.l_linger = 5;
1474 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
1475 debug("Local forwarding listening on %s port %s.", ntop, strport);
1477 /* Bind the socket to the address. */
1478 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1479 /* address can be in use ipv6 address is already bound */
1481 error("bind: %.100s", strerror(errno));
1483 verbose("bind: %.100s", strerror(errno));
1488 /* Start listening for connections on the socket. */
1489 if (listen(sock, 5) < 0) {
1490 error("listen: %.100s", strerror(errno));
1494 /* Allocate a channel number for the socket. */
1496 "port listener", SSH_CHANNEL_PORT_LISTENER,
1498 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1499 0, xstrdup("port listener"));
1500 strlcpy(channels[ch].path, host, sizeof(channels[ch].path));
1501 channels[ch].host_port = host_port;
1502 channels[ch].listening_port = port;
1506 packet_disconnect("cannot listen port: %d", port);
1507 freeaddrinfo(aitop);
1511 * Initiate forwarding of connections to port "port" on remote host through
1512 * the secure channel to host:port from local side.
1516 channel_request_remote_forwarding(u_short listen_port, const char *host_to_connect,
1517 u_short port_to_connect)
1520 /* Record locally that connection to this host/port is permitted. */
1521 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
1522 fatal("channel_request_remote_forwarding: too many forwards");
1524 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
1525 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
1526 permitted_opens[num_permitted_opens].listen_port = listen_port;
1527 num_permitted_opens++;
1529 /* Send the forward request to the remote side. */
1531 const char *address_to_bind = "0.0.0.0";
1532 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1533 packet_put_cstring("tcpip-forward");
1534 packet_put_char(0); /* boolean: want reply */
1535 packet_put_cstring(address_to_bind);
1536 packet_put_int(listen_port);
1538 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1539 packet_put_int(listen_port);
1540 packet_put_cstring(host_to_connect);
1541 packet_put_int(port_to_connect);
1543 packet_write_wait();
1545 * Wait for response from the remote side. It will send a disconnect
1546 * message on failure, and we will never see it here.
1548 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1553 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
1554 * listening for the port, and sends back a success reply (or disconnect
1555 * message if there was an error). This never returns if there was an error.
1559 channel_input_port_forward_request(int is_root, int gateway_ports)
1561 u_short port, host_port;
1564 /* Get arguments from the packet. */
1565 port = packet_get_int();
1566 hostname = packet_get_string(NULL);
1567 host_port = packet_get_int();
1570 * Check that an unprivileged user is not trying to forward a
1573 if (port < IPPORT_RESERVED && !is_root)
1574 packet_disconnect("Requested forwarding of port %d but user is not root.",
1577 * Initiate forwarding,
1579 channel_request_local_forwarding(port, hostname, host_port, gateway_ports);
1581 /* Free the argument string. */
1585 /* XXX move to aux.c */
1587 channel_connect_to(const char *host, u_short host_port)
1589 struct addrinfo hints, *ai, *aitop;
1590 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1594 memset(&hints, 0, sizeof(hints));
1595 hints.ai_family = IPv4or6;
1596 hints.ai_socktype = SOCK_STREAM;
1597 snprintf(strport, sizeof strport, "%d", host_port);
1598 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
1599 error("%.100s: unknown host (%s)", host, gai_strerror(gaierr));
1602 for (ai = aitop; ai; ai = ai->ai_next) {
1603 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1605 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1606 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1607 error("channel_connect_to: getnameinfo failed");
1610 /* Create the socket. */
1611 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1613 error("socket: %.100s", strerror(errno));
1616 /* Connect to the host/port. */
1617 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1618 error("connect %.100s port %s: %.100s", ntop, strport,
1621 continue; /* fail -- try next */
1623 break; /* success */
1626 freeaddrinfo(aitop);
1628 error("connect %.100s port %d: failed.", host, host_port);
1636 * This is called after receiving PORT_OPEN message. This attempts to
1637 * connect to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION
1638 * or CHANNEL_OPEN_FAILURE.
1642 channel_input_port_open(int type, int plen)
1645 char *host, *originator_string;
1646 int remote_channel, sock = -1, newch, i, denied;
1647 unsigned int host_len, originator_len;
1649 /* Get remote channel number. */
1650 remote_channel = packet_get_int();
1652 /* Get host name to connect to. */
1653 host = packet_get_string(&host_len);
1655 /* Get port to connect to. */
1656 host_port = packet_get_int();
1658 /* Get remote originator name. */
1659 if (have_hostname_in_open) {
1660 originator_string = packet_get_string(&originator_len);
1661 originator_len += 4; /* size of packet_int */
1663 originator_string = xstrdup("unknown (remote did not supply name)");
1664 originator_len = 0; /* no originator supplied */
1667 packet_integrity_check(plen,
1668 4 + 4 + host_len + 4 + originator_len, SSH_MSG_PORT_OPEN);
1670 /* Check if opening that port is permitted. */
1672 if (!all_opens_permitted) {
1673 /* Go trough all permitted ports. */
1674 for (i = 0; i < num_permitted_opens; i++)
1675 if (permitted_opens[i].port_to_connect == host_port &&
1676 strcmp(permitted_opens[i].host_to_connect, host) == 0)
1679 /* Check if we found the requested port among those permitted. */
1680 if (i >= num_permitted_opens) {
1681 /* The port is not permitted. */
1682 log("Received request to connect to %.100s:%d, but the request was denied.",
1687 sock = denied ? -1 : channel_connect_to(host, host_port);
1689 /* Allocate a channel for this connection. */
1690 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, originator_string);
1691 channels[newch].remote_id = remote_channel;
1693 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1694 packet_put_int(remote_channel);
1695 packet_put_int(newch);
1698 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1699 packet_put_int(remote_channel);
1706 * Creates an internet domain socket for listening for X11 connections.
1707 * Returns a suitable value for the DISPLAY variable, or NULL if an error
1711 #define NUM_SOCKS 10
1714 x11_create_display_inet(int screen_number, int x11_display_offset)
1716 int display_number, sock;
1718 struct addrinfo hints, *ai, *aitop;
1719 char strport[NI_MAXSERV];
1720 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
1722 char hostname[MAXHOSTNAMELEN];
1724 for (display_number = x11_display_offset;
1725 display_number < MAX_DISPLAYS;
1727 port = 6000 + display_number;
1728 memset(&hints, 0, sizeof(hints));
1729 hints.ai_family = IPv4or6;
1730 hints.ai_flags = AI_PASSIVE; /* XXX loopback only ? */
1731 hints.ai_socktype = SOCK_STREAM;
1732 snprintf(strport, sizeof strport, "%d", port);
1733 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
1734 error("getaddrinfo: %.100s", gai_strerror(gaierr));
1737 for (ai = aitop; ai; ai = ai->ai_next) {
1738 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1740 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1742 if (errno != EINVAL) {
1743 error("socket: %.100s", strerror(errno));
1746 debug("Socket family %d not supported [X11 disp create]", ai->ai_family);
1750 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1751 debug("bind port %d: %.100s", port, strerror(errno));
1752 shutdown(sock, SHUT_RDWR);
1758 for (n = 0; n < num_socks; n++) {
1759 shutdown(socks[n], SHUT_RDWR);
1765 socks[num_socks++] = sock;
1766 #ifndef DONT_TRY_OTHER_AF
1767 if (num_socks == NUM_SOCKS)
1776 if (display_number >= MAX_DISPLAYS) {
1777 error("Failed to allocate internet-domain X11 display socket.");
1780 /* Start listening for connections on the socket. */
1781 for (n = 0; n < num_socks; n++) {
1783 if (listen(sock, 5) < 0) {
1784 error("listen: %.100s", strerror(errno));
1785 shutdown(sock, SHUT_RDWR);
1791 /* Set up a suitable value for the DISPLAY variable. */
1793 if (gethostname(hostname, sizeof(hostname)) < 0)
1794 fatal("gethostname: %.100s", strerror(errno));
1796 #ifdef IPADDR_IN_DISPLAY
1798 * HPUX detects the local hostname in the DISPLAY variable and tries
1799 * to set up a shared memory connection to the server, which it
1800 * incorrectly supposes to be local.
1802 * The workaround - as used in later $$H and other programs - is
1803 * is to set display to the host's IP address.
1807 struct in_addr my_addr;
1809 he = gethostbyname(hostname);
1811 error("[X11-broken-fwd-hostname-workaround] Could not get "
1812 "IP address for hostname %s.", hostname);
1814 packet_send_debug("[X11-broken-fwd-hostname-workaround]"
1815 "Could not get IP address for hostname %s.", hostname);
1817 shutdown(sock, SHUT_RDWR);
1823 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
1825 /* Set DISPLAY to <ip address>:screen.display */
1826 snprintf(display, sizeof(display), "%.50s:%d.%d", inet_ntoa(my_addr),
1827 display_number, screen_number);
1829 #else /* IPADDR_IN_DISPLAY */
1830 /* Just set DISPLAY to hostname:screen.display */
1831 snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
1832 display_number, screen_number);
1833 #endif /* IPADDR_IN_DISPLAY */
1835 /* Allocate a channel for each socket. */
1836 for (n = 0; n < num_socks; n++) {
1838 (void) channel_new("x11 listener",
1839 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
1840 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
1841 0, xstrdup("X11 inet listener"));
1844 /* Return a suitable value for the DISPLAY environment variable. */
1845 return xstrdup(display);
1849 #define X_UNIX_PATH "/tmp/.X11-unix/X"
1854 connect_local_xsocket(unsigned int dnr)
1856 static const char *const x_sockets[] = {
1858 "/var/X/.X11-unix/X" "%u",
1859 "/usr/spool/sockets/X11/" "%u",
1863 struct sockaddr_un addr;
1864 const char *const * path;
1866 for (path = x_sockets; *path; ++path) {
1867 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1869 error("socket: %.100s", strerror(errno));
1870 memset(&addr, 0, sizeof(addr));
1871 addr.sun_family = AF_UNIX;
1872 snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
1873 if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
1877 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
1882 x11_connect_display(void)
1884 int display_number, sock = 0;
1885 const char *display;
1886 char buf[1024], *cp;
1887 struct addrinfo hints, *ai, *aitop;
1888 char strport[NI_MAXSERV];
1891 /* Try to open a socket for the local X server. */
1892 display = getenv("DISPLAY");
1894 error("DISPLAY not set.");
1898 * Now we decode the value of the DISPLAY variable and make a
1899 * connection to the real X server.
1903 * Check if it is a unix domain socket. Unix domain displays are in
1904 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
1906 if (strncmp(display, "unix:", 5) == 0 ||
1907 display[0] == ':') {
1908 /* Connect to the unix domain socket. */
1909 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
1910 error("Could not parse display number from DISPLAY: %.100s",
1914 /* Create a socket. */
1915 sock = connect_local_xsocket(display_number);
1919 /* OK, we now have a connection to the display. */
1923 * Connect to an inet socket. The DISPLAY value is supposedly
1924 * hostname:d[.s], where hostname may also be numeric IP address.
1926 strncpy(buf, display, sizeof(buf));
1927 buf[sizeof(buf) - 1] = 0;
1928 cp = strchr(buf, ':');
1930 error("Could not find ':' in DISPLAY: %.100s", display);
1934 /* buf now contains the host name. But first we parse the display number. */
1935 if (sscanf(cp + 1, "%d", &display_number) != 1) {
1936 error("Could not parse display number from DISPLAY: %.100s",
1941 /* Look up the host address */
1942 memset(&hints, 0, sizeof(hints));
1943 hints.ai_family = IPv4or6;
1944 hints.ai_socktype = SOCK_STREAM;
1945 snprintf(strport, sizeof strport, "%d", 6000 + display_number);
1946 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
1947 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
1950 for (ai = aitop; ai; ai = ai->ai_next) {
1951 /* Create a socket. */
1952 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1954 debug("socket: %.100s", strerror(errno));
1957 /* Connect it to the display. */
1958 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1959 debug("connect %.100s port %d: %.100s", buf,
1960 6000 + display_number, strerror(errno));
1967 freeaddrinfo(aitop);
1969 error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
1977 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
1978 * the remote channel number. We should do whatever we want, and respond
1979 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
1983 x11_input_open(int type, int plen)
1985 int remote_channel, sock = 0, newch;
1987 unsigned int remote_len;
1989 /* Get remote channel number. */
1990 remote_channel = packet_get_int();
1992 /* Get remote originator name. */
1993 if (have_hostname_in_open) {
1994 remote_host = packet_get_string(&remote_len);
1997 remote_host = xstrdup("unknown (remote did not supply name)");
2001 debug("Received X11 open request.");
2002 packet_integrity_check(plen, 4 + remote_len, SSH_SMSG_X11_OPEN);
2004 /* Obtain a connection to the real X display. */
2005 sock = x11_connect_display();
2007 /* Send refusal to the remote host. */
2008 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2009 packet_put_int(remote_channel);
2012 /* Allocate a channel for this connection. */
2013 newch = channel_allocate(
2014 (x11_saved_proto == NULL) ?
2015 SSH_CHANNEL_OPEN : SSH_CHANNEL_X11_OPEN,
2017 channels[newch].remote_id = remote_channel;
2019 /* Send a confirmation to the remote host. */
2020 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2021 packet_put_int(remote_channel);
2022 packet_put_int(newch);
2028 * Requests forwarding of X11 connections, generates fake authentication
2029 * data, and enables authentication spoofing.
2033 x11_request_forwarding_with_spoofing(int client_session_id,
2034 const char *proto, const char *data)
2036 unsigned int data_len = (unsigned int) strlen(data) / 2;
2037 unsigned int i, value;
2043 cp = getenv("DISPLAY");
2045 cp = strchr(cp, ':');
2047 cp = strchr(cp, '.');
2049 screen_number = atoi(cp + 1);
2053 /* Save protocol name. */
2054 x11_saved_proto = xstrdup(proto);
2057 * Extract real authentication data and generate fake data of the
2060 x11_saved_data = xmalloc(data_len);
2061 x11_fake_data = xmalloc(data_len);
2062 for (i = 0; i < data_len; i++) {
2063 if (sscanf(data + 2 * i, "%2x", &value) != 1)
2064 fatal("x11_request_forwarding: bad authentication data: %.100s", data);
2066 rand = arc4random();
2067 x11_saved_data[i] = value;
2068 x11_fake_data[i] = rand & 0xff;
2071 x11_saved_data_len = data_len;
2072 x11_fake_data_len = data_len;
2074 /* Convert the fake data into hex. */
2075 new_data = xmalloc(2 * data_len + 1);
2076 for (i = 0; i < data_len; i++)
2077 sprintf(new_data + 2 * i, "%02x", (unsigned char) x11_fake_data[i]);
2079 /* Send the request packet. */
2081 channel_request_start(client_session_id, "x11-req", 0);
2082 packet_put_char(0); /* XXX bool single connection */
2084 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
2086 packet_put_cstring(proto);
2087 packet_put_cstring(new_data);
2088 packet_put_int(screen_number);
2090 packet_write_wait();
2094 /* Sends a message to the server to request authentication fd forwarding. */
2097 auth_request_forwarding()
2099 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
2101 packet_write_wait();
2105 * Returns the name of the forwarded authentication socket. Returns NULL if
2106 * there is no forwarded authentication socket. The returned value points to
2111 auth_get_socket_name()
2113 return channel_forwarded_auth_socket_name;
2116 /* removes the agent forwarding socket */
2119 cleanup_socket(void)
2121 remove(channel_forwarded_auth_socket_name);
2122 rmdir(channel_forwarded_auth_socket_dir);
2126 * This if called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
2127 * This starts forwarding authentication requests.
2131 auth_input_request_forwarding(struct passwd * pw)
2134 struct sockaddr_un sunaddr;
2136 if (auth_get_socket_name() != NULL)
2137 fatal("Protocol error: authentication forwarding requested twice.");
2139 /* Temporarily drop privileged uid for mkdir/bind. */
2140 temporarily_use_uid(pw->pw_uid);
2142 /* Allocate a buffer for the socket name, and format the name. */
2143 channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
2144 channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
2145 strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
2147 /* Create private directory for socket */
2148 if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL)
2149 packet_disconnect("mkdtemp: %.100s", strerror(errno));
2150 snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME, "%s/agent.%d",
2151 channel_forwarded_auth_socket_dir, (int) getpid());
2153 if (atexit(cleanup_socket) < 0) {
2156 packet_disconnect("socket: %.100s", strerror(saved));
2158 /* Create the socket. */
2159 sock = socket(AF_UNIX, SOCK_STREAM, 0);
2161 packet_disconnect("socket: %.100s", strerror(errno));
2163 /* Bind it to the name. */
2164 memset(&sunaddr, 0, sizeof(sunaddr));
2165 sunaddr.sun_family = AF_UNIX;
2166 strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
2167 sizeof(sunaddr.sun_path));
2169 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
2170 packet_disconnect("bind: %.100s", strerror(errno));
2172 /* Restore the privileged uid. */
2175 /* Start listening on the socket. */
2176 if (listen(sock, 5) < 0)
2177 packet_disconnect("listen: %.100s", strerror(errno));
2179 /* Allocate a channel for the authentication agent socket. */
2180 newch = channel_allocate(SSH_CHANNEL_AUTH_SOCKET, sock,
2181 xstrdup("auth socket"));
2182 strlcpy(channels[newch].path, channel_forwarded_auth_socket_name,
2183 sizeof(channels[newch].path));
2186 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
2189 auth_input_open_request(int type, int plen)
2191 int remch, sock, newch;
2194 packet_integrity_check(plen, 4, type);
2196 /* Read the remote channel number from the message. */
2197 remch = packet_get_int();
2200 * Get a connection to the local authentication agent (this may again
2203 sock = ssh_get_authentication_socket();
2206 * If we could not connect the agent, send an error message back to
2207 * the server. This should never happen unless the agent dies,
2208 * because authentication forwarding is only enabled if we have an
2212 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2213 packet_put_int(remch);
2217 debug("Forwarding authentication connection.");
2220 * Dummy host name. This will be freed when the channel is freed; it
2221 * will still be valid in the packet_put_string below since the
2222 * channel cannot yet be freed at that point.
2224 dummyname = xstrdup("authentication agent connection");
2226 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
2227 channels[newch].remote_id = remch;
2229 /* Send a confirmation to the remote host. */
2230 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2231 packet_put_int(remch);
2232 packet_put_int(newch);
2237 channel_start_open(int id)
2239 Channel *c = channel_lookup(id);
2241 log("channel_open: %d: bad id", id);
2244 debug("send channel open %d", id);
2245 packet_start(SSH2_MSG_CHANNEL_OPEN);
2246 packet_put_cstring(c->ctype);
2247 packet_put_int(c->self);
2248 packet_put_int(c->local_window);
2249 packet_put_int(c->local_maxpacket);
2252 channel_open(int id)
2255 channel_start_open(id);
2259 channel_request(int id, char *service, int wantconfirm)
2261 channel_request_start(id, service, wantconfirm);
2263 debug("channel request %d: %s", id, service) ;
2266 channel_request_start(int id, char *service, int wantconfirm)
2268 Channel *c = channel_lookup(id);
2270 log("channel_request: %d: bad id", id);
2273 packet_start(SSH2_MSG_CHANNEL_REQUEST);
2274 packet_put_int(c->remote_id);
2275 packet_put_cstring(service);
2276 packet_put_char(wantconfirm);
2279 channel_register_callback(int id, int mtype, channel_callback_fn *fn, void *arg)
2281 Channel *c = channel_lookup(id);
2283 log("channel_register_callback: %d: bad id", id);
2286 c->cb_event = mtype;
2291 channel_register_cleanup(int id, channel_callback_fn *fn)
2293 Channel *c = channel_lookup(id);
2295 log("channel_register_cleanup: %d: bad id", id);
2298 c->dettach_user = fn;
2301 channel_cancel_cleanup(int id)
2303 Channel *c = channel_lookup(id);
2305 log("channel_cancel_cleanup: %d: bad id", id);
2308 c->dettach_user = NULL;
2312 channel_set_fds(int id, int rfd, int wfd, int efd, int extusage)
2314 Channel *c = channel_lookup(id);
2315 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
2316 fatal("channel_activate for non-larval channel %d.", id);
2318 channel_register_fds(c, rfd, wfd, efd, extusage);
2319 c->type = SSH_CHANNEL_OPEN;
2320 /* XXX window size? */
2321 c->local_window = c->local_window_max = c->local_maxpacket/2;
2322 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2323 packet_put_int(c->remote_id);
2324 packet_put_int(c->local_window);