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 if (channel < 0 || channel >= channels_alloc ||
170 channels[channel].type == SSH_CHANNEL_FREE)
171 packet_disconnect("channel free: bad local channel %d", channel);
174 shutdown(channels[channel].sock, SHUT_RDWR);
175 close(channels[channel].sock);
176 buffer_free(&channels[channel].input);
177 buffer_free(&channels[channel].output);
178 channels[channel].type = SSH_CHANNEL_FREE;
179 if (channels[channel].remote_name)
181 xfree(channels[channel].remote_name);
182 channels[channel].remote_name = NULL;
186 /* This is called just before select() to add any bits relevant to
187 channels in the select bitmasks. */
189 void channel_prepare_select(fd_set *readset, fd_set *writeset)
194 unsigned int proto_len, data_len;
196 for (i = 0; i < channels_alloc; i++)
202 case SSH_CHANNEL_X11_LISTENER:
203 case SSH_CHANNEL_PORT_LISTENER:
204 case SSH_CHANNEL_AUTH_SOCKET:
205 FD_SET(ch->sock, readset);
208 case SSH_CHANNEL_OPEN:
210 if (buffer_len(&ch->input) < 32768)
211 FD_SET(ch->sock, readset);
212 if (buffer_len(&ch->output) > 0)
213 FD_SET(ch->sock, writeset);
216 /* test whether sockets are 'alive' for read/write */
217 if (ch->istate == CHAN_INPUT_OPEN)
218 if (buffer_len(&ch->input) < 32768)
219 FD_SET(ch->sock, readset);
220 if (ch->ostate == CHAN_OUTPUT_OPEN || ch->ostate == CHAN_OUTPUT_WAIT_DRAIN){
221 if (buffer_len(&ch->output) > 0){
222 FD_SET(ch->sock, writeset);
223 }else if(ch->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
229 case SSH_CHANNEL_INPUT_DRAINING:
231 fatal("cannot happen: IN_DRAIN");
232 if (buffer_len(&ch->input) == 0)
234 packet_start(SSH_MSG_CHANNEL_CLOSE);
235 packet_put_int(ch->remote_id);
237 ch->type = SSH_CHANNEL_CLOSED;
238 debug("Closing channel %d after input drain.", i);
243 case SSH_CHANNEL_OUTPUT_DRAINING:
245 fatal("cannot happen: OUT_DRAIN");
246 if (buffer_len(&ch->output) == 0)
248 /* debug("Freeing channel %d after output drain.", i); */
252 FD_SET(ch->sock, writeset);
255 case SSH_CHANNEL_X11_OPEN:
256 /* This is a special state for X11 authentication spoofing. An
257 opened X11 connection (when authentication spoofing is being
258 done) remains in this state until the first packet has been
259 completely read. The authentication data in that packet is
260 then substituted by the real data if it matches the fake data,
261 and the channel is put into normal mode. */
263 /* Check if the fixed size part of the packet is in buffer. */
264 if (buffer_len(&ch->output) < 12)
267 /* Parse the lengths of variable-length fields. */
268 ucp = (unsigned char *)buffer_ptr(&ch->output);
270 { /* Byte order MSB first. */
271 proto_len = 256 * ucp[6] + ucp[7];
272 data_len = 256 * ucp[8] + ucp[9];
276 { /* Byte order LSB first. */
277 proto_len = ucp[6] + 256 * ucp[7];
278 data_len = ucp[8] + 256 * ucp[9];
282 debug("Initial X11 packet contains bad byte order byte: 0x%x",
284 ch->type = SSH_CHANNEL_OPEN;
288 /* Check if the whole packet is in buffer. */
289 if (buffer_len(&ch->output) <
290 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
293 /* Check if authentication protocol matches. */
294 if (proto_len != strlen(x11_saved_proto) ||
295 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0)
297 debug("X11 connection uses different authentication protocol.");
298 ch->type = SSH_CHANNEL_OPEN;
302 /* Check if authentication data matches our fake data. */
303 if (data_len != x11_fake_data_len ||
304 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
305 x11_fake_data, x11_fake_data_len) != 0)
307 debug("X11 auth data does not match fake data.");
308 ch->type = SSH_CHANNEL_OPEN;
312 /* Check fake data length */
313 if (x11_fake_data_len != x11_saved_data_len)
315 error("X11 fake_data_len %d != saved_data_len %d",
316 x11_fake_data_len, x11_saved_data_len);
317 ch->type = SSH_CHANNEL_OPEN;
321 /* Received authentication protocol and data match our fake data.
322 Substitute the fake data with real data. */
323 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
324 x11_saved_data, x11_saved_data_len);
326 /* Start normal processing for the channel. */
327 ch->type = SSH_CHANNEL_OPEN;
331 /* We have received an X11 connection that has bad authentication
333 log("X11 connection rejected because of wrong authentication.\r\n");
334 buffer_clear(&ch->input);
335 buffer_clear(&ch->output);
339 ch->type = SSH_CHANNEL_CLOSED;
340 packet_start(SSH_MSG_CHANNEL_CLOSE);
341 packet_put_int(ch->remote_id);
344 debug("X11 rejected %d i%d/o%d", ch->self, ch->istate, ch->ostate);
345 chan_read_failed(ch);
346 chan_write_failed(ch);
347 debug("X11 rejected %d i%d/o%d", ch->self, ch->istate, ch->ostate);
351 case SSH_CHANNEL_FREE:
358 /* After select, perform any appropriate operations for channels which
359 have events pending. */
361 void channel_after_select(fd_set *readset, fd_set *writeset)
363 struct sockaddr addr;
364 int addrlen, newsock, i, newch, len;
366 char buf[16384], *remote_hostname;
368 /* Loop over all channels... */
369 for (i = 0; i < channels_alloc; i++)
374 case SSH_CHANNEL_X11_LISTENER:
375 /* This is our fake X11 server socket. */
376 if (FD_ISSET(ch->sock, readset))
378 debug("X11 connection requested.");
379 addrlen = sizeof(addr);
380 newsock = accept(ch->sock, &addr, &addrlen);
383 error("accept: %.100s", strerror(errno));
386 remote_hostname = get_remote_hostname(newsock);
387 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
388 remote_hostname, get_peer_port(newsock));
389 xfree(remote_hostname);
390 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
392 packet_start(SSH_SMSG_X11_OPEN);
393 packet_put_int(newch);
394 if (have_hostname_in_open)
395 packet_put_string(buf, strlen(buf));
400 case SSH_CHANNEL_PORT_LISTENER:
401 /* This socket is listening for connections to a forwarded TCP/IP
403 if (FD_ISSET(ch->sock, readset))
405 debug("Connection to port %d forwarding to %.100s:%d requested.",
406 ch->listening_port, ch->path, ch->host_port);
407 addrlen = sizeof(addr);
408 newsock = accept(ch->sock, &addr, &addrlen);
411 error("accept: %.100s", strerror(errno));
414 remote_hostname = get_remote_hostname(newsock);
415 snprintf(buf, sizeof buf, "listen port %d:%.100s:%d, connect from %.200s:%d",
416 ch->listening_port, ch->path, ch->host_port,
417 remote_hostname, get_peer_port(newsock));
418 xfree(remote_hostname);
419 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
421 packet_start(SSH_MSG_PORT_OPEN);
422 packet_put_int(newch);
423 packet_put_string(ch->path, strlen(ch->path));
424 packet_put_int(ch->host_port);
425 if (have_hostname_in_open)
426 packet_put_string(buf, strlen(buf));
431 case SSH_CHANNEL_AUTH_SOCKET:
432 /* This is the authentication agent socket listening for connections
434 if (FD_ISSET(ch->sock, readset))
438 newsock = accept(ch->sock, &addr, &len);
441 error("accept from auth socket: %.100s", strerror(errno));
445 nchan = channel_allocate(SSH_CHANNEL_OPENING, newsock,
446 xstrdup("accepted auth socket"));
447 packet_start(SSH_SMSG_AGENT_OPEN);
448 packet_put_int(nchan);
453 case SSH_CHANNEL_OPEN:
454 /* This is an open two-way communication channel. It is not of
455 interest to us at this point what kind of data is being
458 /* Read available incoming data and append it to buffer;
459 shutdown socket, if read or write failes */
460 if (FD_ISSET(ch->sock, readset))
462 len = read(ch->sock, buf, sizeof(buf));
466 buffer_consume(&ch->output, buffer_len(&ch->output));
467 ch->type = SSH_CHANNEL_INPUT_DRAINING;
468 debug("Channel %d status set to input draining.", i);
470 chan_read_failed(ch);
474 buffer_append(&ch->input, buf, len);
476 /* Send buffered output data to the socket. */
477 if (FD_ISSET(ch->sock, writeset) && buffer_len(&ch->output) > 0)
479 len = write(ch->sock, buffer_ptr(&ch->output),
480 buffer_len(&ch->output));
484 buffer_consume(&ch->output, buffer_len(&ch->output));
485 debug("Channel %d status set to input draining.", i);
486 ch->type = SSH_CHANNEL_INPUT_DRAINING;
488 chan_write_failed(ch);
492 buffer_consume(&ch->output, len);
496 case SSH_CHANNEL_OUTPUT_DRAINING:
498 fatal("cannot happen: OUT_DRAIN");
499 /* Send buffered output data to the socket. */
500 if (FD_ISSET(ch->sock, writeset) && buffer_len(&ch->output) > 0)
502 len = write(ch->sock, buffer_ptr(&ch->output),
503 buffer_len(&ch->output));
505 buffer_consume(&ch->output, buffer_len(&ch->output));
507 buffer_consume(&ch->output, len);
511 case SSH_CHANNEL_X11_OPEN:
512 case SSH_CHANNEL_FREE:
519 /* If there is data to send to the connection, send some of it now. */
521 void channel_output_poll()
526 for (i = 0; i < channels_alloc; i++)
529 /* We are only interested in channels that can have buffered incoming
531 if (ch->type != SSH_CHANNEL_OPEN &&
532 ch->type != SSH_CHANNEL_INPUT_DRAINING)
535 /* Get the amount of buffered data for this channel. */
536 len = buffer_len(&ch->input);
539 /* Send some data for the other side over the secure connection. */
540 if (packet_is_interactive())
548 len = 16384; /* Keep the packets at reasonable size. */
550 packet_start(SSH_MSG_CHANNEL_DATA);
551 packet_put_int(ch->remote_id);
552 packet_put_string(buffer_ptr(&ch->input), len);
554 buffer_consume(&ch->input, len);
556 else if(ch->istate == CHAN_INPUT_WAIT_DRAIN)
559 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
560 /* input-buffer is empty and read-socket shutdown:
561 tell peer, that we will not send more data: send IEOF */
567 /* This is called when a packet of type CHANNEL_DATA has just been received.
568 The message type has already been consumed, but channel number and data
571 void channel_input_data(int payload_len)
575 unsigned int data_len;
577 /* Get the channel number and verify it. */
578 channel = packet_get_int();
579 if (channel < 0 || channel >= channels_alloc ||
580 channels[channel].type == SSH_CHANNEL_FREE)
581 packet_disconnect("Received data for nonexistent channel %d.", channel);
583 /* Ignore any data for non-open channels (might happen on close) */
584 if (channels[channel].type != SSH_CHANNEL_OPEN &&
585 channels[channel].type != SSH_CHANNEL_X11_OPEN)
589 data = packet_get_string(&data_len);
590 packet_integrity_check(payload_len, 4 + 4+data_len, SSH_MSG_CHANNEL_DATA);
591 buffer_append(&channels[channel].output, data, data_len);
595 /* Returns true if no channel has too much buffered data, and false if
596 one or more channel is overfull. */
598 int channel_not_very_much_buffered_data()
603 for (i = 0; i < channels_alloc; i++)
608 case SSH_CHANNEL_X11_LISTENER:
609 case SSH_CHANNEL_PORT_LISTENER:
610 case SSH_CHANNEL_AUTH_SOCKET:
612 case SSH_CHANNEL_OPEN:
613 if (buffer_len(&ch->input) > 32768)
615 if (buffer_len(&ch->output) > 32768)
618 case SSH_CHANNEL_INPUT_DRAINING:
619 case SSH_CHANNEL_OUTPUT_DRAINING:
620 case SSH_CHANNEL_X11_OPEN:
621 case SSH_CHANNEL_FREE:
629 /* This is called after receiving CHANNEL_CLOSE/IEOF. */
631 void channel_input_close()
635 /* Get the channel number and verify it. */
636 channel = packet_get_int();
637 if (channel < 0 || channel >= channels_alloc ||
638 channels[channel].type == SSH_CHANNEL_FREE)
639 packet_disconnect("Received data for nonexistent channel %d.", channel);
642 /* proto version 1.5 overloads CLOSE with IEOF */
643 chan_rcvd_ieof(&channels[channel]);
647 /* Send a confirmation that we have closed the channel and no more data is
649 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
650 packet_put_int(channels[channel].remote_id);
653 /* If the channel is in closed state, we have sent a close request, and
654 the other side will eventually respond with a confirmation. Thus,
655 we cannot free the channel here, because then there would be no-one to
656 receive the confirmation. The channel gets freed when the confirmation
658 if (channels[channel].type != SSH_CHANNEL_CLOSED)
660 /* Not a closed channel - mark it as draining, which will cause it to
662 buffer_consume(&channels[channel].input,
663 buffer_len(&channels[channel].input));
664 channels[channel].type = SSH_CHANNEL_OUTPUT_DRAINING;
665 /* debug("Setting status to output draining; output len = %d",
666 buffer_len(&channels[channel].output)); */
670 /* This is called after receiving CHANNEL_CLOSE_CONFIRMATION/OCLOSE. */
672 void channel_input_close_confirmation()
676 /* Get the channel number and verify it. */
677 channel = packet_get_int();
678 if (channel < 0 || channel >= channels_alloc)
679 packet_disconnect("Received close confirmation for out-of-range channel %d.",
683 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
684 chan_rcvd_oclose(&channels[channel]);
688 if (channels[channel].type != SSH_CHANNEL_CLOSED)
689 packet_disconnect("Received close confirmation for non-closed channel %d (type %d).",
690 channel, channels[channel].type);
692 /* Free the channel. */
693 channel_free(channel);
696 /* This is called after receiving CHANNEL_OPEN_CONFIRMATION. */
698 void channel_input_open_confirmation()
700 int channel, remote_channel;
702 /* Get the channel number and verify it. */
703 channel = packet_get_int();
704 if (channel < 0 || channel >= channels_alloc ||
705 channels[channel].type != SSH_CHANNEL_OPENING)
706 packet_disconnect("Received open confirmation for non-opening channel %d.",
709 /* Get remote side's id for this channel. */
710 remote_channel = packet_get_int();
712 /* Record the remote channel number and mark that the channel is now open. */
713 channels[channel].remote_id = remote_channel;
714 channels[channel].type = SSH_CHANNEL_OPEN;
717 /* This is called after receiving CHANNEL_OPEN_FAILURE from the other side. */
719 void channel_input_open_failure()
723 /* Get the channel number and verify it. */
724 channel = packet_get_int();
725 if (channel < 0 || channel >= channels_alloc ||
726 channels[channel].type != SSH_CHANNEL_OPENING)
727 packet_disconnect("Received open failure for non-opening channel %d.",
730 /* Free the channel. This will also close the socket. */
731 channel_free(channel);
734 /* Stops listening for channels, and removes any unix domain sockets that
737 void channel_stop_listening()
740 for (i = 0; i < channels_alloc; i++)
742 switch (channels[i].type)
744 case SSH_CHANNEL_AUTH_SOCKET:
745 close(channels[i].sock);
746 remove(channels[i].path);
749 case SSH_CHANNEL_PORT_LISTENER:
750 case SSH_CHANNEL_X11_LISTENER:
751 close(channels[i].sock);
760 /* Closes the sockets of all channels. This is used to close extra file
761 descriptors after a fork. */
763 void channel_close_all()
766 for (i = 0; i < channels_alloc; i++)
768 if (channels[i].type != SSH_CHANNEL_FREE)
769 close(channels[i].sock);
773 /* Returns the maximum file descriptor number used by the channels. */
777 return channel_max_fd_value;
780 /* Returns true if any channel is still open. */
782 int channel_still_open()
785 for (i = 0; i < channels_alloc; i++)
786 switch (channels[i].type)
788 case SSH_CHANNEL_FREE:
789 case SSH_CHANNEL_X11_LISTENER:
790 case SSH_CHANNEL_PORT_LISTENER:
791 case SSH_CHANNEL_CLOSED:
792 case SSH_CHANNEL_AUTH_SOCKET:
794 case SSH_CHANNEL_OPENING:
795 case SSH_CHANNEL_OPEN:
796 case SSH_CHANNEL_X11_OPEN:
798 case SSH_CHANNEL_INPUT_DRAINING:
799 case SSH_CHANNEL_OUTPUT_DRAINING:
801 fatal("cannot happen: OUT_DRAIN");
804 fatal("channel_still_open: bad channel type %d", channels[i].type);
810 /* Returns a message describing the currently open forwarded
811 connections, suitable for sending to the client. The message
812 contains crlf pairs for newlines. */
814 char *channel_open_message()
820 buffer_init(&buffer);
821 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
822 buffer_append(&buffer, buf, strlen(buf));
823 for (i = 0; i < channels_alloc; i++){
824 Channel *c=&channels[i];
827 case SSH_CHANNEL_FREE:
828 case SSH_CHANNEL_X11_LISTENER:
829 case SSH_CHANNEL_PORT_LISTENER:
830 case SSH_CHANNEL_CLOSED:
831 case SSH_CHANNEL_AUTH_SOCKET:
833 case SSH_CHANNEL_OPENING:
834 case SSH_CHANNEL_OPEN:
835 case SSH_CHANNEL_X11_OPEN:
836 case SSH_CHANNEL_INPUT_DRAINING:
837 case SSH_CHANNEL_OUTPUT_DRAINING:
838 snprintf(buf, sizeof buf, " #%d %.300s (t%d r%d i%d o%d)\r\n",
839 c->self,c->remote_name,
840 c->type,c->remote_id, c->istate,c->ostate);
841 buffer_append(&buffer, buf, strlen(buf));
844 fatal("channel_still_open: bad channel type %d", c->type);
848 buffer_append(&buffer, "\0", 1);
849 cp = xstrdup(buffer_ptr(&buffer));
850 buffer_free(&buffer);
854 /* Initiate forwarding of connections to local port "port" through the secure
855 channel to host:port from remote side. */
857 void channel_request_local_forwarding(int port, const char *host,
861 struct sockaddr_in sin;
862 extern Options options;
864 if (strlen(host) > sizeof(channels[0].path) - 1)
865 packet_disconnect("Forward host name too long.");
867 /* Create a port to listen for the host. */
868 sock = socket(AF_INET, SOCK_STREAM, 0);
870 packet_disconnect("socket: %.100s", strerror(errno));
872 /* Initialize socket address. */
873 memset(&sin, 0, sizeof(sin));
874 sin.sin_family = AF_INET;
875 if (options.gateway_ports == 1)
876 sin.sin_addr.s_addr = htonl(INADDR_ANY);
878 sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
879 sin.sin_port = htons(port);
881 /* Bind the socket to the address. */
882 if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
883 packet_disconnect("bind: %.100s", strerror(errno));
885 /* Start listening for connections on the socket. */
886 if (listen(sock, 5) < 0)
887 packet_disconnect("listen: %.100s", strerror(errno));
889 /* Allocate a channel number for the socket. */
890 ch = channel_allocate(SSH_CHANNEL_PORT_LISTENER, sock,
891 xstrdup("port listener"));
892 strcpy(channels[ch].path, host); /* note: host name stored here */
893 channels[ch].host_port = host_port; /* port on host to connect to */
894 channels[ch].listening_port = port; /* port being listened */
897 /* Initiate forwarding of connections to port "port" on remote host through
898 the secure channel to host:port from local side. */
900 void channel_request_remote_forwarding(int port, const char *host,
904 /* Record locally that connection to this host/port is permitted. */
905 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
906 fatal("channel_request_remote_forwarding: too many forwards");
907 permitted_opens[num_permitted_opens].host = xstrdup(host);
908 permitted_opens[num_permitted_opens].port = remote_port;
909 num_permitted_opens++;
911 /* Send the forward request to the remote side. */
912 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
913 packet_put_int(port);
914 packet_put_string(host, strlen(host));
915 packet_put_int(remote_port);
919 /* Wait for response from the remote side. It will send a disconnect
920 message on failure, and we will never see it here. */
921 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
924 /* This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
925 listening for the port, and sends back a success reply (or disconnect
926 message if there was an error). This never returns if there was an
929 void channel_input_port_forward_request(int is_root)
934 /* Get arguments from the packet. */
935 port = packet_get_int();
936 hostname = packet_get_string(NULL);
937 host_port = packet_get_int();
939 /* Port numbers are 16 bit quantities. */
940 if ((port & 0xffff) != port)
941 packet_disconnect("Requested forwarding of nonexistent port %d.", port);
943 /* Check that an unprivileged user is not trying to forward a privileged
945 if (port < IPPORT_RESERVED && !is_root)
946 packet_disconnect("Requested forwarding of port %d but user is not root.",
949 /* Initiate forwarding. */
950 channel_request_local_forwarding(port, hostname, host_port);
952 /* Free the argument string. */
956 /* This is called after receiving PORT_OPEN message. This attempts to connect
957 to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION or
958 CHANNEL_OPEN_FAILURE. */
960 void channel_input_port_open(int payload_len)
962 int remote_channel, sock, newch, host_port, i;
963 struct sockaddr_in sin;
964 char *host, *originator_string;
966 int host_len, originator_len;
968 /* Get remote channel number. */
969 remote_channel = packet_get_int();
971 /* Get host name to connect to. */
972 host = packet_get_string(&host_len);
974 /* Get port to connect to. */
975 host_port = packet_get_int();
977 /* Get remote originator name. */
978 if (have_hostname_in_open)
979 originator_string = packet_get_string(&originator_len);
981 originator_string = xstrdup("unknown (remote did not supply name)");
983 packet_integrity_check(payload_len,
984 4 + 4 + host_len + 4 + 4 + originator_len,
987 /* Check if opening that port is permitted. */
988 if (!all_opens_permitted)
990 /* Go trough all permitted ports. */
991 for (i = 0; i < num_permitted_opens; i++)
992 if (permitted_opens[i].port == host_port &&
993 strcmp(permitted_opens[i].host, host) == 0)
996 /* Check if we found the requested port among those permitted. */
997 if (i >= num_permitted_opens)
999 /* The port is not permitted. */
1000 log("Received request to connect to %.100s:%d, but the request was denied.",
1002 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1003 packet_put_int(remote_channel);
1008 memset(&sin, 0, sizeof(sin));
1009 sin.sin_addr.s_addr = inet_addr(host);
1010 if ((sin.sin_addr.s_addr & 0xffffffff) != 0xffffffff)
1012 /* It was a valid numeric host address. */
1013 sin.sin_family = AF_INET;
1017 /* Look up the host address from the name servers. */
1018 hp = gethostbyname(host);
1021 error("%.100s: unknown host.", host);
1024 if (!hp->h_addr_list[0])
1026 error("%.100s: host has no IP address.", host);
1029 sin.sin_family = hp->h_addrtype;
1030 memcpy(&sin.sin_addr, hp->h_addr_list[0],
1031 sizeof(sin.sin_addr));
1033 sin.sin_port = htons(host_port);
1035 /* Create the socket. */
1036 sock = socket(sin.sin_family, SOCK_STREAM, 0);
1039 error("socket: %.100s", strerror(errno));
1043 /* Connect to the host/port. */
1044 if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1046 error("connect %.100s:%d: %.100s", host, host_port,
1052 /* Successful connection. */
1054 /* Allocate a channel for this connection. */
1055 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, originator_string);
1056 channels[newch].remote_id = remote_channel;
1058 /* Send a confirmation to the remote host. */
1059 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1060 packet_put_int(remote_channel);
1061 packet_put_int(newch);
1064 /* Free the argument string. */
1070 /* Free the argument string. */
1073 /* Send refusal to the remote host. */
1074 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1075 packet_put_int(remote_channel);
1079 /* Creates an internet domain socket for listening for X11 connections.
1080 Returns a suitable value for the DISPLAY variable, or NULL if an error
1083 char *x11_create_display_inet(int screen_number)
1085 extern ServerOptions options;
1086 int display_number, port, sock;
1087 struct sockaddr_in sin;
1089 char hostname[MAXHOSTNAMELEN];
1091 for (display_number = options.x11_display_offset; display_number < MAX_DISPLAYS; display_number++)
1093 port = 6000 + display_number;
1094 memset(&sin, 0, sizeof(sin));
1095 sin.sin_family = AF_INET;
1096 sin.sin_addr.s_addr = htonl(INADDR_ANY);
1097 sin.sin_port = htons(port);
1099 sock = socket(AF_INET, SOCK_STREAM, 0);
1102 error("socket: %.100s", strerror(errno));
1106 if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1108 debug("bind port %d: %.100s", port, strerror(errno));
1109 shutdown(sock, SHUT_RDWR);
1115 if (display_number >= MAX_DISPLAYS)
1117 error("Failed to allocate internet-domain X11 display socket.");
1121 /* Start listening for connections on the socket. */
1122 if (listen(sock, 5) < 0)
1124 error("listen: %.100s", strerror(errno));
1125 shutdown(sock, SHUT_RDWR);
1130 /* Set up a suitable value for the DISPLAY variable. */
1131 if (gethostname(hostname, sizeof(hostname)) < 0)
1132 fatal("gethostname: %.100s", strerror(errno));
1133 snprintf(buf, sizeof buf, "%.400s:%d.%d", hostname,
1134 display_number, screen_number);
1136 /* Allocate a channel for the socket. */
1137 (void)channel_allocate(SSH_CHANNEL_X11_LISTENER, sock,
1138 xstrdup("X11 inet listener"));
1140 /* Return a suitable value for the DISPLAY environment variable. */
1141 return xstrdup(buf);
1145 #define X_UNIX_PATH "/tmp/.X11-unix/X"
1150 connect_local_xsocket(unsigned dnr)
1152 static const char *const x_sockets[] = {
1154 "/var/X/.X11-unix/X" "%u",
1155 "/usr/spool/sockets/X11/" "%u",
1159 struct sockaddr_un addr;
1160 const char *const *path;
1162 for (path = x_sockets; *path; ++path)
1164 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1166 error("socket: %.100s", strerror(errno));
1167 memset(&addr, 0, sizeof(addr));
1168 addr.sun_family = AF_UNIX;
1169 snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
1170 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
1174 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
1179 /* This is called when SSH_SMSG_X11_OPEN is received. The packet contains
1180 the remote channel number. We should do whatever we want, and respond
1181 with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE. */
1183 void x11_input_open(int payload_len)
1185 int remote_channel, display_number, sock, newch;
1186 const char *display;
1187 struct sockaddr_in sin;
1188 char buf[1024], *cp, *remote_host;
1192 /* Get remote channel number. */
1193 remote_channel = packet_get_int();
1195 /* Get remote originator name. */
1196 if (have_hostname_in_open)
1197 remote_host = packet_get_string(&remote_len);
1199 remote_host = xstrdup("unknown (remote did not supply name)");
1201 debug("Received X11 open request.");
1202 packet_integrity_check(payload_len, 4 + 4+remote_len, SSH_SMSG_X11_OPEN);
1204 /* Try to open a socket for the local X server. */
1205 display = getenv("DISPLAY");
1208 error("DISPLAY not set.");
1212 /* Now we decode the value of the DISPLAY variable and make a connection
1213 to the real X server. */
1215 /* Check if it is a unix domain socket. Unix domain displays are in one
1216 of the following formats: unix:d[.s], :d[.s], ::d[.s] */
1217 if (strncmp(display, "unix:", 5) == 0 ||
1220 /* Connect to the unix domain socket. */
1221 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1)
1223 error("Could not parse display number from DISPLAY: %.100s",
1227 /* Create a socket. */
1228 sock = connect_local_xsocket(display_number);
1232 /* OK, we now have a connection to the display. */
1236 /* Connect to an inet socket. The DISPLAY value is supposedly
1237 hostname:d[.s], where hostname may also be numeric IP address. */
1238 strncpy(buf, display, sizeof(buf));
1239 buf[sizeof(buf) - 1] = 0;
1240 cp = strchr(buf, ':');
1243 error("Could not find ':' in DISPLAY: %.100s", display);
1247 /* buf now contains the host name. But first we parse the display number. */
1248 if (sscanf(cp + 1, "%d", &display_number) != 1)
1250 error("Could not parse display number from DISPLAY: %.100s",
1255 /* Try to parse the host name as a numeric IP address. */
1256 memset(&sin, 0, sizeof(sin));
1257 sin.sin_addr.s_addr = inet_addr(buf);
1258 if ((sin.sin_addr.s_addr & 0xffffffff) != 0xffffffff)
1260 /* It was a valid numeric host address. */
1261 sin.sin_family = AF_INET;
1265 /* Not a numeric IP address. */
1266 /* Look up the host address from the name servers. */
1267 hp = gethostbyname(buf);
1270 error("%.100s: unknown host.", buf);
1273 if (!hp->h_addr_list[0])
1275 error("%.100s: host has no IP address.", buf);
1278 sin.sin_family = hp->h_addrtype;
1279 memcpy(&sin.sin_addr, hp->h_addr_list[0],
1280 sizeof(sin.sin_addr));
1282 /* Set port number. */
1283 sin.sin_port = htons(6000 + display_number);
1285 /* Create a socket. */
1286 sock = socket(sin.sin_family, SOCK_STREAM, 0);
1289 error("socket: %.100s", strerror(errno));
1292 /* Connect it to the display. */
1293 if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1295 error("connect %.100s:%d: %.100s", buf, 6000 + display_number,
1302 /* We have successfully obtained a connection to the real X display. */
1304 /* Allocate a channel for this connection. */
1305 if (x11_saved_proto == NULL)
1306 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, remote_host);
1308 newch = channel_allocate(SSH_CHANNEL_X11_OPEN, sock, remote_host);
1309 channels[newch].remote_id = remote_channel;
1311 /* Send a confirmation to the remote host. */
1312 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1313 packet_put_int(remote_channel);
1314 packet_put_int(newch);
1320 /* Send refusal to the remote host. */
1321 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1322 packet_put_int(remote_channel);
1326 /* Requests forwarding of X11 connections, generates fake authentication
1327 data, and enables authentication spoofing. */
1329 void x11_request_forwarding_with_spoofing(const char *proto, const char *data)
1331 unsigned int data_len = (unsigned int)strlen(data) / 2;
1332 unsigned int i, value;
1338 cp = getenv("DISPLAY");
1340 cp = strchr(cp, ':');
1342 cp = strchr(cp, '.');
1344 screen_number = atoi(cp + 1);
1348 /* Save protocol name. */
1349 x11_saved_proto = xstrdup(proto);
1351 /* Extract real authentication data and generate fake data of the same
1353 x11_saved_data = xmalloc(data_len);
1354 x11_fake_data = xmalloc(data_len);
1355 for (i = 0; i < data_len; i++)
1357 if (sscanf(data + 2 * i, "%2x", &value) != 1)
1358 fatal("x11_request_forwarding: bad authentication data: %.100s", data);
1360 rand = arc4random();
1361 x11_saved_data[i] = value;
1362 x11_fake_data[i] = rand & 0xff;
1365 x11_saved_data_len = data_len;
1366 x11_fake_data_len = data_len;
1368 /* Convert the fake data into hex. */
1369 new_data = xmalloc(2 * data_len + 1);
1370 for (i = 0; i < data_len; i++)
1371 sprintf(new_data + 2 * i, "%02x", (unsigned char)x11_fake_data[i]);
1373 /* Send the request packet. */
1374 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
1375 packet_put_string(proto, strlen(proto));
1376 packet_put_string(new_data, strlen(new_data));
1377 packet_put_int(screen_number);
1379 packet_write_wait();
1383 /* Sends a message to the server to request authentication fd forwarding. */
1385 void auth_request_forwarding()
1387 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
1389 packet_write_wait();
1392 /* Returns the name of the forwarded authentication socket. Returns NULL
1393 if there is no forwarded authentication socket. The returned value
1394 points to a static buffer. */
1396 char *auth_get_socket_name()
1398 return channel_forwarded_auth_socket_name;
1401 /* removes the agent forwarding socket */
1403 void cleanup_socket(void) {
1404 remove(channel_forwarded_auth_socket_name);
1405 rmdir(channel_forwarded_auth_socket_dir);
1408 /* This if called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
1409 This starts forwarding authentication requests. */
1411 void auth_input_request_forwarding(struct passwd *pw)
1414 struct sockaddr_un sunaddr;
1416 if (auth_get_socket_name() != NULL)
1417 fatal("Protocol error: authentication forwarding requested twice.");
1419 /* Temporarily drop privileged uid for mkdir/bind. */
1420 temporarily_use_uid(pw->pw_uid);
1422 /* Allocate a buffer for the socket name, and format the name. */
1423 channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
1424 channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
1425 strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
1427 /* Create private directory for socket */
1428 if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL)
1429 packet_disconnect("mkdtemp: %.100s", strerror(errno));
1430 snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME,
1431 "%s/agent.%d", channel_forwarded_auth_socket_dir, (int)getpid());
1433 if (atexit(cleanup_socket) < 0) {
1436 packet_disconnect("socket: %.100s", strerror(saved));
1439 /* Create the socket. */
1440 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1442 packet_disconnect("socket: %.100s", strerror(errno));
1444 /* Bind it to the name. */
1445 memset(&sunaddr, 0, sizeof(sunaddr));
1446 sunaddr.sun_family = AF_UNIX;
1447 strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
1448 sizeof(sunaddr.sun_path));
1450 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0)
1451 packet_disconnect("bind: %.100s", strerror(errno));
1453 /* Restore the privileged uid. */
1456 /* Start listening on the socket. */
1457 if (listen(sock, 5) < 0)
1458 packet_disconnect("listen: %.100s", strerror(errno));
1460 /* Allocate a channel for the authentication agent socket. */
1461 newch = channel_allocate(SSH_CHANNEL_AUTH_SOCKET, sock,
1462 xstrdup("auth socket"));
1463 strcpy(channels[newch].path, channel_forwarded_auth_socket_name);
1466 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
1468 void auth_input_open_request()
1470 int remch, sock, newch;
1473 /* Read the remote channel number from the message. */
1474 remch = packet_get_int();
1476 /* Get a connection to the local authentication agent (this may again get
1478 sock = ssh_get_authentication_socket();
1480 /* If we could not connect the agent, send an error message back to
1481 the server. This should never happen unless the agent
1482 dies, because authentication forwarding is only enabled if we have an
1485 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1486 packet_put_int(remch);
1491 debug("Forwarding authentication connection.");
1493 /* Dummy host name. This will be freed when the channel is freed; it will
1494 still be valid in the packet_put_string below since the channel cannot
1495 yet be freed at that point. */
1496 dummyname = xstrdup("authentication agent connection");
1498 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
1499 channels[newch].remote_id = remch;
1501 /* Send a confirmation to the remote host. */
1502 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1503 packet_put_int(remch);
1504 packet_put_int(newch);