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.
33 /* Maximum number of fake X11 displays to try. */
34 #define MAX_DISPLAYS 1000
36 /* Max len of agent socket */
37 #define MAX_SOCKET_NAME 100
39 /* Pointer to an array containing all allocated channels. The array is
40 dynamically extended as needed. */
41 static Channel *channels = NULL;
43 /* Size of the channel array. All slots of the array must always be
44 initialized (at least the type field); unused slots are marked with
45 type SSH_CHANNEL_FREE. */
46 static int channels_alloc = 0;
48 /* Maximum file descriptor value used in any of the channels. This is updated
49 in channel_allocate. */
50 static int channel_max_fd_value = 0;
52 /* Name and directory of socket for authentication agent forwarding. */
53 static char *channel_forwarded_auth_socket_name = NULL;
54 static char *channel_forwarded_auth_socket_dir = NULL;
56 /* Saved X11 authentication protocol name. */
57 char *x11_saved_proto = NULL;
59 /* Saved X11 authentication data. This is the real data. */
60 char *x11_saved_data = NULL;
61 unsigned int x11_saved_data_len = 0;
63 /* Fake X11 authentication data. This is what the server will be sending
64 us; we should replace any occurrences of this by the real data. */
65 char *x11_fake_data = NULL;
66 unsigned int x11_fake_data_len;
68 /* Data structure for storing which hosts are permitted for forward requests.
69 The local sides of any remote forwards are stored in this array to prevent
70 a corrupt remote server from accessing arbitrary TCP/IP ports on our
71 local network (which might be behind a firewall). */
74 char *host; /* Host name. */
75 int port; /* Port number. */
78 /* List of all permitted host/port pairs to connect. */
79 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
80 /* Number of permitted host/port pairs in the array. */
81 static int num_permitted_opens = 0;
82 /* If this is true, all opens are permitted. This is the case on the
83 server on which we have to trust the client anyway, and the user could
84 do anything after logging in anyway. */
85 static int all_opens_permitted = 0;
87 /* This is set to true if both sides support SSH_PROTOFLAG_HOST_IN_FWD_OPEN. */
88 static int have_hostname_in_open = 0;
90 /* Sets specific protocol options. */
92 void channel_set_options(int hostname_in_open)
94 have_hostname_in_open = hostname_in_open;
97 /* Permits opening to any host/port in SSH_MSG_PORT_OPEN. This is usually
98 called by the server, because the user could connect to any port anyway,
99 and the server has no way to know but to trust the client anyway. */
101 void channel_permit_all_opens()
103 all_opens_permitted = 1;
106 /* Allocate a new channel object and set its type and socket.
107 This will cause remote_name to be freed. */
109 int channel_allocate(int type, int sock, char *remote_name)
114 /* Update the maximum file descriptor value. */
115 if (sock > channel_max_fd_value)
116 channel_max_fd_value = sock;
118 /* Do initial allocation if this is the first call. */
119 if (channels_alloc == 0)
122 channels = xmalloc(channels_alloc * sizeof(Channel));
123 for (i = 0; i < channels_alloc; i++)
124 channels[i].type = SSH_CHANNEL_FREE;
126 /* Kludge: arrange a call to channel_stop_listening if we terminate
128 fatal_add_cleanup((void (*)(void *))channel_stop_listening, NULL);
131 /* Try to find a free slot where to put the new channel. */
132 for (found = -1, i = 0; i < channels_alloc; i++)
133 if (channels[i].type == SSH_CHANNEL_FREE)
135 /* Found a free slot. */
142 /* There are no free slots. Take last+1 slot and expand the array. */
143 found = channels_alloc;
144 channels_alloc += 10;
145 debug("channel: expanding %d", channels_alloc);
146 channels = xrealloc(channels, channels_alloc * sizeof(Channel));
147 for (i = found; i < channels_alloc; i++)
148 channels[i].type = SSH_CHANNEL_FREE;
151 /* Initialize and return new channel number. */
153 buffer_init(&c->input);
154 buffer_init(&c->output);
155 chan_init_iostates(c);
160 c->remote_name = remote_name;
161 debug("channel %d: new [%s]", found, remote_name);
165 /* Free the channel and close its socket. */
167 void channel_free(int channel)
169 assert(channel >= 0 && channel < channels_alloc &&
170 channels[channel].type != SSH_CHANNEL_FREE);
172 shutdown(channels[channel].sock, SHUT_RDWR);
173 close(channels[channel].sock);
174 buffer_free(&channels[channel].input);
175 buffer_free(&channels[channel].output);
176 channels[channel].type = SSH_CHANNEL_FREE;
177 if (channels[channel].remote_name)
179 xfree(channels[channel].remote_name);
180 channels[channel].remote_name = NULL;
184 /* This is called just before select() to add any bits relevant to
185 channels in the select bitmasks. */
187 void channel_prepare_select(fd_set *readset, fd_set *writeset)
192 unsigned int proto_len, data_len;
194 for (i = 0; i < channels_alloc; i++)
200 case SSH_CHANNEL_X11_LISTENER:
201 case SSH_CHANNEL_PORT_LISTENER:
202 case SSH_CHANNEL_AUTH_SOCKET:
203 FD_SET(ch->sock, readset);
206 case SSH_CHANNEL_OPEN:
208 if (buffer_len(&ch->input) < 32768)
209 FD_SET(ch->sock, readset);
210 if (buffer_len(&ch->output) > 0)
211 FD_SET(ch->sock, writeset);
214 /* test whether sockets are 'alive' for read/write */
215 if (ch->istate == CHAN_INPUT_OPEN)
216 if (buffer_len(&ch->input) < 32768)
217 FD_SET(ch->sock, readset);
218 if (ch->ostate == CHAN_OUTPUT_OPEN || ch->ostate == CHAN_OUTPUT_WAIT_DRAIN){
219 if (buffer_len(&ch->output) > 0){
220 FD_SET(ch->sock, writeset);
221 }else if(ch->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
227 case SSH_CHANNEL_INPUT_DRAINING:
229 fatal("cannot happen: IN_DRAIN");
230 if (buffer_len(&ch->input) == 0)
232 packet_start(SSH_MSG_CHANNEL_CLOSE);
233 packet_put_int(ch->remote_id);
235 ch->type = SSH_CHANNEL_CLOSED;
236 debug("Closing channel %d after input drain.", i);
241 case SSH_CHANNEL_OUTPUT_DRAINING:
243 fatal("cannot happen: OUT_DRAIN");
244 if (buffer_len(&ch->output) == 0)
246 /* debug("Freeing channel %d after output drain.", i); */
250 FD_SET(ch->sock, writeset);
253 case SSH_CHANNEL_X11_OPEN:
254 /* This is a special state for X11 authentication spoofing. An
255 opened X11 connection (when authentication spoofing is being
256 done) remains in this state until the first packet has been
257 completely read. The authentication data in that packet is
258 then substituted by the real data if it matches the fake data,
259 and the channel is put into normal mode. */
261 /* Check if the fixed size part of the packet is in buffer. */
262 if (buffer_len(&ch->output) < 12)
265 /* Parse the lengths of variable-length fields. */
266 ucp = (unsigned char *)buffer_ptr(&ch->output);
268 { /* Byte order MSB first. */
269 proto_len = 256 * ucp[6] + ucp[7];
270 data_len = 256 * ucp[8] + ucp[9];
274 { /* Byte order LSB first. */
275 proto_len = ucp[6] + 256 * ucp[7];
276 data_len = ucp[8] + 256 * ucp[9];
280 debug("Initial X11 packet contains bad byte order byte: 0x%x",
282 ch->type = SSH_CHANNEL_OPEN;
286 /* Check if the whole packet is in buffer. */
287 if (buffer_len(&ch->output) <
288 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
291 /* Check if authentication protocol matches. */
292 if (proto_len != strlen(x11_saved_proto) ||
293 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0)
295 debug("X11 connection uses different authentication protocol.");
296 ch->type = SSH_CHANNEL_OPEN;
300 /* Check if authentication data matches our fake data. */
301 if (data_len != x11_fake_data_len ||
302 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
303 x11_fake_data, x11_fake_data_len) != 0)
305 debug("X11 auth data does not match fake data.");
306 ch->type = SSH_CHANNEL_OPEN;
310 /* Received authentication protocol and data match our fake data.
311 Substitute the fake data with real data. */
312 assert(x11_fake_data_len == x11_saved_data_len);
313 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
314 x11_saved_data, x11_saved_data_len);
316 /* Start normal processing for the channel. */
317 ch->type = SSH_CHANNEL_OPEN;
321 /* We have received an X11 connection that has bad authentication
323 log("X11 connection rejected because of wrong authentication.\r\n");
324 buffer_clear(&ch->input);
325 buffer_clear(&ch->output);
329 ch->type = SSH_CHANNEL_CLOSED;
330 packet_start(SSH_MSG_CHANNEL_CLOSE);
331 packet_put_int(ch->remote_id);
334 debug("X11 rejected %d i%d/o%d", ch->self, ch->istate, ch->ostate);
335 chan_read_failed(ch);
336 chan_write_failed(ch);
337 debug("X11 rejected %d i%d/o%d", ch->self, ch->istate, ch->ostate);
341 case SSH_CHANNEL_FREE:
348 /* After select, perform any appropriate operations for channels which
349 have events pending. */
351 void channel_after_select(fd_set *readset, fd_set *writeset)
353 struct sockaddr addr;
354 int addrlen, newsock, i, newch, len;
356 char buf[16384], *remote_hostname;
358 /* Loop over all channels... */
359 for (i = 0; i < channels_alloc; i++)
364 case SSH_CHANNEL_X11_LISTENER:
365 /* This is our fake X11 server socket. */
366 if (FD_ISSET(ch->sock, readset))
368 debug("X11 connection requested.");
369 addrlen = sizeof(addr);
370 newsock = accept(ch->sock, &addr, &addrlen);
373 error("accept: %.100s", strerror(errno));
376 remote_hostname = get_remote_hostname(newsock);
377 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
378 remote_hostname, get_peer_port(newsock));
379 xfree(remote_hostname);
380 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
382 packet_start(SSH_SMSG_X11_OPEN);
383 packet_put_int(newch);
384 if (have_hostname_in_open)
385 packet_put_string(buf, strlen(buf));
390 case SSH_CHANNEL_PORT_LISTENER:
391 /* This socket is listening for connections to a forwarded TCP/IP
393 if (FD_ISSET(ch->sock, readset))
395 debug("Connection to port %d forwarding to %.100s:%d requested.",
396 ch->listening_port, ch->path, ch->host_port);
397 addrlen = sizeof(addr);
398 newsock = accept(ch->sock, &addr, &addrlen);
401 error("accept: %.100s", strerror(errno));
404 remote_hostname = get_remote_hostname(newsock);
405 snprintf(buf, sizeof buf, "listen port %d:%.100s:%d, connect from %.200s:%d",
406 ch->listening_port, ch->path, ch->host_port,
407 remote_hostname, get_peer_port(newsock));
408 xfree(remote_hostname);
409 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
411 packet_start(SSH_MSG_PORT_OPEN);
412 packet_put_int(newch);
413 packet_put_string(ch->path, strlen(ch->path));
414 packet_put_int(ch->host_port);
415 if (have_hostname_in_open)
416 packet_put_string(buf, strlen(buf));
421 case SSH_CHANNEL_AUTH_SOCKET:
422 /* This is the authentication agent socket listening for connections
424 if (FD_ISSET(ch->sock, readset))
428 newsock = accept(ch->sock, &addr, &len);
431 error("accept from auth socket: %.100s", strerror(errno));
435 nchan = channel_allocate(SSH_CHANNEL_OPENING, newsock,
436 xstrdup("accepted auth socket"));
437 packet_start(SSH_SMSG_AGENT_OPEN);
438 packet_put_int(nchan);
443 case SSH_CHANNEL_OPEN:
444 /* This is an open two-way communication channel. It is not of
445 interest to us at this point what kind of data is being
448 /* Read available incoming data and append it to buffer;
449 shutdown socket, if read or write failes */
450 if (FD_ISSET(ch->sock, readset))
452 len = read(ch->sock, buf, sizeof(buf));
456 buffer_consume(&ch->output, buffer_len(&ch->output));
457 ch->type = SSH_CHANNEL_INPUT_DRAINING;
458 debug("Channel %d status set to input draining.", i);
460 chan_read_failed(ch);
464 buffer_append(&ch->input, buf, len);
466 /* Send buffered output data to the socket. */
467 if (FD_ISSET(ch->sock, writeset) && buffer_len(&ch->output) > 0)
469 len = write(ch->sock, buffer_ptr(&ch->output),
470 buffer_len(&ch->output));
474 buffer_consume(&ch->output, buffer_len(&ch->output));
475 debug("Channel %d status set to input draining.", i);
476 ch->type = SSH_CHANNEL_INPUT_DRAINING;
478 chan_write_failed(ch);
482 buffer_consume(&ch->output, len);
486 case SSH_CHANNEL_OUTPUT_DRAINING:
488 fatal("cannot happen: OUT_DRAIN");
489 /* Send buffered output data to the socket. */
490 if (FD_ISSET(ch->sock, writeset) && buffer_len(&ch->output) > 0)
492 len = write(ch->sock, buffer_ptr(&ch->output),
493 buffer_len(&ch->output));
495 buffer_consume(&ch->output, buffer_len(&ch->output));
497 buffer_consume(&ch->output, len);
501 case SSH_CHANNEL_X11_OPEN:
502 case SSH_CHANNEL_FREE:
509 /* If there is data to send to the connection, send some of it now. */
511 void channel_output_poll()
516 for (i = 0; i < channels_alloc; i++)
519 /* We are only interested in channels that can have buffered incoming
521 if (ch->type != SSH_CHANNEL_OPEN &&
522 ch->type != SSH_CHANNEL_INPUT_DRAINING)
525 /* Get the amount of buffered data for this channel. */
526 len = buffer_len(&ch->input);
529 /* Send some data for the other side over the secure connection. */
530 if (packet_is_interactive())
538 len = 16384; /* Keep the packets at reasonable size. */
540 packet_start(SSH_MSG_CHANNEL_DATA);
541 packet_put_int(ch->remote_id);
542 packet_put_string(buffer_ptr(&ch->input), len);
544 buffer_consume(&ch->input, len);
546 else if(ch->istate == CHAN_INPUT_WAIT_DRAIN)
549 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
550 /* input-buffer is empty and read-socket shutdown:
551 tell peer, that we will not send more data: send IEOF */
557 /* This is called when a packet of type CHANNEL_DATA has just been received.
558 The message type has already been consumed, but channel number and data
561 void channel_input_data(int payload_len)
565 unsigned int data_len;
567 /* Get the channel number and verify it. */
568 channel = packet_get_int();
569 if (channel < 0 || channel >= channels_alloc ||
570 channels[channel].type == SSH_CHANNEL_FREE)
571 packet_disconnect("Received data for nonexistent channel %d.", channel);
573 /* Ignore any data for non-open channels (might happen on close) */
574 if (channels[channel].type != SSH_CHANNEL_OPEN &&
575 channels[channel].type != SSH_CHANNEL_X11_OPEN)
579 data = packet_get_string(&data_len);
580 packet_integrity_check(payload_len, 4 + 4+data_len, SSH_MSG_CHANNEL_DATA);
581 buffer_append(&channels[channel].output, data, data_len);
585 /* Returns true if no channel has too much buffered data, and false if
586 one or more channel is overfull. */
588 int channel_not_very_much_buffered_data()
593 for (i = 0; i < channels_alloc; i++)
598 case SSH_CHANNEL_X11_LISTENER:
599 case SSH_CHANNEL_PORT_LISTENER:
600 case SSH_CHANNEL_AUTH_SOCKET:
602 case SSH_CHANNEL_OPEN:
603 if (buffer_len(&ch->input) > 32768)
605 if (buffer_len(&ch->output) > 32768)
608 case SSH_CHANNEL_INPUT_DRAINING:
609 case SSH_CHANNEL_OUTPUT_DRAINING:
610 case SSH_CHANNEL_X11_OPEN:
611 case SSH_CHANNEL_FREE:
619 /* This is called after receiving CHANNEL_CLOSE/IEOF. */
621 void channel_input_close()
625 /* Get the channel number and verify it. */
626 channel = packet_get_int();
627 if (channel < 0 || channel >= channels_alloc ||
628 channels[channel].type == SSH_CHANNEL_FREE)
629 packet_disconnect("Received data for nonexistent channel %d.", channel);
632 /* proto version 1.5 overloads CLOSE with IEOF */
633 chan_rcvd_ieof(&channels[channel]);
637 /* Send a confirmation that we have closed the channel and no more data is
639 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
640 packet_put_int(channels[channel].remote_id);
643 /* If the channel is in closed state, we have sent a close request, and
644 the other side will eventually respond with a confirmation. Thus,
645 we cannot free the channel here, because then there would be no-one to
646 receive the confirmation. The channel gets freed when the confirmation
648 if (channels[channel].type != SSH_CHANNEL_CLOSED)
650 /* Not a closed channel - mark it as draining, which will cause it to
652 buffer_consume(&channels[channel].input,
653 buffer_len(&channels[channel].input));
654 channels[channel].type = SSH_CHANNEL_OUTPUT_DRAINING;
655 /* debug("Setting status to output draining; output len = %d",
656 buffer_len(&channels[channel].output)); */
660 /* This is called after receiving CHANNEL_CLOSE_CONFIRMATION/OCLOSE. */
662 void channel_input_close_confirmation()
666 /* Get the channel number and verify it. */
667 channel = packet_get_int();
668 if (channel < 0 || channel >= channels_alloc)
669 packet_disconnect("Received close confirmation for out-of-range channel %d.",
673 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
674 chan_rcvd_oclose(&channels[channel]);
678 if (channels[channel].type != SSH_CHANNEL_CLOSED)
679 packet_disconnect("Received close confirmation for non-closed channel %d (type %d).",
680 channel, channels[channel].type);
682 /* Free the channel. */
683 channel_free(channel);
686 /* This is called after receiving CHANNEL_OPEN_CONFIRMATION. */
688 void channel_input_open_confirmation()
690 int channel, remote_channel;
692 /* Get the channel number and verify it. */
693 channel = packet_get_int();
694 if (channel < 0 || channel >= channels_alloc ||
695 channels[channel].type != SSH_CHANNEL_OPENING)
696 packet_disconnect("Received open confirmation for non-opening channel %d.",
699 /* Get remote side's id for this channel. */
700 remote_channel = packet_get_int();
702 /* Record the remote channel number and mark that the channel is now open. */
703 channels[channel].remote_id = remote_channel;
704 channels[channel].type = SSH_CHANNEL_OPEN;
707 /* This is called after receiving CHANNEL_OPEN_FAILURE from the other side. */
709 void channel_input_open_failure()
713 /* Get the channel number and verify it. */
714 channel = packet_get_int();
715 if (channel < 0 || channel >= channels_alloc ||
716 channels[channel].type != SSH_CHANNEL_OPENING)
717 packet_disconnect("Received open failure for non-opening channel %d.",
720 /* Free the channel. This will also close the socket. */
721 channel_free(channel);
724 /* Stops listening for channels, and removes any unix domain sockets that
727 void channel_stop_listening()
730 for (i = 0; i < channels_alloc; i++)
732 switch (channels[i].type)
734 case SSH_CHANNEL_AUTH_SOCKET:
735 close(channels[i].sock);
736 remove(channels[i].path);
739 case SSH_CHANNEL_PORT_LISTENER:
740 case SSH_CHANNEL_X11_LISTENER:
741 close(channels[i].sock);
750 /* Closes the sockets of all channels. This is used to close extra file
751 descriptors after a fork. */
753 void channel_close_all()
756 for (i = 0; i < channels_alloc; i++)
758 if (channels[i].type != SSH_CHANNEL_FREE)
759 close(channels[i].sock);
763 /* Returns the maximum file descriptor number used by the channels. */
767 return channel_max_fd_value;
770 /* Returns true if any channel is still open. */
772 int channel_still_open()
775 for (i = 0; i < channels_alloc; i++)
776 switch (channels[i].type)
778 case SSH_CHANNEL_FREE:
779 case SSH_CHANNEL_X11_LISTENER:
780 case SSH_CHANNEL_PORT_LISTENER:
781 case SSH_CHANNEL_CLOSED:
782 case SSH_CHANNEL_AUTH_SOCKET:
784 case SSH_CHANNEL_OPENING:
785 case SSH_CHANNEL_OPEN:
786 case SSH_CHANNEL_X11_OPEN:
788 case SSH_CHANNEL_INPUT_DRAINING:
789 case SSH_CHANNEL_OUTPUT_DRAINING:
791 fatal("cannot happen: OUT_DRAIN");
794 fatal("channel_still_open: bad channel type %d", channels[i].type);
800 /* Returns a message describing the currently open forwarded
801 connections, suitable for sending to the client. The message
802 contains crlf pairs for newlines. */
804 char *channel_open_message()
810 buffer_init(&buffer);
811 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
812 buffer_append(&buffer, buf, strlen(buf));
813 for (i = 0; i < channels_alloc; i++){
814 Channel *c=&channels[i];
817 case SSH_CHANNEL_FREE:
818 case SSH_CHANNEL_X11_LISTENER:
819 case SSH_CHANNEL_PORT_LISTENER:
820 case SSH_CHANNEL_CLOSED:
821 case SSH_CHANNEL_AUTH_SOCKET:
823 case SSH_CHANNEL_OPENING:
824 case SSH_CHANNEL_OPEN:
825 case SSH_CHANNEL_X11_OPEN:
826 case SSH_CHANNEL_INPUT_DRAINING:
827 case SSH_CHANNEL_OUTPUT_DRAINING:
828 snprintf(buf, sizeof buf, " #%d %.300s (t%d r%d i%d o%d)\r\n",
829 c->self,c->remote_name,
830 c->type,c->remote_id, c->istate,c->ostate);
831 buffer_append(&buffer, buf, strlen(buf));
834 fatal("channel_still_open: bad channel type %d", c->type);
838 buffer_append(&buffer, "\0", 1);
839 cp = xstrdup(buffer_ptr(&buffer));
840 buffer_free(&buffer);
844 /* Initiate forwarding of connections to local port "port" through the secure
845 channel to host:port from remote side. */
847 void channel_request_local_forwarding(int port, const char *host,
851 struct sockaddr_in sin;
852 extern Options options;
854 if (strlen(host) > sizeof(channels[0].path) - 1)
855 packet_disconnect("Forward host name too long.");
857 /* Create a port to listen for the host. */
858 sock = socket(AF_INET, SOCK_STREAM, 0);
860 packet_disconnect("socket: %.100s", strerror(errno));
862 /* Initialize socket address. */
863 memset(&sin, 0, sizeof(sin));
864 sin.sin_family = AF_INET;
865 if (options.gateway_ports == 1)
866 sin.sin_addr.s_addr = htonl(INADDR_ANY);
868 sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
869 sin.sin_port = htons(port);
871 /* Bind the socket to the address. */
872 if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
873 packet_disconnect("bind: %.100s", strerror(errno));
875 /* Start listening for connections on the socket. */
876 if (listen(sock, 5) < 0)
877 packet_disconnect("listen: %.100s", strerror(errno));
879 /* Allocate a channel number for the socket. */
880 ch = channel_allocate(SSH_CHANNEL_PORT_LISTENER, sock,
881 xstrdup("port listener"));
882 strcpy(channels[ch].path, host); /* note: host name stored here */
883 channels[ch].host_port = host_port; /* port on host to connect to */
884 channels[ch].listening_port = port; /* port being listened */
887 /* Initiate forwarding of connections to port "port" on remote host through
888 the secure channel to host:port from local side. */
890 void channel_request_remote_forwarding(int port, const char *host,
894 /* Record locally that connection to this host/port is permitted. */
895 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
896 fatal("channel_request_remote_forwarding: too many forwards");
897 permitted_opens[num_permitted_opens].host = xstrdup(host);
898 permitted_opens[num_permitted_opens].port = remote_port;
899 num_permitted_opens++;
901 /* Send the forward request to the remote side. */
902 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
903 packet_put_int(port);
904 packet_put_string(host, strlen(host));
905 packet_put_int(remote_port);
909 /* Wait for response from the remote side. It will send a disconnect
910 message on failure, and we will never see it here. */
911 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
914 /* This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
915 listening for the port, and sends back a success reply (or disconnect
916 message if there was an error). This never returns if there was an
919 void channel_input_port_forward_request(int is_root)
924 /* Get arguments from the packet. */
925 port = packet_get_int();
926 hostname = packet_get_string(NULL);
927 host_port = packet_get_int();
929 /* Port numbers are 16 bit quantities. */
930 if ((port & 0xffff) != port)
931 packet_disconnect("Requested forwarding of nonexistent port %d.", port);
933 /* Check that an unprivileged user is not trying to forward a privileged
935 if (port < IPPORT_RESERVED && !is_root)
936 packet_disconnect("Requested forwarding of port %d but user is not root.",
939 /* Initiate forwarding. */
940 channel_request_local_forwarding(port, hostname, host_port);
942 /* Free the argument string. */
946 /* This is called after receiving PORT_OPEN message. This attempts to connect
947 to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION or
948 CHANNEL_OPEN_FAILURE. */
950 void channel_input_port_open(int payload_len)
952 int remote_channel, sock, newch, host_port, i;
953 struct sockaddr_in sin;
954 char *host, *originator_string;
956 int host_len, originator_len;
958 /* Get remote channel number. */
959 remote_channel = packet_get_int();
961 /* Get host name to connect to. */
962 host = packet_get_string(&host_len);
964 /* Get port to connect to. */
965 host_port = packet_get_int();
967 /* Get remote originator name. */
968 if (have_hostname_in_open)
969 originator_string = packet_get_string(&originator_len);
971 originator_string = xstrdup("unknown (remote did not supply name)");
973 packet_integrity_check(payload_len,
974 4 + 4 + host_len + 4 + 4 + originator_len,
977 /* Check if opening that port is permitted. */
978 if (!all_opens_permitted)
980 /* Go trough all permitted ports. */
981 for (i = 0; i < num_permitted_opens; i++)
982 if (permitted_opens[i].port == host_port &&
983 strcmp(permitted_opens[i].host, host) == 0)
986 /* Check if we found the requested port among those permitted. */
987 if (i >= num_permitted_opens)
989 /* The port is not permitted. */
990 log("Received request to connect to %.100s:%d, but the request was denied.",
992 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
993 packet_put_int(remote_channel);
998 memset(&sin, 0, sizeof(sin));
999 sin.sin_addr.s_addr = inet_addr(host);
1000 if ((sin.sin_addr.s_addr & 0xffffffff) != 0xffffffff)
1002 /* It was a valid numeric host address. */
1003 sin.sin_family = AF_INET;
1007 /* Look up the host address from the name servers. */
1008 hp = gethostbyname(host);
1011 error("%.100s: unknown host.", host);
1014 if (!hp->h_addr_list[0])
1016 error("%.100s: host has no IP address.", host);
1019 sin.sin_family = hp->h_addrtype;
1020 memcpy(&sin.sin_addr, hp->h_addr_list[0],
1021 sizeof(sin.sin_addr));
1023 sin.sin_port = htons(host_port);
1025 /* Create the socket. */
1026 sock = socket(sin.sin_family, SOCK_STREAM, 0);
1029 error("socket: %.100s", strerror(errno));
1033 /* Connect to the host/port. */
1034 if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1036 error("connect %.100s:%d: %.100s", host, host_port,
1042 /* Successful connection. */
1044 /* Allocate a channel for this connection. */
1045 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, originator_string);
1046 channels[newch].remote_id = remote_channel;
1048 /* Send a confirmation to the remote host. */
1049 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1050 packet_put_int(remote_channel);
1051 packet_put_int(newch);
1054 /* Free the argument string. */
1060 /* Free the argument string. */
1063 /* Send refusal to the remote host. */
1064 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1065 packet_put_int(remote_channel);
1069 /* Creates an internet domain socket for listening for X11 connections.
1070 Returns a suitable value for the DISPLAY variable, or NULL if an error
1073 char *x11_create_display_inet(int screen_number)
1075 extern ServerOptions options;
1076 int display_number, port, sock;
1077 struct sockaddr_in sin;
1079 char hostname[MAXHOSTNAMELEN];
1081 for (display_number = options.x11_display_offset; display_number < MAX_DISPLAYS; display_number++)
1083 port = 6000 + display_number;
1084 memset(&sin, 0, sizeof(sin));
1085 sin.sin_family = AF_INET;
1086 sin.sin_addr.s_addr = htonl(INADDR_ANY);
1087 sin.sin_port = htons(port);
1089 sock = socket(AF_INET, SOCK_STREAM, 0);
1092 error("socket: %.100s", strerror(errno));
1096 if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1098 debug("bind port %d: %.100s", port, strerror(errno));
1099 shutdown(sock, SHUT_RDWR);
1105 if (display_number >= MAX_DISPLAYS)
1107 error("Failed to allocate internet-domain X11 display socket.");
1111 /* Start listening for connections on the socket. */
1112 if (listen(sock, 5) < 0)
1114 error("listen: %.100s", strerror(errno));
1115 shutdown(sock, SHUT_RDWR);
1120 /* Set up a suitable value for the DISPLAY variable. */
1121 if (gethostname(hostname, sizeof(hostname)) < 0)
1122 fatal("gethostname: %.100s", strerror(errno));
1123 snprintf(buf, sizeof buf, "%.400s:%d.%d", hostname,
1124 display_number, screen_number);
1126 /* Allocate a channel for the socket. */
1127 (void)channel_allocate(SSH_CHANNEL_X11_LISTENER, sock,
1128 xstrdup("X11 inet listener"));
1130 /* Return a suitable value for the DISPLAY environment variable. */
1131 return xstrdup(buf);
1135 #define X_UNIX_PATH "/tmp/.X11-unix/X"
1140 connect_local_xsocket(unsigned dnr)
1142 static const char *const x_sockets[] = {
1144 "/var/X/.X11-unix/X" "%u",
1145 "/usr/spool/sockets/X11/" "%u",
1149 struct sockaddr_un addr;
1150 const char *const *path;
1152 for (path = x_sockets; *path; ++path)
1154 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1156 error("socket: %.100s", strerror(errno));
1157 memset(&addr, 0, sizeof(addr));
1158 addr.sun_family = AF_UNIX;
1159 snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
1160 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
1164 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
1169 /* This is called when SSH_SMSG_X11_OPEN is received. The packet contains
1170 the remote channel number. We should do whatever we want, and respond
1171 with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE. */
1173 void x11_input_open(int payload_len)
1175 int remote_channel, display_number, sock, newch;
1176 const char *display;
1177 struct sockaddr_in sin;
1178 char buf[1024], *cp, *remote_host;
1182 /* Get remote channel number. */
1183 remote_channel = packet_get_int();
1185 /* Get remote originator name. */
1186 if (have_hostname_in_open)
1187 remote_host = packet_get_string(&remote_len);
1189 remote_host = xstrdup("unknown (remote did not supply name)");
1191 debug("Received X11 open request.");
1192 packet_integrity_check(payload_len, 4 + 4+remote_len, SSH_SMSG_X11_OPEN);
1194 /* Try to open a socket for the local X server. */
1195 display = getenv("DISPLAY");
1198 error("DISPLAY not set.");
1202 /* Now we decode the value of the DISPLAY variable and make a connection
1203 to the real X server. */
1205 /* Check if it is a unix domain socket. Unix domain displays are in one
1206 of the following formats: unix:d[.s], :d[.s], ::d[.s] */
1207 if (strncmp(display, "unix:", 5) == 0 ||
1210 /* Connect to the unix domain socket. */
1211 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1)
1213 error("Could not parse display number from DISPLAY: %.100s",
1217 /* Create a socket. */
1218 sock = connect_local_xsocket(display_number);
1222 /* OK, we now have a connection to the display. */
1226 /* Connect to an inet socket. The DISPLAY value is supposedly
1227 hostname:d[.s], where hostname may also be numeric IP address. */
1228 strncpy(buf, display, sizeof(buf));
1229 buf[sizeof(buf) - 1] = 0;
1230 cp = strchr(buf, ':');
1233 error("Could not find ':' in DISPLAY: %.100s", display);
1237 /* buf now contains the host name. But first we parse the display number. */
1238 if (sscanf(cp + 1, "%d", &display_number) != 1)
1240 error("Could not parse display number from DISPLAY: %.100s",
1245 /* Try to parse the host name as a numeric IP address. */
1246 memset(&sin, 0, sizeof(sin));
1247 sin.sin_addr.s_addr = inet_addr(buf);
1248 if ((sin.sin_addr.s_addr & 0xffffffff) != 0xffffffff)
1250 /* It was a valid numeric host address. */
1251 sin.sin_family = AF_INET;
1255 /* Not a numeric IP address. */
1256 /* Look up the host address from the name servers. */
1257 hp = gethostbyname(buf);
1260 error("%.100s: unknown host.", buf);
1263 if (!hp->h_addr_list[0])
1265 error("%.100s: host has no IP address.", buf);
1268 sin.sin_family = hp->h_addrtype;
1269 memcpy(&sin.sin_addr, hp->h_addr_list[0],
1270 sizeof(sin.sin_addr));
1272 /* Set port number. */
1273 sin.sin_port = htons(6000 + display_number);
1275 /* Create a socket. */
1276 sock = socket(sin.sin_family, SOCK_STREAM, 0);
1279 error("socket: %.100s", strerror(errno));
1282 /* Connect it to the display. */
1283 if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1285 error("connect %.100s:%d: %.100s", buf, 6000 + display_number,
1292 /* We have successfully obtained a connection to the real X display. */
1294 /* Allocate a channel for this connection. */
1295 if (x11_saved_proto == NULL)
1296 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, remote_host);
1298 newch = channel_allocate(SSH_CHANNEL_X11_OPEN, sock, remote_host);
1299 channels[newch].remote_id = remote_channel;
1301 /* Send a confirmation to the remote host. */
1302 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1303 packet_put_int(remote_channel);
1304 packet_put_int(newch);
1310 /* Send refusal to the remote host. */
1311 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1312 packet_put_int(remote_channel);
1316 /* Requests forwarding of X11 connections, generates fake authentication
1317 data, and enables authentication spoofing. */
1319 void x11_request_forwarding_with_spoofing(const char *proto, const char *data)
1321 unsigned int data_len = (unsigned int)strlen(data) / 2;
1322 unsigned int i, value;
1328 cp = getenv("DISPLAY");
1330 cp = strchr(cp, ':');
1332 cp = strchr(cp, '.');
1334 screen_number = atoi(cp + 1);
1338 /* Save protocol name. */
1339 x11_saved_proto = xstrdup(proto);
1341 /* Extract real authentication data and generate fake data of the same
1343 x11_saved_data = xmalloc(data_len);
1344 x11_fake_data = xmalloc(data_len);
1345 for (i = 0; i < data_len; i++)
1347 if (sscanf(data + 2 * i, "%2x", &value) != 1)
1348 fatal("x11_request_forwarding: bad authentication data: %.100s", data);
1350 rand = arc4random();
1351 x11_saved_data[i] = value;
1352 x11_fake_data[i] = rand & 0xff;
1355 x11_saved_data_len = data_len;
1356 x11_fake_data_len = data_len;
1358 /* Convert the fake data into hex. */
1359 new_data = xmalloc(2 * data_len + 1);
1360 for (i = 0; i < data_len; i++)
1361 sprintf(new_data + 2 * i, "%02x", (unsigned char)x11_fake_data[i]);
1363 /* Send the request packet. */
1364 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
1365 packet_put_string(proto, strlen(proto));
1366 packet_put_string(new_data, strlen(new_data));
1367 packet_put_int(screen_number);
1369 packet_write_wait();
1373 /* Sends a message to the server to request authentication fd forwarding. */
1375 void auth_request_forwarding()
1377 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
1379 packet_write_wait();
1382 /* Returns the name of the forwarded authentication socket. Returns NULL
1383 if there is no forwarded authentication socket. The returned value
1384 points to a static buffer. */
1386 char *auth_get_socket_name()
1388 return channel_forwarded_auth_socket_name;
1391 /* removes the agent forwarding socket */
1393 void cleanup_socket(void) {
1394 remove(channel_forwarded_auth_socket_name);
1395 rmdir(channel_forwarded_auth_socket_dir);
1398 /* This if called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
1399 This starts forwarding authentication requests. */
1401 void auth_input_request_forwarding(struct passwd *pw)
1404 struct sockaddr_un sunaddr;
1406 if (auth_get_socket_name() != NULL)
1407 fatal("Protocol error: authentication forwarding requested twice.");
1409 /* Temporarily drop privileged uid for mkdir/bind. */
1410 temporarily_use_uid(pw->pw_uid);
1412 /* Allocate a buffer for the socket name, and format the name. */
1413 channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
1414 channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
1415 strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
1417 /* Create private directory for socket */
1418 if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL)
1419 packet_disconnect("mkdtemp: %.100s", strerror(errno));
1420 snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME,
1421 "%s/agent.%d", channel_forwarded_auth_socket_dir, (int)getpid());
1423 if (atexit(cleanup_socket) < 0) {
1426 packet_disconnect("socket: %.100s", strerror(saved));
1429 /* Create the socket. */
1430 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1432 packet_disconnect("socket: %.100s", strerror(errno));
1434 /* Bind it to the name. */
1435 memset(&sunaddr, 0, sizeof(sunaddr));
1436 sunaddr.sun_family = AF_UNIX;
1437 strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
1438 sizeof(sunaddr.sun_path));
1440 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0)
1441 packet_disconnect("bind: %.100s", strerror(errno));
1443 /* Restore the privileged uid. */
1446 /* Start listening on the socket. */
1447 if (listen(sock, 5) < 0)
1448 packet_disconnect("listen: %.100s", strerror(errno));
1450 /* Allocate a channel for the authentication agent socket. */
1451 newch = channel_allocate(SSH_CHANNEL_AUTH_SOCKET, sock,
1452 xstrdup("auth socket"));
1453 strcpy(channels[newch].path, channel_forwarded_auth_socket_name);
1456 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
1458 void auth_input_open_request()
1460 int remch, sock, newch;
1463 /* Read the remote channel number from the message. */
1464 remch = packet_get_int();
1466 /* Get a connection to the local authentication agent (this may again get
1468 sock = ssh_get_authentication_socket();
1470 /* If we could not connect the agent, send an error message back to
1471 the server. This should never happen unless the agent
1472 dies, because authentication forwarding is only enabled if we have an
1475 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1476 packet_put_int(remch);
1481 debug("Forwarding authentication connection.");
1483 /* Dummy host name. This will be freed when the channel is freed; it will
1484 still be valid in the packet_put_string below since the channel cannot
1485 yet be freed at that point. */
1486 dummyname = xstrdup("authentication agent connection");
1488 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
1489 channels[newch].remote_id = remch;
1491 /* Send a confirmation to the remote host. */
1492 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1493 packet_put_int(remch);
1494 packet_put_int(newch);