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)
113 /* Update the maximum file descriptor value. */
114 if (sock > channel_max_fd_value)
115 channel_max_fd_value = sock;
117 /* Do initial allocation if this is the first call. */
118 if (channels_alloc == 0)
121 channels = xmalloc(channels_alloc * sizeof(Channel));
122 for (i = 0; i < channels_alloc; i++)
123 channels[i].type = SSH_CHANNEL_FREE;
125 /* Kludge: arrange a call to channel_stop_listening if we terminate
127 fatal_add_cleanup((void (*)(void *))channel_stop_listening, NULL);
130 /* Try to find a free slot where to put the new channel. */
131 for (i = 0; i < channels_alloc; i++)
132 if (channels[i].type == SSH_CHANNEL_FREE)
134 /* Found a free slot. Initialize the fields and return its number. */
135 buffer_init(&channels[i].input);
136 buffer_init(&channels[i].output);
137 channels[i].self = i;
138 channels[i].type = type;
140 channels[i].sock = sock;
141 channels[i].remote_id = -1;
142 channels[i].remote_name = remote_name;
143 chan_init_iostates(&channels[i]);
147 /* There are no free slots. Must expand the array. */
148 old_channels = channels_alloc;
149 channels_alloc += 10;
150 channels = xrealloc(channels, channels_alloc * sizeof(Channel));
151 for (i = old_channels; i < channels_alloc; i++)
152 channels[i].type = SSH_CHANNEL_FREE;
154 /* We know that the next one after the old maximum channel number is now
155 available. Initialize and return its number. */
156 buffer_init(&channels[old_channels].input);
157 buffer_init(&channels[old_channels].output);
158 channels[old_channels].self = old_channels;
159 channels[old_channels].type = type;
160 channels[old_channels].x11 = 0;
161 channels[old_channels].sock = sock;
162 channels[old_channels].remote_id = -1;
163 channels[old_channels].remote_name = remote_name;
164 chan_init_iostates(&channels[old_channels]);
168 /* Free the channel and close its socket. */
170 void channel_free(int channel)
172 assert(channel >= 0 && channel < channels_alloc &&
173 channels[channel].type != SSH_CHANNEL_FREE);
175 shutdown(channels[channel].sock, SHUT_RDWR);
176 close(channels[channel].sock);
177 buffer_free(&channels[channel].input);
178 buffer_free(&channels[channel].output);
179 channels[channel].type = SSH_CHANNEL_FREE;
180 if (channels[channel].remote_name)
182 xfree(channels[channel].remote_name);
183 channels[channel].remote_name = NULL;
187 /* This is called just before select() to add any bits relevant to
188 channels in the select bitmasks. */
190 void channel_prepare_select(fd_set *readset, fd_set *writeset)
195 unsigned int proto_len, data_len;
197 for (i = 0; i < channels_alloc; i++)
203 case SSH_CHANNEL_X11_LISTENER:
204 case SSH_CHANNEL_PORT_LISTENER:
205 case SSH_CHANNEL_AUTH_SOCKET:
206 FD_SET(ch->sock, readset);
209 case SSH_CHANNEL_OPEN:
211 if (buffer_len(&ch->input) < 32768)
212 FD_SET(ch->sock, readset);
213 if (buffer_len(&ch->output) > 0)
214 FD_SET(ch->sock, writeset);
217 /* test whether sockets are 'alive' for read/write */
218 if (ch->istate == CHAN_INPUT_OPEN)
219 if (buffer_len(&ch->input) < 32768)
220 FD_SET(ch->sock, readset);
221 if (ch->ostate == CHAN_OUTPUT_OPEN || ch->ostate == CHAN_OUTPUT_WAIT_DRAIN){
222 if (buffer_len(&ch->output) > 0){
223 FD_SET(ch->sock, writeset);
224 }else if(ch->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
230 case SSH_CHANNEL_INPUT_DRAINING:
232 fatal("cannot happen: IN_DRAIN");
233 if (buffer_len(&ch->input) == 0)
235 packet_start(SSH_MSG_CHANNEL_CLOSE);
236 packet_put_int(ch->remote_id);
238 ch->type = SSH_CHANNEL_CLOSED;
239 debug("Closing channel %d after input drain.", i);
244 case SSH_CHANNEL_OUTPUT_DRAINING:
246 fatal("cannot happen: OUT_DRAIN");
247 if (buffer_len(&ch->output) == 0)
249 /* debug("Freeing channel %d after output drain.", i); */
253 FD_SET(ch->sock, writeset);
256 case SSH_CHANNEL_X11_OPEN:
257 /* This is a special state for X11 authentication spoofing. An
258 opened X11 connection (when authentication spoofing is being
259 done) remains in this state until the first packet has been
260 completely read. The authentication data in that packet is
261 then substituted by the real data if it matches the fake data,
262 and the channel is put into normal mode. */
264 /* Check if the fixed size part of the packet is in buffer. */
265 if (buffer_len(&ch->output) < 12)
268 /* Parse the lengths of variable-length fields. */
269 ucp = (unsigned char *)buffer_ptr(&ch->output);
271 { /* Byte order MSB first. */
272 proto_len = 256 * ucp[6] + ucp[7];
273 data_len = 256 * ucp[8] + ucp[9];
277 { /* Byte order LSB first. */
278 proto_len = ucp[6] + 256 * ucp[7];
279 data_len = ucp[8] + 256 * ucp[9];
283 debug("Initial X11 packet contains bad byte order byte: 0x%x",
285 ch->type = SSH_CHANNEL_OPEN;
289 /* Check if the whole packet is in buffer. */
290 if (buffer_len(&ch->output) <
291 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
294 /* Check if authentication protocol matches. */
295 if (proto_len != strlen(x11_saved_proto) ||
296 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0)
298 debug("X11 connection uses different authentication protocol.");
299 ch->type = SSH_CHANNEL_OPEN;
303 /* Check if authentication data matches our fake data. */
304 if (data_len != x11_fake_data_len ||
305 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
306 x11_fake_data, x11_fake_data_len) != 0)
308 debug("X11 auth data does not match fake data.");
309 ch->type = SSH_CHANNEL_OPEN;
313 /* Received authentication protocol and data match our fake data.
314 Substitute the fake data with real data. */
315 assert(x11_fake_data_len == x11_saved_data_len);
316 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
317 x11_saved_data, x11_saved_data_len);
319 /* Start normal processing for the channel. */
320 ch->type = SSH_CHANNEL_OPEN;
321 /* Enable X11 Problem FIX */
326 /* We have received an X11 connection that has bad authentication
328 log("X11 connection rejected because of wrong authentication.\r\n");
329 buffer_clear(&ch->input);
330 buffer_clear(&ch->output);
334 ch->type = SSH_CHANNEL_CLOSED;
335 packet_start(SSH_MSG_CHANNEL_CLOSE);
336 packet_put_int(ch->remote_id);
339 debug("X11 rejected %d 0x%x 0x%x", ch->self, ch->istate, ch->ostate);
340 chan_read_failed(ch);
341 chan_write_failed(ch);
342 debug("X11 rejected %d 0x%x 0x%x", ch->self, ch->istate, ch->ostate);
346 case SSH_CHANNEL_FREE:
353 /* After select, perform any appropriate operations for channels which
354 have events pending. */
356 void channel_after_select(fd_set *readset, fd_set *writeset)
358 struct sockaddr addr;
359 int addrlen, newsock, i, newch, len;
361 char buf[16384], *remote_hostname;
363 /* Loop over all channels... */
364 for (i = 0; i < channels_alloc; i++)
369 case SSH_CHANNEL_X11_LISTENER:
370 /* This is our fake X11 server socket. */
371 if (FD_ISSET(ch->sock, readset))
373 debug("X11 connection requested.");
374 addrlen = sizeof(addr);
375 newsock = accept(ch->sock, &addr, &addrlen);
378 error("accept: %.100s", strerror(errno));
381 remote_hostname = get_remote_hostname(newsock);
382 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
383 remote_hostname, get_peer_port(newsock));
384 xfree(remote_hostname);
385 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
387 packet_start(SSH_SMSG_X11_OPEN);
388 packet_put_int(newch);
389 if (have_hostname_in_open)
390 packet_put_string(buf, strlen(buf));
395 case SSH_CHANNEL_PORT_LISTENER:
396 /* This socket is listening for connections to a forwarded TCP/IP
398 if (FD_ISSET(ch->sock, readset))
400 debug("Connection to port %d forwarding to %.100s:%d requested.",
401 ch->listening_port, ch->path, ch->host_port);
402 addrlen = sizeof(addr);
403 newsock = accept(ch->sock, &addr, &addrlen);
406 error("accept: %.100s", strerror(errno));
409 remote_hostname = get_remote_hostname(newsock);
410 snprintf(buf, sizeof buf, "port %d, connection from %.200s port %d",
411 ch->listening_port, remote_hostname,
412 get_peer_port(newsock));
413 xfree(remote_hostname);
414 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
416 packet_start(SSH_MSG_PORT_OPEN);
417 packet_put_int(newch);
418 packet_put_string(ch->path, strlen(ch->path));
419 packet_put_int(ch->host_port);
420 if (have_hostname_in_open)
421 packet_put_string(buf, strlen(buf));
426 case SSH_CHANNEL_AUTH_SOCKET:
427 /* This is the authentication agent socket listening for connections
429 if (FD_ISSET(ch->sock, readset))
433 newsock = accept(ch->sock, &addr, &len);
436 error("accept from auth socket: %.100s", strerror(errno));
440 nchan = channel_allocate(SSH_CHANNEL_OPENING, newsock,
441 xstrdup("accepted auth socket"));
442 packet_start(SSH_SMSG_AGENT_OPEN);
443 packet_put_int(nchan);
448 case SSH_CHANNEL_OPEN:
449 /* This is an open two-way communication channel. It is not of
450 interest to us at this point what kind of data is being
453 /* Read available incoming data and append it to buffer;
454 shutdown socket, if read or write failes */
455 if (FD_ISSET(ch->sock, readset))
457 len = read(ch->sock, buf, sizeof(buf));
461 buffer_consume(&ch->output, buffer_len(&ch->output));
462 ch->type = SSH_CHANNEL_INPUT_DRAINING;
463 debug("Channel %d status set to input draining.", i);
465 chan_read_failed(ch);
469 buffer_append(&ch->input, buf, len);
471 /* Send buffered output data to the socket. */
472 if (FD_ISSET(ch->sock, writeset) && buffer_len(&ch->output) > 0)
474 len = write(ch->sock, buffer_ptr(&ch->output),
475 buffer_len(&ch->output));
479 buffer_consume(&ch->output, buffer_len(&ch->output));
480 debug("Channel %d status set to input draining.", i);
481 ch->type = SSH_CHANNEL_INPUT_DRAINING;
483 chan_write_failed(ch);
487 buffer_consume(&ch->output, len);
491 case SSH_CHANNEL_OUTPUT_DRAINING:
493 fatal("cannot happen: OUT_DRAIN");
494 /* Send buffered output data to the socket. */
495 if (FD_ISSET(ch->sock, writeset) && buffer_len(&ch->output) > 0)
497 len = write(ch->sock, buffer_ptr(&ch->output),
498 buffer_len(&ch->output));
500 buffer_consume(&ch->output, buffer_len(&ch->output));
502 buffer_consume(&ch->output, len);
506 case SSH_CHANNEL_X11_OPEN:
507 case SSH_CHANNEL_FREE:
514 /* If there is data to send to the connection, send some of it now. */
516 void channel_output_poll()
521 for (i = 0; i < channels_alloc; i++)
524 /* We are only interested in channels that can have buffered incoming
526 if (ch->type != SSH_CHANNEL_OPEN &&
527 ch->type != SSH_CHANNEL_INPUT_DRAINING)
530 /* Get the amount of buffered data for this channel. */
531 len = buffer_len(&ch->input);
534 /* Send some data for the other side over the secure connection. */
535 if (packet_is_interactive())
543 len = 16384; /* Keep the packets at reasonable size. */
545 packet_start(SSH_MSG_CHANNEL_DATA);
546 packet_put_int(ch->remote_id);
547 packet_put_string(buffer_ptr(&ch->input), len);
549 buffer_consume(&ch->input, len);
551 else if(ch->istate == CHAN_INPUT_WAIT_DRAIN)
554 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
555 /* input-buffer is empty and read-socket shutdown:
556 tell peer, that we will not send more data: send IEOF */
562 /* This is called when a packet of type CHANNEL_DATA has just been received.
563 The message type has already been consumed, but channel number and data
566 void channel_input_data(int payload_len)
570 unsigned int data_len;
572 /* Get the channel number and verify it. */
573 channel = packet_get_int();
574 if (channel < 0 || channel >= channels_alloc ||
575 channels[channel].type == SSH_CHANNEL_FREE)
576 packet_disconnect("Received data for nonexistent channel %d.", channel);
578 /* Ignore any data for non-open channels (might happen on close) */
579 if (channels[channel].type != SSH_CHANNEL_OPEN &&
580 channels[channel].type != SSH_CHANNEL_X11_OPEN)
584 data = packet_get_string(&data_len);
585 packet_integrity_check(payload_len, 4 + 4+data_len, SSH_MSG_CHANNEL_DATA);
586 buffer_append(&channels[channel].output, data, data_len);
590 /* Returns true if no channel has too much buffered data, and false if
591 one or more channel is overfull. */
593 int channel_not_very_much_buffered_data()
598 for (i = 0; i < channels_alloc; i++)
603 case SSH_CHANNEL_X11_LISTENER:
604 case SSH_CHANNEL_PORT_LISTENER:
605 case SSH_CHANNEL_AUTH_SOCKET:
607 case SSH_CHANNEL_OPEN:
608 if (buffer_len(&ch->input) > 32768)
610 if (buffer_len(&ch->output) > 32768)
613 case SSH_CHANNEL_INPUT_DRAINING:
614 case SSH_CHANNEL_OUTPUT_DRAINING:
615 case SSH_CHANNEL_X11_OPEN:
616 case SSH_CHANNEL_FREE:
624 /* This is called after receiving CHANNEL_CLOSE/IEOF. */
626 void channel_input_close()
630 /* Get the channel number and verify it. */
631 channel = packet_get_int();
632 if (channel < 0 || channel >= channels_alloc ||
633 channels[channel].type == SSH_CHANNEL_FREE)
634 packet_disconnect("Received data for nonexistent channel %d.", channel);
637 /* proto version 1.5 overloads CLOSE with IEOF */
638 chan_rcvd_ieof(&channels[channel]);
642 /* Send a confirmation that we have closed the channel and no more data is
644 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
645 packet_put_int(channels[channel].remote_id);
648 /* If the channel is in closed state, we have sent a close request, and
649 the other side will eventually respond with a confirmation. Thus,
650 we cannot free the channel here, because then there would be no-one to
651 receive the confirmation. The channel gets freed when the confirmation
653 if (channels[channel].type != SSH_CHANNEL_CLOSED)
655 /* Not a closed channel - mark it as draining, which will cause it to
657 buffer_consume(&channels[channel].input,
658 buffer_len(&channels[channel].input));
659 channels[channel].type = SSH_CHANNEL_OUTPUT_DRAINING;
660 /* debug("Setting status to output draining; output len = %d",
661 buffer_len(&channels[channel].output)); */
665 /* This is called after receiving CHANNEL_CLOSE_CONFIRMATION/OCLOSE. */
667 void channel_input_close_confirmation()
671 /* Get the channel number and verify it. */
672 channel = packet_get_int();
673 if (channel < 0 || channel >= channels_alloc)
674 packet_disconnect("Received close confirmation for out-of-range channel %d.",
678 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
679 chan_rcvd_oclose(&channels[channel]);
683 if (channels[channel].type != SSH_CHANNEL_CLOSED)
684 packet_disconnect("Received close confirmation for non-closed channel %d (type %d).",
685 channel, channels[channel].type);
687 /* Free the channel. */
688 channel_free(channel);
691 /* This is called after receiving CHANNEL_OPEN_CONFIRMATION. */
693 void channel_input_open_confirmation()
695 int channel, remote_channel;
697 /* Get the channel number and verify it. */
698 channel = packet_get_int();
699 if (channel < 0 || channel >= channels_alloc ||
700 channels[channel].type != SSH_CHANNEL_OPENING)
701 packet_disconnect("Received open confirmation for non-opening channel %d.",
704 /* Get remote side's id for this channel. */
705 remote_channel = packet_get_int();
707 /* Record the remote channel number and mark that the channel is now open. */
708 channels[channel].remote_id = remote_channel;
709 channels[channel].type = SSH_CHANNEL_OPEN;
712 /* This is called after receiving CHANNEL_OPEN_FAILURE from the other side. */
714 void channel_input_open_failure()
718 /* Get the channel number and verify it. */
719 channel = packet_get_int();
720 if (channel < 0 || channel >= channels_alloc ||
721 channels[channel].type != SSH_CHANNEL_OPENING)
722 packet_disconnect("Received open failure for non-opening channel %d.",
725 /* Free the channel. This will also close the socket. */
726 channel_free(channel);
729 /* Stops listening for channels, and removes any unix domain sockets that
732 void channel_stop_listening()
735 for (i = 0; i < channels_alloc; i++)
737 switch (channels[i].type)
739 case SSH_CHANNEL_AUTH_SOCKET:
740 close(channels[i].sock);
741 remove(channels[i].path);
744 case SSH_CHANNEL_PORT_LISTENER:
745 case SSH_CHANNEL_X11_LISTENER:
746 close(channels[i].sock);
755 /* Closes the sockets of all channels. This is used to close extra file
756 descriptors after a fork. */
758 void channel_close_all()
761 for (i = 0; i < channels_alloc; i++)
763 if (channels[i].type != SSH_CHANNEL_FREE)
764 close(channels[i].sock);
768 /* Returns the maximum file descriptor number used by the channels. */
772 return channel_max_fd_value;
775 /* Returns true if any channel is still open. */
777 int channel_still_open()
780 for (i = 0; i < channels_alloc; i++)
781 switch (channels[i].type)
783 case SSH_CHANNEL_FREE:
784 case SSH_CHANNEL_X11_LISTENER:
785 case SSH_CHANNEL_PORT_LISTENER:
786 case SSH_CHANNEL_CLOSED:
787 case SSH_CHANNEL_AUTH_SOCKET:
789 case SSH_CHANNEL_OPENING:
790 case SSH_CHANNEL_OPEN:
791 case SSH_CHANNEL_X11_OPEN:
793 case SSH_CHANNEL_INPUT_DRAINING:
794 case SSH_CHANNEL_OUTPUT_DRAINING:
796 fatal("cannot happen: OUT_DRAIN");
799 fatal("channel_still_open: bad channel type %d", channels[i].type);
805 /* Returns a message describing the currently open forwarded
806 connections, suitable for sending to the client. The message
807 contains crlf pairs for newlines. */
809 char *channel_open_message()
815 buffer_init(&buffer);
816 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
817 buffer_append(&buffer, buf, strlen(buf));
818 for (i = 0; i < channels_alloc; i++){
819 Channel *c=&channels[i];
822 case SSH_CHANNEL_FREE:
823 case SSH_CHANNEL_X11_LISTENER:
824 case SSH_CHANNEL_PORT_LISTENER:
825 case SSH_CHANNEL_CLOSED:
826 case SSH_CHANNEL_AUTH_SOCKET:
828 case SSH_CHANNEL_OPENING:
829 case SSH_CHANNEL_OPEN:
830 case SSH_CHANNEL_X11_OPEN:
831 case SSH_CHANNEL_INPUT_DRAINING:
832 case SSH_CHANNEL_OUTPUT_DRAINING:
833 snprintf(buf, sizeof buf, " #%d/%d %.300s\r\n",
834 c->self,c->type,c->remote_name);
835 buffer_append(&buffer, buf, strlen(buf));
838 fatal("channel_still_open: bad channel type %d", c->type);
842 buffer_append(&buffer, "\0", 1);
843 cp = xstrdup(buffer_ptr(&buffer));
844 buffer_free(&buffer);
848 /* Initiate forwarding of connections to local port "port" through the secure
849 channel to host:port from remote side. */
851 void channel_request_local_forwarding(int port, const char *host,
855 struct sockaddr_in sin;
856 extern Options options;
858 if (strlen(host) > sizeof(channels[0].path) - 1)
859 packet_disconnect("Forward host name too long.");
861 /* Create a port to listen for the host. */
862 sock = socket(AF_INET, SOCK_STREAM, 0);
864 packet_disconnect("socket: %.100s", strerror(errno));
866 /* Initialize socket address. */
867 memset(&sin, 0, sizeof(sin));
868 sin.sin_family = AF_INET;
869 if (options.gateway_ports == 1)
870 sin.sin_addr.s_addr = htonl(INADDR_ANY);
872 sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
873 sin.sin_port = htons(port);
875 /* Bind the socket to the address. */
876 if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
877 packet_disconnect("bind: %.100s", strerror(errno));
879 /* Start listening for connections on the socket. */
880 if (listen(sock, 5) < 0)
881 packet_disconnect("listen: %.100s", strerror(errno));
883 /* Allocate a channel number for the socket. */
884 ch = channel_allocate(SSH_CHANNEL_PORT_LISTENER, sock,
885 xstrdup("port listener"));
886 strcpy(channels[ch].path, host); /* note: host name stored here */
887 channels[ch].host_port = host_port; /* port on host to connect to */
888 channels[ch].listening_port = port; /* port being listened */
891 /* Initiate forwarding of connections to port "port" on remote host through
892 the secure channel to host:port from local side. */
894 void channel_request_remote_forwarding(int port, const char *host,
898 /* Record locally that connection to this host/port is permitted. */
899 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
900 fatal("channel_request_remote_forwarding: too many forwards");
901 permitted_opens[num_permitted_opens].host = xstrdup(host);
902 permitted_opens[num_permitted_opens].port = remote_port;
903 num_permitted_opens++;
905 /* Send the forward request to the remote side. */
906 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
907 packet_put_int(port);
908 packet_put_string(host, strlen(host));
909 packet_put_int(remote_port);
913 /* Wait for response from the remote side. It will send a disconnect
914 message on failure, and we will never see it here. */
915 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
918 /* This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
919 listening for the port, and sends back a success reply (or disconnect
920 message if there was an error). This never returns if there was an
923 void channel_input_port_forward_request(int is_root)
928 /* Get arguments from the packet. */
929 port = packet_get_int();
930 hostname = packet_get_string(NULL);
931 host_port = packet_get_int();
933 /* Port numbers are 16 bit quantities. */
934 if ((port & 0xffff) != port)
935 packet_disconnect("Requested forwarding of nonexistent port %d.", port);
937 /* Check that an unprivileged user is not trying to forward a privileged
939 if (port < IPPORT_RESERVED && !is_root)
940 packet_disconnect("Requested forwarding of port %d but user is not root.",
943 /* Initiate forwarding. */
944 channel_request_local_forwarding(port, hostname, host_port);
946 /* Free the argument string. */
950 /* This is called after receiving PORT_OPEN message. This attempts to connect
951 to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION or
952 CHANNEL_OPEN_FAILURE. */
954 void channel_input_port_open(int payload_len)
956 int remote_channel, sock, newch, host_port, i;
957 struct sockaddr_in sin;
958 char *host, *originator_string;
960 int host_len, originator_len;
962 /* Get remote channel number. */
963 remote_channel = packet_get_int();
965 /* Get host name to connect to. */
966 host = packet_get_string(&host_len);
968 /* Get port to connect to. */
969 host_port = packet_get_int();
971 /* Get remote originator name. */
972 if (have_hostname_in_open)
973 originator_string = packet_get_string(&originator_len);
975 originator_string = xstrdup("unknown (remote did not supply name)");
977 packet_integrity_check(payload_len,
978 4 + 4 + host_len + 4 + 4 + originator_len,
981 /* Check if opening that port is permitted. */
982 if (!all_opens_permitted)
984 /* Go trough all permitted ports. */
985 for (i = 0; i < num_permitted_opens; i++)
986 if (permitted_opens[i].port == host_port &&
987 strcmp(permitted_opens[i].host, host) == 0)
990 /* Check if we found the requested port among those permitted. */
991 if (i >= num_permitted_opens)
993 /* The port is not permitted. */
994 log("Received request to connect to %.100s:%d, but the request was denied.",
996 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
997 packet_put_int(remote_channel);
1002 memset(&sin, 0, sizeof(sin));
1003 sin.sin_addr.s_addr = inet_addr(host);
1004 if ((sin.sin_addr.s_addr & 0xffffffff) != 0xffffffff)
1006 /* It was a valid numeric host address. */
1007 sin.sin_family = AF_INET;
1011 /* Look up the host address from the name servers. */
1012 hp = gethostbyname(host);
1015 error("%.100s: unknown host.", host);
1018 if (!hp->h_addr_list[0])
1020 error("%.100s: host has no IP address.", host);
1023 sin.sin_family = hp->h_addrtype;
1024 memcpy(&sin.sin_addr, hp->h_addr_list[0],
1025 sizeof(sin.sin_addr));
1027 sin.sin_port = htons(host_port);
1029 /* Create the socket. */
1030 sock = socket(sin.sin_family, SOCK_STREAM, 0);
1033 error("socket: %.100s", strerror(errno));
1037 /* Connect to the host/port. */
1038 if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1040 error("connect %.100s:%d: %.100s", host, host_port,
1046 /* Successful connection. */
1048 /* Allocate a channel for this connection. */
1049 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, originator_string);
1050 channels[newch].remote_id = remote_channel;
1052 /* Send a confirmation to the remote host. */
1053 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1054 packet_put_int(remote_channel);
1055 packet_put_int(newch);
1058 /* Free the argument string. */
1064 /* Free the argument string. */
1067 /* Send refusal to the remote host. */
1068 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1069 packet_put_int(remote_channel);
1073 /* Creates an internet domain socket for listening for X11 connections.
1074 Returns a suitable value for the DISPLAY variable, or NULL if an error
1077 char *x11_create_display_inet(int screen_number)
1079 extern ServerOptions options;
1080 int display_number, port, sock;
1081 struct sockaddr_in sin;
1083 char hostname[MAXHOSTNAMELEN];
1085 for (display_number = options.x11_display_offset; display_number < MAX_DISPLAYS; display_number++)
1087 port = 6000 + display_number;
1088 memset(&sin, 0, sizeof(sin));
1089 sin.sin_family = AF_INET;
1090 sin.sin_addr.s_addr = htonl(INADDR_ANY);
1091 sin.sin_port = htons(port);
1093 sock = socket(AF_INET, SOCK_STREAM, 0);
1096 error("socket: %.100s", strerror(errno));
1100 if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1102 debug("bind port %d: %.100s", port, strerror(errno));
1103 shutdown(sock, SHUT_RDWR);
1109 if (display_number >= MAX_DISPLAYS)
1111 error("Failed to allocate internet-domain X11 display socket.");
1115 /* Start listening for connections on the socket. */
1116 if (listen(sock, 5) < 0)
1118 error("listen: %.100s", strerror(errno));
1119 shutdown(sock, SHUT_RDWR);
1124 /* Set up a suitable value for the DISPLAY variable. */
1125 if (gethostname(hostname, sizeof(hostname)) < 0)
1126 fatal("gethostname: %.100s", strerror(errno));
1127 snprintf(buf, sizeof buf, "%.400s:%d.%d", hostname,
1128 display_number, screen_number);
1130 /* Allocate a channel for the socket. */
1131 (void)channel_allocate(SSH_CHANNEL_X11_LISTENER, sock,
1132 xstrdup("X11 inet listener"));
1134 /* Return a suitable value for the DISPLAY environment variable. */
1135 return xstrdup(buf);
1139 #define X_UNIX_PATH "/tmp/.X11-unix/X"
1144 connect_local_xsocket(unsigned dnr)
1146 static const char *const x_sockets[] = {
1148 "/var/X/.X11-unix/X" "%u",
1149 "/usr/spool/sockets/X11/" "%u",
1153 struct sockaddr_un addr;
1154 const char *const *path;
1156 for (path = x_sockets; *path; ++path)
1158 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1160 error("socket: %.100s", strerror(errno));
1161 memset(&addr, 0, sizeof(addr));
1162 addr.sun_family = AF_UNIX;
1163 snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
1164 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
1168 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
1173 /* This is called when SSH_SMSG_X11_OPEN is received. The packet contains
1174 the remote channel number. We should do whatever we want, and respond
1175 with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE. */
1177 void x11_input_open(int payload_len)
1179 int remote_channel, display_number, sock, newch;
1180 const char *display;
1181 struct sockaddr_in sin;
1182 char buf[1024], *cp, *remote_host;
1186 /* Get remote channel number. */
1187 remote_channel = packet_get_int();
1189 /* Get remote originator name. */
1190 if (have_hostname_in_open)
1191 remote_host = packet_get_string(&remote_len);
1193 remote_host = xstrdup("unknown (remote did not supply name)");
1195 debug("Received X11 open request.");
1196 packet_integrity_check(payload_len, 4 + 4+remote_len, SSH_SMSG_X11_OPEN);
1198 /* Try to open a socket for the local X server. */
1199 display = getenv("DISPLAY");
1202 error("DISPLAY not set.");
1206 /* Now we decode the value of the DISPLAY variable and make a connection
1207 to the real X server. */
1209 /* Check if it is a unix domain socket. Unix domain displays are in one
1210 of the following formats: unix:d[.s], :d[.s], ::d[.s] */
1211 if (strncmp(display, "unix:", 5) == 0 ||
1214 /* Connect to the unix domain socket. */
1215 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1)
1217 error("Could not parse display number from DISPLAY: %.100s",
1221 /* Create a socket. */
1222 sock = connect_local_xsocket(display_number);
1226 /* OK, we now have a connection to the display. */
1230 /* Connect to an inet socket. The DISPLAY value is supposedly
1231 hostname:d[.s], where hostname may also be numeric IP address. */
1232 strncpy(buf, display, sizeof(buf));
1233 buf[sizeof(buf) - 1] = 0;
1234 cp = strchr(buf, ':');
1237 error("Could not find ':' in DISPLAY: %.100s", display);
1241 /* buf now contains the host name. But first we parse the display number. */
1242 if (sscanf(cp + 1, "%d", &display_number) != 1)
1244 error("Could not parse display number from DISPLAY: %.100s",
1249 /* Try to parse the host name as a numeric IP address. */
1250 memset(&sin, 0, sizeof(sin));
1251 sin.sin_addr.s_addr = inet_addr(buf);
1252 if ((sin.sin_addr.s_addr & 0xffffffff) != 0xffffffff)
1254 /* It was a valid numeric host address. */
1255 sin.sin_family = AF_INET;
1259 /* Not a numeric IP address. */
1260 /* Look up the host address from the name servers. */
1261 hp = gethostbyname(buf);
1264 error("%.100s: unknown host.", buf);
1267 if (!hp->h_addr_list[0])
1269 error("%.100s: host has no IP address.", buf);
1272 sin.sin_family = hp->h_addrtype;
1273 memcpy(&sin.sin_addr, hp->h_addr_list[0],
1274 sizeof(sin.sin_addr));
1276 /* Set port number. */
1277 sin.sin_port = htons(6000 + display_number);
1279 /* Create a socket. */
1280 sock = socket(sin.sin_family, SOCK_STREAM, 0);
1283 error("socket: %.100s", strerror(errno));
1286 /* Connect it to the display. */
1287 if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1289 error("connect %.100s:%d: %.100s", buf, 6000 + display_number,
1296 /* We have successfully obtained a connection to the real X display. */
1298 /* Allocate a channel for this connection. */
1299 if (x11_saved_proto == NULL)
1300 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, remote_host);
1302 newch = channel_allocate(SSH_CHANNEL_X11_OPEN, sock, remote_host);
1303 channels[newch].remote_id = remote_channel;
1305 /* Send a confirmation to the remote host. */
1306 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1307 packet_put_int(remote_channel);
1308 packet_put_int(newch);
1314 /* Send refusal to the remote host. */
1315 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1316 packet_put_int(remote_channel);
1320 /* Requests forwarding of X11 connections, generates fake authentication
1321 data, and enables authentication spoofing. */
1323 void x11_request_forwarding_with_spoofing(const char *proto, const char *data)
1325 unsigned int data_len = (unsigned int)strlen(data) / 2;
1326 unsigned int i, value;
1332 cp = getenv("DISPLAY");
1334 cp = strchr(cp, ':');
1336 cp = strchr(cp, '.');
1338 screen_number = atoi(cp + 1);
1342 /* Save protocol name. */
1343 x11_saved_proto = xstrdup(proto);
1345 /* Extract real authentication data and generate fake data of the same
1347 x11_saved_data = xmalloc(data_len);
1348 x11_fake_data = xmalloc(data_len);
1349 for (i = 0; i < data_len; i++)
1351 if (sscanf(data + 2 * i, "%2x", &value) != 1)
1352 fatal("x11_request_forwarding: bad authentication data: %.100s", data);
1354 rand = arc4random();
1355 x11_saved_data[i] = value;
1356 x11_fake_data[i] = rand & 0xff;
1359 x11_saved_data_len = data_len;
1360 x11_fake_data_len = data_len;
1362 /* Convert the fake data into hex. */
1363 new_data = xmalloc(2 * data_len + 1);
1364 for (i = 0; i < data_len; i++)
1365 sprintf(new_data + 2 * i, "%02x", (unsigned char)x11_fake_data[i]);
1367 /* Send the request packet. */
1368 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
1369 packet_put_string(proto, strlen(proto));
1370 packet_put_string(new_data, strlen(new_data));
1371 packet_put_int(screen_number);
1373 packet_write_wait();
1377 /* Sends a message to the server to request authentication fd forwarding. */
1379 void auth_request_forwarding()
1381 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
1383 packet_write_wait();
1386 /* Returns the name of the forwarded authentication socket. Returns NULL
1387 if there is no forwarded authentication socket. The returned value
1388 points to a static buffer. */
1390 char *auth_get_socket_name()
1392 return channel_forwarded_auth_socket_name;
1395 /* removes the agent forwarding socket */
1397 void cleanup_socket(void) {
1398 remove(channel_forwarded_auth_socket_name);
1399 rmdir(channel_forwarded_auth_socket_dir);
1402 /* This if called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
1403 This starts forwarding authentication requests. */
1405 void auth_input_request_forwarding(struct passwd *pw)
1408 struct sockaddr_un sunaddr;
1410 if (auth_get_socket_name() != NULL)
1411 fatal("Protocol error: authentication forwarding requested twice.");
1413 /* Temporarily drop privileged uid for mkdir/bind. */
1414 temporarily_use_uid(pw->pw_uid);
1416 /* Allocate a buffer for the socket name, and format the name. */
1417 channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
1418 channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
1419 strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
1421 /* Create private directory for socket */
1422 if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL)
1423 packet_disconnect("mkdtemp: %.100s", strerror(errno));
1424 snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME,
1425 "%s/agent.%d", channel_forwarded_auth_socket_dir, (int)getpid());
1427 if (atexit(cleanup_socket) < 0) {
1430 packet_disconnect("socket: %.100s", strerror(saved));
1433 /* Create the socket. */
1434 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1436 packet_disconnect("socket: %.100s", strerror(errno));
1438 /* Bind it to the name. */
1439 memset(&sunaddr, 0, sizeof(sunaddr));
1440 sunaddr.sun_family = AF_UNIX;
1441 strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
1442 sizeof(sunaddr.sun_path));
1444 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0)
1445 packet_disconnect("bind: %.100s", strerror(errno));
1447 /* Restore the privileged uid. */
1450 /* Start listening on the socket. */
1451 if (listen(sock, 5) < 0)
1452 packet_disconnect("listen: %.100s", strerror(errno));
1454 /* Allocate a channel for the authentication agent socket. */
1455 newch = channel_allocate(SSH_CHANNEL_AUTH_SOCKET, sock,
1456 xstrdup("auth socket"));
1457 strcpy(channels[newch].path, channel_forwarded_auth_socket_name);
1460 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
1462 void auth_input_open_request()
1464 int remch, sock, newch;
1467 /* Read the remote channel number from the message. */
1468 remch = packet_get_int();
1470 /* Get a connection to the local authentication agent (this may again get
1472 sock = ssh_get_authentication_socket();
1474 /* If we could not connect the agent, send an error message back to
1475 the server. This should never happen unless the agent
1476 dies, because authentication forwarding is only enabled if we have an
1479 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1480 packet_put_int(remch);
1485 debug("Forwarding authentication connection.");
1487 /* Dummy host name. This will be freed when the channel is freed; it will
1488 still be valid in the packet_put_string below since the channel cannot
1489 yet be freed at that point. */
1490 dummyname = xstrdup("authentication agent connection");
1492 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
1493 channels[newch].remote_id = remch;
1495 /* Send a confirmation to the remote host. */
1496 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1497 packet_put_int(remch);
1498 packet_put_int(newch);