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);
161 c->remote_name = remote_name;
162 debug("channel %d: new [%s]", found, remote_name);
166 /* Free the channel and close its socket. */
168 void channel_free(int channel)
170 assert(channel >= 0 && channel < channels_alloc &&
171 channels[channel].type != SSH_CHANNEL_FREE);
173 shutdown(channels[channel].sock, SHUT_RDWR);
174 close(channels[channel].sock);
175 buffer_free(&channels[channel].input);
176 buffer_free(&channels[channel].output);
177 channels[channel].type = SSH_CHANNEL_FREE;
178 if (channels[channel].remote_name)
180 xfree(channels[channel].remote_name);
181 channels[channel].remote_name = NULL;
185 /* This is called just before select() to add any bits relevant to
186 channels in the select bitmasks. */
188 void channel_prepare_select(fd_set *readset, fd_set *writeset)
193 unsigned int proto_len, data_len;
195 for (i = 0; i < channels_alloc; i++)
201 case SSH_CHANNEL_X11_LISTENER:
202 case SSH_CHANNEL_PORT_LISTENER:
203 case SSH_CHANNEL_AUTH_SOCKET:
204 FD_SET(ch->sock, readset);
207 case SSH_CHANNEL_OPEN:
209 if (buffer_len(&ch->input) < 32768)
210 FD_SET(ch->sock, readset);
211 if (buffer_len(&ch->output) > 0)
212 FD_SET(ch->sock, writeset);
215 /* test whether sockets are 'alive' for read/write */
216 if (ch->istate == CHAN_INPUT_OPEN)
217 if (buffer_len(&ch->input) < 32768)
218 FD_SET(ch->sock, readset);
219 if (ch->ostate == CHAN_OUTPUT_OPEN || ch->ostate == CHAN_OUTPUT_WAIT_DRAIN){
220 if (buffer_len(&ch->output) > 0){
221 FD_SET(ch->sock, writeset);
222 }else if(ch->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
228 case SSH_CHANNEL_INPUT_DRAINING:
230 fatal("cannot happen: IN_DRAIN");
231 if (buffer_len(&ch->input) == 0)
233 packet_start(SSH_MSG_CHANNEL_CLOSE);
234 packet_put_int(ch->remote_id);
236 ch->type = SSH_CHANNEL_CLOSED;
237 debug("Closing channel %d after input drain.", i);
242 case SSH_CHANNEL_OUTPUT_DRAINING:
244 fatal("cannot happen: OUT_DRAIN");
245 if (buffer_len(&ch->output) == 0)
247 /* debug("Freeing channel %d after output drain.", i); */
251 FD_SET(ch->sock, writeset);
254 case SSH_CHANNEL_X11_OPEN:
255 /* This is a special state for X11 authentication spoofing. An
256 opened X11 connection (when authentication spoofing is being
257 done) remains in this state until the first packet has been
258 completely read. The authentication data in that packet is
259 then substituted by the real data if it matches the fake data,
260 and the channel is put into normal mode. */
262 /* Check if the fixed size part of the packet is in buffer. */
263 if (buffer_len(&ch->output) < 12)
266 /* Parse the lengths of variable-length fields. */
267 ucp = (unsigned char *)buffer_ptr(&ch->output);
269 { /* Byte order MSB first. */
270 proto_len = 256 * ucp[6] + ucp[7];
271 data_len = 256 * ucp[8] + ucp[9];
275 { /* Byte order LSB first. */
276 proto_len = ucp[6] + 256 * ucp[7];
277 data_len = ucp[8] + 256 * ucp[9];
281 debug("Initial X11 packet contains bad byte order byte: 0x%x",
283 ch->type = SSH_CHANNEL_OPEN;
287 /* Check if the whole packet is in buffer. */
288 if (buffer_len(&ch->output) <
289 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
292 /* Check if authentication protocol matches. */
293 if (proto_len != strlen(x11_saved_proto) ||
294 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0)
296 debug("X11 connection uses different authentication protocol.");
297 ch->type = SSH_CHANNEL_OPEN;
301 /* Check if authentication data matches our fake data. */
302 if (data_len != x11_fake_data_len ||
303 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
304 x11_fake_data, x11_fake_data_len) != 0)
306 debug("X11 auth data does not match fake data.");
307 ch->type = SSH_CHANNEL_OPEN;
311 /* Received authentication protocol and data match our fake data.
312 Substitute the fake data with real data. */
313 assert(x11_fake_data_len == x11_saved_data_len);
314 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
315 x11_saved_data, x11_saved_data_len);
317 /* Start normal processing for the channel. */
318 ch->type = SSH_CHANNEL_OPEN;
319 /* Enable X11 Problem FIX */
324 /* We have received an X11 connection that has bad authentication
326 log("X11 connection rejected because of wrong authentication.\r\n");
327 buffer_clear(&ch->input);
328 buffer_clear(&ch->output);
332 ch->type = SSH_CHANNEL_CLOSED;
333 packet_start(SSH_MSG_CHANNEL_CLOSE);
334 packet_put_int(ch->remote_id);
337 debug("X11 rejected %d i%d/o%d", ch->self, ch->istate, ch->ostate);
338 chan_read_failed(ch);
339 chan_write_failed(ch);
340 debug("X11 rejected %d i%d/o%d", ch->self, ch->istate, ch->ostate);
344 case SSH_CHANNEL_FREE:
351 /* After select, perform any appropriate operations for channels which
352 have events pending. */
354 void channel_after_select(fd_set *readset, fd_set *writeset)
356 struct sockaddr addr;
357 int addrlen, newsock, i, newch, len;
359 char buf[16384], *remote_hostname;
361 /* Loop over all channels... */
362 for (i = 0; i < channels_alloc; i++)
367 case SSH_CHANNEL_X11_LISTENER:
368 /* This is our fake X11 server socket. */
369 if (FD_ISSET(ch->sock, readset))
371 debug("X11 connection requested.");
372 addrlen = sizeof(addr);
373 newsock = accept(ch->sock, &addr, &addrlen);
376 error("accept: %.100s", strerror(errno));
379 remote_hostname = get_remote_hostname(newsock);
380 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
381 remote_hostname, get_peer_port(newsock));
382 xfree(remote_hostname);
383 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
385 packet_start(SSH_SMSG_X11_OPEN);
386 packet_put_int(newch);
387 if (have_hostname_in_open)
388 packet_put_string(buf, strlen(buf));
393 case SSH_CHANNEL_PORT_LISTENER:
394 /* This socket is listening for connections to a forwarded TCP/IP
396 if (FD_ISSET(ch->sock, readset))
398 debug("Connection to port %d forwarding to %.100s:%d requested.",
399 ch->listening_port, ch->path, ch->host_port);
400 addrlen = sizeof(addr);
401 newsock = accept(ch->sock, &addr, &addrlen);
404 error("accept: %.100s", strerror(errno));
407 remote_hostname = get_remote_hostname(newsock);
408 snprintf(buf, sizeof buf, "listen port %d:%.100s:%d, connect from %.200s:%d",
409 ch->listening_port, ch->path, ch->host_port,
410 remote_hostname, get_peer_port(newsock));
411 xfree(remote_hostname);
412 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
414 packet_start(SSH_MSG_PORT_OPEN);
415 packet_put_int(newch);
416 packet_put_string(ch->path, strlen(ch->path));
417 packet_put_int(ch->host_port);
418 if (have_hostname_in_open)
419 packet_put_string(buf, strlen(buf));
424 case SSH_CHANNEL_AUTH_SOCKET:
425 /* This is the authentication agent socket listening for connections
427 if (FD_ISSET(ch->sock, readset))
431 newsock = accept(ch->sock, &addr, &len);
434 error("accept from auth socket: %.100s", strerror(errno));
438 nchan = channel_allocate(SSH_CHANNEL_OPENING, newsock,
439 xstrdup("accepted auth socket"));
440 packet_start(SSH_SMSG_AGENT_OPEN);
441 packet_put_int(nchan);
446 case SSH_CHANNEL_OPEN:
447 /* This is an open two-way communication channel. It is not of
448 interest to us at this point what kind of data is being
451 /* Read available incoming data and append it to buffer;
452 shutdown socket, if read or write failes */
453 if (FD_ISSET(ch->sock, readset))
455 len = read(ch->sock, buf, sizeof(buf));
459 buffer_consume(&ch->output, buffer_len(&ch->output));
460 ch->type = SSH_CHANNEL_INPUT_DRAINING;
461 debug("Channel %d status set to input draining.", i);
463 chan_read_failed(ch);
467 buffer_append(&ch->input, buf, len);
469 /* Send buffered output data to the socket. */
470 if (FD_ISSET(ch->sock, writeset) && buffer_len(&ch->output) > 0)
472 len = write(ch->sock, buffer_ptr(&ch->output),
473 buffer_len(&ch->output));
477 buffer_consume(&ch->output, buffer_len(&ch->output));
478 debug("Channel %d status set to input draining.", i);
479 ch->type = SSH_CHANNEL_INPUT_DRAINING;
481 chan_write_failed(ch);
485 buffer_consume(&ch->output, len);
489 case SSH_CHANNEL_OUTPUT_DRAINING:
491 fatal("cannot happen: OUT_DRAIN");
492 /* Send buffered output data to the socket. */
493 if (FD_ISSET(ch->sock, writeset) && buffer_len(&ch->output) > 0)
495 len = write(ch->sock, buffer_ptr(&ch->output),
496 buffer_len(&ch->output));
498 buffer_consume(&ch->output, buffer_len(&ch->output));
500 buffer_consume(&ch->output, len);
504 case SSH_CHANNEL_X11_OPEN:
505 case SSH_CHANNEL_FREE:
512 /* If there is data to send to the connection, send some of it now. */
514 void channel_output_poll()
519 for (i = 0; i < channels_alloc; i++)
522 /* We are only interested in channels that can have buffered incoming
524 if (ch->type != SSH_CHANNEL_OPEN &&
525 ch->type != SSH_CHANNEL_INPUT_DRAINING)
528 /* Get the amount of buffered data for this channel. */
529 len = buffer_len(&ch->input);
532 /* Send some data for the other side over the secure connection. */
533 if (packet_is_interactive())
541 len = 16384; /* Keep the packets at reasonable size. */
543 packet_start(SSH_MSG_CHANNEL_DATA);
544 packet_put_int(ch->remote_id);
545 packet_put_string(buffer_ptr(&ch->input), len);
547 buffer_consume(&ch->input, len);
549 else if(ch->istate == CHAN_INPUT_WAIT_DRAIN)
552 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
553 /* input-buffer is empty and read-socket shutdown:
554 tell peer, that we will not send more data: send IEOF */
560 /* This is called when a packet of type CHANNEL_DATA has just been received.
561 The message type has already been consumed, but channel number and data
564 void channel_input_data(int payload_len)
568 unsigned int data_len;
570 /* Get the channel number and verify it. */
571 channel = packet_get_int();
572 if (channel < 0 || channel >= channels_alloc ||
573 channels[channel].type == SSH_CHANNEL_FREE)
574 packet_disconnect("Received data for nonexistent channel %d.", channel);
576 /* Ignore any data for non-open channels (might happen on close) */
577 if (channels[channel].type != SSH_CHANNEL_OPEN &&
578 channels[channel].type != SSH_CHANNEL_X11_OPEN)
582 data = packet_get_string(&data_len);
583 packet_integrity_check(payload_len, 4 + 4+data_len, SSH_MSG_CHANNEL_DATA);
584 buffer_append(&channels[channel].output, data, data_len);
588 /* Returns true if no channel has too much buffered data, and false if
589 one or more channel is overfull. */
591 int channel_not_very_much_buffered_data()
596 for (i = 0; i < channels_alloc; i++)
601 case SSH_CHANNEL_X11_LISTENER:
602 case SSH_CHANNEL_PORT_LISTENER:
603 case SSH_CHANNEL_AUTH_SOCKET:
605 case SSH_CHANNEL_OPEN:
606 if (buffer_len(&ch->input) > 32768)
608 if (buffer_len(&ch->output) > 32768)
611 case SSH_CHANNEL_INPUT_DRAINING:
612 case SSH_CHANNEL_OUTPUT_DRAINING:
613 case SSH_CHANNEL_X11_OPEN:
614 case SSH_CHANNEL_FREE:
622 /* This is called after receiving CHANNEL_CLOSE/IEOF. */
624 void channel_input_close()
628 /* Get the channel number and verify it. */
629 channel = packet_get_int();
630 if (channel < 0 || channel >= channels_alloc ||
631 channels[channel].type == SSH_CHANNEL_FREE)
632 packet_disconnect("Received data for nonexistent channel %d.", channel);
635 /* proto version 1.5 overloads CLOSE with IEOF */
636 chan_rcvd_ieof(&channels[channel]);
640 /* Send a confirmation that we have closed the channel and no more data is
642 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
643 packet_put_int(channels[channel].remote_id);
646 /* If the channel is in closed state, we have sent a close request, and
647 the other side will eventually respond with a confirmation. Thus,
648 we cannot free the channel here, because then there would be no-one to
649 receive the confirmation. The channel gets freed when the confirmation
651 if (channels[channel].type != SSH_CHANNEL_CLOSED)
653 /* Not a closed channel - mark it as draining, which will cause it to
655 buffer_consume(&channels[channel].input,
656 buffer_len(&channels[channel].input));
657 channels[channel].type = SSH_CHANNEL_OUTPUT_DRAINING;
658 /* debug("Setting status to output draining; output len = %d",
659 buffer_len(&channels[channel].output)); */
663 /* This is called after receiving CHANNEL_CLOSE_CONFIRMATION/OCLOSE. */
665 void channel_input_close_confirmation()
669 /* Get the channel number and verify it. */
670 channel = packet_get_int();
671 if (channel < 0 || channel >= channels_alloc)
672 packet_disconnect("Received close confirmation for out-of-range channel %d.",
676 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
677 chan_rcvd_oclose(&channels[channel]);
681 if (channels[channel].type != SSH_CHANNEL_CLOSED)
682 packet_disconnect("Received close confirmation for non-closed channel %d (type %d).",
683 channel, channels[channel].type);
685 /* Free the channel. */
686 channel_free(channel);
689 /* This is called after receiving CHANNEL_OPEN_CONFIRMATION. */
691 void channel_input_open_confirmation()
693 int channel, remote_channel;
695 /* Get the channel number and verify it. */
696 channel = packet_get_int();
697 if (channel < 0 || channel >= channels_alloc ||
698 channels[channel].type != SSH_CHANNEL_OPENING)
699 packet_disconnect("Received open confirmation for non-opening channel %d.",
702 /* Get remote side's id for this channel. */
703 remote_channel = packet_get_int();
705 /* Record the remote channel number and mark that the channel is now open. */
706 channels[channel].remote_id = remote_channel;
707 channels[channel].type = SSH_CHANNEL_OPEN;
710 /* This is called after receiving CHANNEL_OPEN_FAILURE from the other side. */
712 void channel_input_open_failure()
716 /* Get the channel number and verify it. */
717 channel = packet_get_int();
718 if (channel < 0 || channel >= channels_alloc ||
719 channels[channel].type != SSH_CHANNEL_OPENING)
720 packet_disconnect("Received open failure for non-opening channel %d.",
723 /* Free the channel. This will also close the socket. */
724 channel_free(channel);
727 /* Stops listening for channels, and removes any unix domain sockets that
730 void channel_stop_listening()
733 for (i = 0; i < channels_alloc; i++)
735 switch (channels[i].type)
737 case SSH_CHANNEL_AUTH_SOCKET:
738 close(channels[i].sock);
739 remove(channels[i].path);
742 case SSH_CHANNEL_PORT_LISTENER:
743 case SSH_CHANNEL_X11_LISTENER:
744 close(channels[i].sock);
753 /* Closes the sockets of all channels. This is used to close extra file
754 descriptors after a fork. */
756 void channel_close_all()
759 for (i = 0; i < channels_alloc; i++)
761 if (channels[i].type != SSH_CHANNEL_FREE)
762 close(channels[i].sock);
766 /* Returns the maximum file descriptor number used by the channels. */
770 return channel_max_fd_value;
773 /* Returns true if any channel is still open. */
775 int channel_still_open()
778 for (i = 0; i < channels_alloc; i++)
779 switch (channels[i].type)
781 case SSH_CHANNEL_FREE:
782 case SSH_CHANNEL_X11_LISTENER:
783 case SSH_CHANNEL_PORT_LISTENER:
784 case SSH_CHANNEL_CLOSED:
785 case SSH_CHANNEL_AUTH_SOCKET:
787 case SSH_CHANNEL_OPENING:
788 case SSH_CHANNEL_OPEN:
789 case SSH_CHANNEL_X11_OPEN:
791 case SSH_CHANNEL_INPUT_DRAINING:
792 case SSH_CHANNEL_OUTPUT_DRAINING:
794 fatal("cannot happen: OUT_DRAIN");
797 fatal("channel_still_open: bad channel type %d", channels[i].type);
803 /* Returns a message describing the currently open forwarded
804 connections, suitable for sending to the client. The message
805 contains crlf pairs for newlines. */
807 char *channel_open_message()
813 buffer_init(&buffer);
814 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
815 buffer_append(&buffer, buf, strlen(buf));
816 for (i = 0; i < channels_alloc; i++){
817 Channel *c=&channels[i];
820 case SSH_CHANNEL_FREE:
821 case SSH_CHANNEL_X11_LISTENER:
822 case SSH_CHANNEL_PORT_LISTENER:
823 case SSH_CHANNEL_CLOSED:
824 case SSH_CHANNEL_AUTH_SOCKET:
826 case SSH_CHANNEL_OPENING:
827 case SSH_CHANNEL_OPEN:
828 case SSH_CHANNEL_X11_OPEN:
829 case SSH_CHANNEL_INPUT_DRAINING:
830 case SSH_CHANNEL_OUTPUT_DRAINING:
831 snprintf(buf, sizeof buf, " #%d %.300s (t%d r%d i%d o%d)\r\n",
832 c->self,c->remote_name,
833 c->type,c->remote_id, c->istate,c->ostate);
834 buffer_append(&buffer, buf, strlen(buf));
837 fatal("channel_still_open: bad channel type %d", c->type);
841 buffer_append(&buffer, "\0", 1);
842 cp = xstrdup(buffer_ptr(&buffer));
843 buffer_free(&buffer);
847 /* Initiate forwarding of connections to local port "port" through the secure
848 channel to host:port from remote side. */
850 void channel_request_local_forwarding(int port, const char *host,
854 struct sockaddr_in sin;
855 extern Options options;
857 if (strlen(host) > sizeof(channels[0].path) - 1)
858 packet_disconnect("Forward host name too long.");
860 /* Create a port to listen for the host. */
861 sock = socket(AF_INET, SOCK_STREAM, 0);
863 packet_disconnect("socket: %.100s", strerror(errno));
865 /* Initialize socket address. */
866 memset(&sin, 0, sizeof(sin));
867 sin.sin_family = AF_INET;
868 if (options.gateway_ports == 1)
869 sin.sin_addr.s_addr = htonl(INADDR_ANY);
871 sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
872 sin.sin_port = htons(port);
874 /* Bind the socket to the address. */
875 if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
876 packet_disconnect("bind: %.100s", strerror(errno));
878 /* Start listening for connections on the socket. */
879 if (listen(sock, 5) < 0)
880 packet_disconnect("listen: %.100s", strerror(errno));
882 /* Allocate a channel number for the socket. */
883 ch = channel_allocate(SSH_CHANNEL_PORT_LISTENER, sock,
884 xstrdup("port listener"));
885 strcpy(channels[ch].path, host); /* note: host name stored here */
886 channels[ch].host_port = host_port; /* port on host to connect to */
887 channels[ch].listening_port = port; /* port being listened */
890 /* Initiate forwarding of connections to port "port" on remote host through
891 the secure channel to host:port from local side. */
893 void channel_request_remote_forwarding(int port, const char *host,
897 /* Record locally that connection to this host/port is permitted. */
898 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
899 fatal("channel_request_remote_forwarding: too many forwards");
900 permitted_opens[num_permitted_opens].host = xstrdup(host);
901 permitted_opens[num_permitted_opens].port = remote_port;
902 num_permitted_opens++;
904 /* Send the forward request to the remote side. */
905 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
906 packet_put_int(port);
907 packet_put_string(host, strlen(host));
908 packet_put_int(remote_port);
912 /* Wait for response from the remote side. It will send a disconnect
913 message on failure, and we will never see it here. */
914 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
917 /* This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
918 listening for the port, and sends back a success reply (or disconnect
919 message if there was an error). This never returns if there was an
922 void channel_input_port_forward_request(int is_root)
927 /* Get arguments from the packet. */
928 port = packet_get_int();
929 hostname = packet_get_string(NULL);
930 host_port = packet_get_int();
932 /* Port numbers are 16 bit quantities. */
933 if ((port & 0xffff) != port)
934 packet_disconnect("Requested forwarding of nonexistent port %d.", port);
936 /* Check that an unprivileged user is not trying to forward a privileged
938 if (port < IPPORT_RESERVED && !is_root)
939 packet_disconnect("Requested forwarding of port %d but user is not root.",
942 /* Initiate forwarding. */
943 channel_request_local_forwarding(port, hostname, host_port);
945 /* Free the argument string. */
949 /* This is called after receiving PORT_OPEN message. This attempts to connect
950 to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION or
951 CHANNEL_OPEN_FAILURE. */
953 void channel_input_port_open(int payload_len)
955 int remote_channel, sock, newch, host_port, i;
956 struct sockaddr_in sin;
957 char *host, *originator_string;
959 int host_len, originator_len;
961 /* Get remote channel number. */
962 remote_channel = packet_get_int();
964 /* Get host name to connect to. */
965 host = packet_get_string(&host_len);
967 /* Get port to connect to. */
968 host_port = packet_get_int();
970 /* Get remote originator name. */
971 if (have_hostname_in_open)
972 originator_string = packet_get_string(&originator_len);
974 originator_string = xstrdup("unknown (remote did not supply name)");
976 packet_integrity_check(payload_len,
977 4 + 4 + host_len + 4 + 4 + originator_len,
980 /* Check if opening that port is permitted. */
981 if (!all_opens_permitted)
983 /* Go trough all permitted ports. */
984 for (i = 0; i < num_permitted_opens; i++)
985 if (permitted_opens[i].port == host_port &&
986 strcmp(permitted_opens[i].host, host) == 0)
989 /* Check if we found the requested port among those permitted. */
990 if (i >= num_permitted_opens)
992 /* The port is not permitted. */
993 log("Received request to connect to %.100s:%d, but the request was denied.",
995 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
996 packet_put_int(remote_channel);
1001 memset(&sin, 0, sizeof(sin));
1002 sin.sin_addr.s_addr = inet_addr(host);
1003 if ((sin.sin_addr.s_addr & 0xffffffff) != 0xffffffff)
1005 /* It was a valid numeric host address. */
1006 sin.sin_family = AF_INET;
1010 /* Look up the host address from the name servers. */
1011 hp = gethostbyname(host);
1014 error("%.100s: unknown host.", host);
1017 if (!hp->h_addr_list[0])
1019 error("%.100s: host has no IP address.", host);
1022 sin.sin_family = hp->h_addrtype;
1023 memcpy(&sin.sin_addr, hp->h_addr_list[0],
1024 sizeof(sin.sin_addr));
1026 sin.sin_port = htons(host_port);
1028 /* Create the socket. */
1029 sock = socket(sin.sin_family, SOCK_STREAM, 0);
1032 error("socket: %.100s", strerror(errno));
1036 /* Connect to the host/port. */
1037 if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1039 error("connect %.100s:%d: %.100s", host, host_port,
1045 /* Successful connection. */
1047 /* Allocate a channel for this connection. */
1048 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, originator_string);
1049 channels[newch].remote_id = remote_channel;
1051 /* Send a confirmation to the remote host. */
1052 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1053 packet_put_int(remote_channel);
1054 packet_put_int(newch);
1057 /* Free the argument string. */
1063 /* Free the argument string. */
1066 /* Send refusal to the remote host. */
1067 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1068 packet_put_int(remote_channel);
1072 /* Creates an internet domain socket for listening for X11 connections.
1073 Returns a suitable value for the DISPLAY variable, or NULL if an error
1076 char *x11_create_display_inet(int screen_number)
1078 extern ServerOptions options;
1079 int display_number, port, sock;
1080 struct sockaddr_in sin;
1082 char hostname[MAXHOSTNAMELEN];
1084 for (display_number = options.x11_display_offset; display_number < MAX_DISPLAYS; display_number++)
1086 port = 6000 + display_number;
1087 memset(&sin, 0, sizeof(sin));
1088 sin.sin_family = AF_INET;
1089 sin.sin_addr.s_addr = htonl(INADDR_ANY);
1090 sin.sin_port = htons(port);
1092 sock = socket(AF_INET, SOCK_STREAM, 0);
1095 error("socket: %.100s", strerror(errno));
1099 if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1101 debug("bind port %d: %.100s", port, strerror(errno));
1102 shutdown(sock, SHUT_RDWR);
1108 if (display_number >= MAX_DISPLAYS)
1110 error("Failed to allocate internet-domain X11 display socket.");
1114 /* Start listening for connections on the socket. */
1115 if (listen(sock, 5) < 0)
1117 error("listen: %.100s", strerror(errno));
1118 shutdown(sock, SHUT_RDWR);
1123 /* Set up a suitable value for the DISPLAY variable. */
1124 if (gethostname(hostname, sizeof(hostname)) < 0)
1125 fatal("gethostname: %.100s", strerror(errno));
1126 snprintf(buf, sizeof buf, "%.400s:%d.%d", hostname,
1127 display_number, screen_number);
1129 /* Allocate a channel for the socket. */
1130 (void)channel_allocate(SSH_CHANNEL_X11_LISTENER, sock,
1131 xstrdup("X11 inet listener"));
1133 /* Return a suitable value for the DISPLAY environment variable. */
1134 return xstrdup(buf);
1138 #define X_UNIX_PATH "/tmp/.X11-unix/X"
1143 connect_local_xsocket(unsigned dnr)
1145 static const char *const x_sockets[] = {
1147 "/var/X/.X11-unix/X" "%u",
1148 "/usr/spool/sockets/X11/" "%u",
1152 struct sockaddr_un addr;
1153 const char *const *path;
1155 for (path = x_sockets; *path; ++path)
1157 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1159 error("socket: %.100s", strerror(errno));
1160 memset(&addr, 0, sizeof(addr));
1161 addr.sun_family = AF_UNIX;
1162 snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
1163 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
1167 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
1172 /* This is called when SSH_SMSG_X11_OPEN is received. The packet contains
1173 the remote channel number. We should do whatever we want, and respond
1174 with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE. */
1176 void x11_input_open(int payload_len)
1178 int remote_channel, display_number, sock, newch;
1179 const char *display;
1180 struct sockaddr_in sin;
1181 char buf[1024], *cp, *remote_host;
1185 /* Get remote channel number. */
1186 remote_channel = packet_get_int();
1188 /* Get remote originator name. */
1189 if (have_hostname_in_open)
1190 remote_host = packet_get_string(&remote_len);
1192 remote_host = xstrdup("unknown (remote did not supply name)");
1194 debug("Received X11 open request.");
1195 packet_integrity_check(payload_len, 4 + 4+remote_len, SSH_SMSG_X11_OPEN);
1197 /* Try to open a socket for the local X server. */
1198 display = getenv("DISPLAY");
1201 error("DISPLAY not set.");
1205 /* Now we decode the value of the DISPLAY variable and make a connection
1206 to the real X server. */
1208 /* Check if it is a unix domain socket. Unix domain displays are in one
1209 of the following formats: unix:d[.s], :d[.s], ::d[.s] */
1210 if (strncmp(display, "unix:", 5) == 0 ||
1213 /* Connect to the unix domain socket. */
1214 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1)
1216 error("Could not parse display number from DISPLAY: %.100s",
1220 /* Create a socket. */
1221 sock = connect_local_xsocket(display_number);
1225 /* OK, we now have a connection to the display. */
1229 /* Connect to an inet socket. The DISPLAY value is supposedly
1230 hostname:d[.s], where hostname may also be numeric IP address. */
1231 strncpy(buf, display, sizeof(buf));
1232 buf[sizeof(buf) - 1] = 0;
1233 cp = strchr(buf, ':');
1236 error("Could not find ':' in DISPLAY: %.100s", display);
1240 /* buf now contains the host name. But first we parse the display number. */
1241 if (sscanf(cp + 1, "%d", &display_number) != 1)
1243 error("Could not parse display number from DISPLAY: %.100s",
1248 /* Try to parse the host name as a numeric IP address. */
1249 memset(&sin, 0, sizeof(sin));
1250 sin.sin_addr.s_addr = inet_addr(buf);
1251 if ((sin.sin_addr.s_addr & 0xffffffff) != 0xffffffff)
1253 /* It was a valid numeric host address. */
1254 sin.sin_family = AF_INET;
1258 /* Not a numeric IP address. */
1259 /* Look up the host address from the name servers. */
1260 hp = gethostbyname(buf);
1263 error("%.100s: unknown host.", buf);
1266 if (!hp->h_addr_list[0])
1268 error("%.100s: host has no IP address.", buf);
1271 sin.sin_family = hp->h_addrtype;
1272 memcpy(&sin.sin_addr, hp->h_addr_list[0],
1273 sizeof(sin.sin_addr));
1275 /* Set port number. */
1276 sin.sin_port = htons(6000 + display_number);
1278 /* Create a socket. */
1279 sock = socket(sin.sin_family, SOCK_STREAM, 0);
1282 error("socket: %.100s", strerror(errno));
1285 /* Connect it to the display. */
1286 if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1288 error("connect %.100s:%d: %.100s", buf, 6000 + display_number,
1295 /* We have successfully obtained a connection to the real X display. */
1297 /* Allocate a channel for this connection. */
1298 if (x11_saved_proto == NULL)
1299 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, remote_host);
1301 newch = channel_allocate(SSH_CHANNEL_X11_OPEN, sock, remote_host);
1302 channels[newch].remote_id = remote_channel;
1304 /* Send a confirmation to the remote host. */
1305 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1306 packet_put_int(remote_channel);
1307 packet_put_int(newch);
1313 /* Send refusal to the remote host. */
1314 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1315 packet_put_int(remote_channel);
1319 /* Requests forwarding of X11 connections, generates fake authentication
1320 data, and enables authentication spoofing. */
1322 void x11_request_forwarding_with_spoofing(const char *proto, const char *data)
1324 unsigned int data_len = (unsigned int)strlen(data) / 2;
1325 unsigned int i, value;
1331 cp = getenv("DISPLAY");
1333 cp = strchr(cp, ':');
1335 cp = strchr(cp, '.');
1337 screen_number = atoi(cp + 1);
1341 /* Save protocol name. */
1342 x11_saved_proto = xstrdup(proto);
1344 /* Extract real authentication data and generate fake data of the same
1346 x11_saved_data = xmalloc(data_len);
1347 x11_fake_data = xmalloc(data_len);
1348 for (i = 0; i < data_len; i++)
1350 if (sscanf(data + 2 * i, "%2x", &value) != 1)
1351 fatal("x11_request_forwarding: bad authentication data: %.100s", data);
1353 rand = arc4random();
1354 x11_saved_data[i] = value;
1355 x11_fake_data[i] = rand & 0xff;
1358 x11_saved_data_len = data_len;
1359 x11_fake_data_len = data_len;
1361 /* Convert the fake data into hex. */
1362 new_data = xmalloc(2 * data_len + 1);
1363 for (i = 0; i < data_len; i++)
1364 sprintf(new_data + 2 * i, "%02x", (unsigned char)x11_fake_data[i]);
1366 /* Send the request packet. */
1367 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
1368 packet_put_string(proto, strlen(proto));
1369 packet_put_string(new_data, strlen(new_data));
1370 packet_put_int(screen_number);
1372 packet_write_wait();
1376 /* Sends a message to the server to request authentication fd forwarding. */
1378 void auth_request_forwarding()
1380 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
1382 packet_write_wait();
1385 /* Returns the name of the forwarded authentication socket. Returns NULL
1386 if there is no forwarded authentication socket. The returned value
1387 points to a static buffer. */
1389 char *auth_get_socket_name()
1391 return channel_forwarded_auth_socket_name;
1394 /* removes the agent forwarding socket */
1396 void cleanup_socket(void) {
1397 remove(channel_forwarded_auth_socket_name);
1398 rmdir(channel_forwarded_auth_socket_dir);
1401 /* This if called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
1402 This starts forwarding authentication requests. */
1404 void auth_input_request_forwarding(struct passwd *pw)
1407 struct sockaddr_un sunaddr;
1409 if (auth_get_socket_name() != NULL)
1410 fatal("Protocol error: authentication forwarding requested twice.");
1412 /* Temporarily drop privileged uid for mkdir/bind. */
1413 temporarily_use_uid(pw->pw_uid);
1415 /* Allocate a buffer for the socket name, and format the name. */
1416 channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
1417 channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
1418 strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
1420 /* Create private directory for socket */
1421 if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL)
1422 packet_disconnect("mkdtemp: %.100s", strerror(errno));
1423 snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME,
1424 "%s/agent.%d", channel_forwarded_auth_socket_dir, (int)getpid());
1426 if (atexit(cleanup_socket) < 0) {
1429 packet_disconnect("socket: %.100s", strerror(saved));
1432 /* Create the socket. */
1433 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1435 packet_disconnect("socket: %.100s", strerror(errno));
1437 /* Bind it to the name. */
1438 memset(&sunaddr, 0, sizeof(sunaddr));
1439 sunaddr.sun_family = AF_UNIX;
1440 strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
1441 sizeof(sunaddr.sun_path));
1443 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0)
1444 packet_disconnect("bind: %.100s", strerror(errno));
1446 /* Restore the privileged uid. */
1449 /* Start listening on the socket. */
1450 if (listen(sock, 5) < 0)
1451 packet_disconnect("listen: %.100s", strerror(errno));
1453 /* Allocate a channel for the authentication agent socket. */
1454 newch = channel_allocate(SSH_CHANNEL_AUTH_SOCKET, sock,
1455 xstrdup("auth socket"));
1456 strcpy(channels[newch].path, channel_forwarded_auth_socket_name);
1459 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
1461 void auth_input_open_request()
1463 int remch, sock, newch;
1466 /* Read the remote channel number from the message. */
1467 remch = packet_get_int();
1469 /* Get a connection to the local authentication agent (this may again get
1471 sock = ssh_get_authentication_socket();
1473 /* If we could not connect the agent, send an error message back to
1474 the server. This should never happen unless the agent
1475 dies, because authentication forwarding is only enabled if we have an
1478 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1479 packet_put_int(remch);
1484 debug("Forwarding authentication connection.");
1486 /* Dummy host name. This will be freed when the channel is freed; it will
1487 still be valid in the packet_put_string below since the channel cannot
1488 yet be freed at that point. */
1489 dummyname = xstrdup("authentication agent connection");
1491 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
1492 channels[newch].remote_id = remch;
1494 /* Send a confirmation to the remote host. */
1495 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1496 packet_put_int(remch);
1497 packet_put_int(newch);