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.
34 /* Maximum number of fake X11 displays to try. */
35 #define MAX_DISPLAYS 1000
37 /* Max len of agent socket */
38 #define MAX_SOCKET_NAME 100
40 /* Pointer to an array containing all allocated channels. The array is
41 dynamically extended as needed. */
42 static Channel *channels = NULL;
44 /* Size of the channel array. All slots of the array must always be
45 initialized (at least the type field); unused slots are marked with
46 type SSH_CHANNEL_FREE. */
47 static int channels_alloc = 0;
49 /* Maximum file descriptor value used in any of the channels. This is updated
50 in channel_allocate. */
51 static int channel_max_fd_value = 0;
53 /* Name and directory of socket for authentication agent forwarding. */
54 static char *channel_forwarded_auth_socket_name = NULL;
55 static char *channel_forwarded_auth_socket_dir = NULL;
57 /* Saved X11 authentication protocol name. */
58 char *x11_saved_proto = NULL;
60 /* Saved X11 authentication data. This is the real data. */
61 char *x11_saved_data = NULL;
62 unsigned int x11_saved_data_len = 0;
64 /* Fake X11 authentication data. This is what the server will be sending
65 us; we should replace any occurrences of this by the real data. */
66 char *x11_fake_data = NULL;
67 unsigned int x11_fake_data_len;
69 /* Data structure for storing which hosts are permitted for forward requests.
70 The local sides of any remote forwards are stored in this array to prevent
71 a corrupt remote server from accessing arbitrary TCP/IP ports on our
72 local network (which might be behind a firewall). */
75 char *host; /* Host name. */
76 int port; /* Port number. */
79 /* List of all permitted host/port pairs to connect. */
80 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
81 /* Number of permitted host/port pairs in the array. */
82 static int num_permitted_opens = 0;
83 /* If this is true, all opens are permitted. This is the case on the
84 server on which we have to trust the client anyway, and the user could
85 do anything after logging in anyway. */
86 static int all_opens_permitted = 0;
88 /* This is set to true if both sides support SSH_PROTOFLAG_HOST_IN_FWD_OPEN. */
89 static int have_hostname_in_open = 0;
91 /* Sets specific protocol options. */
93 void channel_set_options(int hostname_in_open)
95 have_hostname_in_open = hostname_in_open;
98 /* Permits opening to any host/port in SSH_MSG_PORT_OPEN. This is usually
99 called by the server, because the user could connect to any port anyway,
100 and the server has no way to know but to trust the client anyway. */
102 void channel_permit_all_opens()
104 all_opens_permitted = 1;
107 /* Allocate a new channel object and set its type and socket.
108 This will cause remote_name to be freed. */
110 int channel_allocate(int type, int sock, char *remote_name)
115 /* Update the maximum file descriptor value. */
116 if (sock > channel_max_fd_value)
117 channel_max_fd_value = sock;
119 /* Do initial allocation if this is the first call. */
120 if (channels_alloc == 0)
123 channels = xmalloc(channels_alloc * sizeof(Channel));
124 for (i = 0; i < channels_alloc; i++)
125 channels[i].type = SSH_CHANNEL_FREE;
127 /* Kludge: arrange a call to channel_stop_listening if we terminate
129 fatal_add_cleanup((void (*)(void *))channel_stop_listening, NULL);
132 /* Try to find a free slot where to put the new channel. */
133 for (found = -1, i = 0; i < channels_alloc; i++)
134 if (channels[i].type == SSH_CHANNEL_FREE)
136 /* Found a free slot. */
143 /* There are no free slots. Take last+1 slot and expand the array. */
144 found = channels_alloc;
145 channels_alloc += 10;
146 debug("channel: expanding %d", channels_alloc);
147 channels = xrealloc(channels, channels_alloc * sizeof(Channel));
148 for (i = found; i < channels_alloc; i++)
149 channels[i].type = SSH_CHANNEL_FREE;
152 /* Initialize and return new channel number. */
154 buffer_init(&c->input);
155 buffer_init(&c->output);
156 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 if (channel < 0 || channel >= channels_alloc ||
171 channels[channel].type == SSH_CHANNEL_FREE)
172 packet_disconnect("channel free: bad local channel %d", channel);
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 /* Check fake data length */
314 if (x11_fake_data_len != x11_saved_data_len)
316 error("X11 fake_data_len %d != saved_data_len %d",
317 x11_fake_data_len, x11_saved_data_len);
318 ch->type = SSH_CHANNEL_OPEN;
322 /* Received authentication protocol and data match our fake data.
323 Substitute the fake data with real data. */
324 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
325 x11_saved_data, x11_saved_data_len);
327 /* Start normal processing for the channel. */
328 ch->type = SSH_CHANNEL_OPEN;
332 /* We have received an X11 connection that has bad authentication
334 log("X11 connection rejected because of wrong authentication.\r\n");
335 buffer_clear(&ch->input);
336 buffer_clear(&ch->output);
340 ch->type = SSH_CHANNEL_CLOSED;
341 packet_start(SSH_MSG_CHANNEL_CLOSE);
342 packet_put_int(ch->remote_id);
345 debug("X11 rejected %d i%d/o%d", ch->self, ch->istate, ch->ostate);
346 chan_read_failed(ch);
347 chan_write_failed(ch);
348 debug("X11 rejected %d i%d/o%d", ch->self, ch->istate, ch->ostate);
352 case SSH_CHANNEL_FREE:
359 /* After select, perform any appropriate operations for channels which
360 have events pending. */
362 void channel_after_select(fd_set *readset, fd_set *writeset)
364 struct sockaddr addr;
365 int addrlen, newsock, i, newch, len;
367 char buf[16384], *remote_hostname;
369 /* Loop over all channels... */
370 for (i = 0; i < channels_alloc; i++)
375 case SSH_CHANNEL_X11_LISTENER:
376 /* This is our fake X11 server socket. */
377 if (FD_ISSET(ch->sock, readset))
379 debug("X11 connection requested.");
380 addrlen = sizeof(addr);
381 newsock = accept(ch->sock, &addr, &addrlen);
384 error("accept: %.100s", strerror(errno));
387 remote_hostname = get_remote_hostname(newsock);
388 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
389 remote_hostname, get_peer_port(newsock));
390 xfree(remote_hostname);
391 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
393 packet_start(SSH_SMSG_X11_OPEN);
394 packet_put_int(newch);
395 if (have_hostname_in_open)
396 packet_put_string(buf, strlen(buf));
401 case SSH_CHANNEL_PORT_LISTENER:
402 /* This socket is listening for connections to a forwarded TCP/IP
404 if (FD_ISSET(ch->sock, readset))
406 debug("Connection to port %d forwarding to %.100s:%d requested.",
407 ch->listening_port, ch->path, ch->host_port);
408 addrlen = sizeof(addr);
409 newsock = accept(ch->sock, &addr, &addrlen);
412 error("accept: %.100s", strerror(errno));
415 remote_hostname = get_remote_hostname(newsock);
416 snprintf(buf, sizeof buf, "listen port %d:%.100s:%d, connect from %.200s:%d",
417 ch->listening_port, ch->path, ch->host_port,
418 remote_hostname, get_peer_port(newsock));
419 xfree(remote_hostname);
420 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
422 packet_start(SSH_MSG_PORT_OPEN);
423 packet_put_int(newch);
424 packet_put_string(ch->path, strlen(ch->path));
425 packet_put_int(ch->host_port);
426 if (have_hostname_in_open)
427 packet_put_string(buf, strlen(buf));
432 case SSH_CHANNEL_AUTH_SOCKET:
433 /* This is the authentication agent socket listening for connections
435 if (FD_ISSET(ch->sock, readset))
439 newsock = accept(ch->sock, &addr, &len);
442 error("accept from auth socket: %.100s", strerror(errno));
446 nchan = channel_allocate(SSH_CHANNEL_OPENING, newsock,
447 xstrdup("accepted auth socket"));
448 packet_start(SSH_SMSG_AGENT_OPEN);
449 packet_put_int(nchan);
454 case SSH_CHANNEL_OPEN:
455 /* This is an open two-way communication channel. It is not of
456 interest to us at this point what kind of data is being
459 /* Read available incoming data and append it to buffer;
460 shutdown socket, if read or write failes */
461 if (FD_ISSET(ch->sock, readset))
463 len = read(ch->sock, buf, sizeof(buf));
467 buffer_consume(&ch->output, buffer_len(&ch->output));
468 ch->type = SSH_CHANNEL_INPUT_DRAINING;
469 debug("Channel %d status set to input draining.", i);
471 chan_read_failed(ch);
475 buffer_append(&ch->input, buf, len);
477 /* Send buffered output data to the socket. */
478 if (FD_ISSET(ch->sock, writeset) && buffer_len(&ch->output) > 0)
480 len = write(ch->sock, buffer_ptr(&ch->output),
481 buffer_len(&ch->output));
485 buffer_consume(&ch->output, buffer_len(&ch->output));
486 debug("Channel %d status set to input draining.", i);
487 ch->type = SSH_CHANNEL_INPUT_DRAINING;
489 chan_write_failed(ch);
493 buffer_consume(&ch->output, len);
497 case SSH_CHANNEL_OUTPUT_DRAINING:
499 fatal("cannot happen: OUT_DRAIN");
500 /* Send buffered output data to the socket. */
501 if (FD_ISSET(ch->sock, writeset) && buffer_len(&ch->output) > 0)
503 len = write(ch->sock, buffer_ptr(&ch->output),
504 buffer_len(&ch->output));
506 buffer_consume(&ch->output, buffer_len(&ch->output));
508 buffer_consume(&ch->output, len);
512 case SSH_CHANNEL_X11_OPEN:
513 case SSH_CHANNEL_FREE:
520 /* If there is data to send to the connection, send some of it now. */
522 void channel_output_poll()
527 for (i = 0; i < channels_alloc; i++)
530 /* We are only interested in channels that can have buffered incoming
532 if (ch->type != SSH_CHANNEL_OPEN &&
533 ch->type != SSH_CHANNEL_INPUT_DRAINING)
536 /* Get the amount of buffered data for this channel. */
537 len = buffer_len(&ch->input);
540 /* Send some data for the other side over the secure connection. */
541 if (packet_is_interactive())
549 len = 16384; /* Keep the packets at reasonable size. */
551 packet_start(SSH_MSG_CHANNEL_DATA);
552 packet_put_int(ch->remote_id);
553 packet_put_string(buffer_ptr(&ch->input), len);
555 buffer_consume(&ch->input, len);
557 else if(ch->istate == CHAN_INPUT_WAIT_DRAIN)
560 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
561 /* input-buffer is empty and read-socket shutdown:
562 tell peer, that we will not send more data: send IEOF */
568 /* This is called when a packet of type CHANNEL_DATA has just been received.
569 The message type has already been consumed, but channel number and data
572 void channel_input_data(int payload_len)
576 unsigned int data_len;
578 /* Get the channel number and verify it. */
579 channel = packet_get_int();
580 if (channel < 0 || channel >= channels_alloc ||
581 channels[channel].type == SSH_CHANNEL_FREE)
582 packet_disconnect("Received data for nonexistent channel %d.", channel);
584 /* Ignore any data for non-open channels (might happen on close) */
585 if (channels[channel].type != SSH_CHANNEL_OPEN &&
586 channels[channel].type != SSH_CHANNEL_X11_OPEN)
590 data = packet_get_string(&data_len);
591 packet_integrity_check(payload_len, 4 + 4+data_len, SSH_MSG_CHANNEL_DATA);
592 buffer_append(&channels[channel].output, data, data_len);
596 /* Returns true if no channel has too much buffered data, and false if
597 one or more channel is overfull. */
599 int channel_not_very_much_buffered_data()
604 for (i = 0; i < channels_alloc; i++)
609 case SSH_CHANNEL_X11_LISTENER:
610 case SSH_CHANNEL_PORT_LISTENER:
611 case SSH_CHANNEL_AUTH_SOCKET:
613 case SSH_CHANNEL_OPEN:
614 if (buffer_len(&ch->input) > 32768)
616 if (buffer_len(&ch->output) > 32768)
619 case SSH_CHANNEL_INPUT_DRAINING:
620 case SSH_CHANNEL_OUTPUT_DRAINING:
621 case SSH_CHANNEL_X11_OPEN:
622 case SSH_CHANNEL_FREE:
630 /* This is called after receiving CHANNEL_CLOSE/IEOF. */
632 void channel_input_close()
636 /* Get the channel number and verify it. */
637 channel = packet_get_int();
638 if (channel < 0 || channel >= channels_alloc ||
639 channels[channel].type == SSH_CHANNEL_FREE)
640 packet_disconnect("Received data for nonexistent channel %d.", channel);
643 /* proto version 1.5 overloads CLOSE with IEOF */
644 chan_rcvd_ieof(&channels[channel]);
648 /* Send a confirmation that we have closed the channel and no more data is
650 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
651 packet_put_int(channels[channel].remote_id);
654 /* If the channel is in closed state, we have sent a close request, and
655 the other side will eventually respond with a confirmation. Thus,
656 we cannot free the channel here, because then there would be no-one to
657 receive the confirmation. The channel gets freed when the confirmation
659 if (channels[channel].type != SSH_CHANNEL_CLOSED)
661 /* Not a closed channel - mark it as draining, which will cause it to
663 buffer_consume(&channels[channel].input,
664 buffer_len(&channels[channel].input));
665 channels[channel].type = SSH_CHANNEL_OUTPUT_DRAINING;
666 /* debug("Setting status to output draining; output len = %d",
667 buffer_len(&channels[channel].output)); */
671 /* This is called after receiving CHANNEL_CLOSE_CONFIRMATION/OCLOSE. */
673 void channel_input_close_confirmation()
677 /* Get the channel number and verify it. */
678 channel = packet_get_int();
679 if (channel < 0 || channel >= channels_alloc)
680 packet_disconnect("Received close confirmation for out-of-range channel %d.",
684 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
685 chan_rcvd_oclose(&channels[channel]);
689 if (channels[channel].type != SSH_CHANNEL_CLOSED)
690 packet_disconnect("Received close confirmation for non-closed channel %d (type %d).",
691 channel, channels[channel].type);
693 /* Free the channel. */
694 channel_free(channel);
697 /* This is called after receiving CHANNEL_OPEN_CONFIRMATION. */
699 void channel_input_open_confirmation()
701 int channel, remote_channel;
703 /* Get the channel number and verify it. */
704 channel = packet_get_int();
705 if (channel < 0 || channel >= channels_alloc ||
706 channels[channel].type != SSH_CHANNEL_OPENING)
707 packet_disconnect("Received open confirmation for non-opening channel %d.",
710 /* Get remote side's id for this channel. */
711 remote_channel = packet_get_int();
713 /* Record the remote channel number and mark that the channel is now open. */
714 channels[channel].remote_id = remote_channel;
715 channels[channel].type = SSH_CHANNEL_OPEN;
718 /* This is called after receiving CHANNEL_OPEN_FAILURE from the other side. */
720 void channel_input_open_failure()
724 /* Get the channel number and verify it. */
725 channel = packet_get_int();
726 if (channel < 0 || channel >= channels_alloc ||
727 channels[channel].type != SSH_CHANNEL_OPENING)
728 packet_disconnect("Received open failure for non-opening channel %d.",
731 /* Free the channel. This will also close the socket. */
732 channel_free(channel);
735 /* Stops listening for channels, and removes any unix domain sockets that
738 void channel_stop_listening()
741 for (i = 0; i < channels_alloc; i++)
743 switch (channels[i].type)
745 case SSH_CHANNEL_AUTH_SOCKET:
746 close(channels[i].sock);
747 remove(channels[i].path);
750 case SSH_CHANNEL_PORT_LISTENER:
751 case SSH_CHANNEL_X11_LISTENER:
752 close(channels[i].sock);
761 /* Closes the sockets of all channels. This is used to close extra file
762 descriptors after a fork. */
764 void channel_close_all()
767 for (i = 0; i < channels_alloc; i++)
769 if (channels[i].type != SSH_CHANNEL_FREE)
770 close(channels[i].sock);
774 /* Returns the maximum file descriptor number used by the channels. */
778 return channel_max_fd_value;
781 /* Returns true if any channel is still open. */
783 int channel_still_open()
786 for (i = 0; i < channels_alloc; i++)
787 switch (channels[i].type)
789 case SSH_CHANNEL_FREE:
790 case SSH_CHANNEL_X11_LISTENER:
791 case SSH_CHANNEL_PORT_LISTENER:
792 case SSH_CHANNEL_CLOSED:
793 case SSH_CHANNEL_AUTH_SOCKET:
795 case SSH_CHANNEL_OPENING:
796 case SSH_CHANNEL_OPEN:
797 case SSH_CHANNEL_X11_OPEN:
799 case SSH_CHANNEL_INPUT_DRAINING:
800 case SSH_CHANNEL_OUTPUT_DRAINING:
802 fatal("cannot happen: OUT_DRAIN");
805 fatal("channel_still_open: bad channel type %d", channels[i].type);
811 /* Returns a message describing the currently open forwarded
812 connections, suitable for sending to the client. The message
813 contains crlf pairs for newlines. */
815 char *channel_open_message()
821 buffer_init(&buffer);
822 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
823 buffer_append(&buffer, buf, strlen(buf));
824 for (i = 0; i < channels_alloc; i++){
825 Channel *c=&channels[i];
828 case SSH_CHANNEL_FREE:
829 case SSH_CHANNEL_X11_LISTENER:
830 case SSH_CHANNEL_PORT_LISTENER:
831 case SSH_CHANNEL_CLOSED:
832 case SSH_CHANNEL_AUTH_SOCKET:
834 case SSH_CHANNEL_OPENING:
835 case SSH_CHANNEL_OPEN:
836 case SSH_CHANNEL_X11_OPEN:
837 case SSH_CHANNEL_INPUT_DRAINING:
838 case SSH_CHANNEL_OUTPUT_DRAINING:
839 snprintf(buf, sizeof buf, " #%d %.300s (t%d r%d i%d o%d)\r\n",
840 c->self,c->remote_name,
841 c->type,c->remote_id, c->istate,c->ostate);
842 buffer_append(&buffer, buf, strlen(buf));
845 fatal("channel_still_open: bad channel type %d", c->type);
849 buffer_append(&buffer, "\0", 1);
850 cp = xstrdup(buffer_ptr(&buffer));
851 buffer_free(&buffer);
855 /* Initiate forwarding of connections to local port "port" through the secure
856 channel to host:port from remote side. */
858 void channel_request_local_forwarding(int port, const char *host,
862 struct sockaddr_in sin;
863 extern Options options;
865 if (strlen(host) > sizeof(channels[0].path) - 1)
866 packet_disconnect("Forward host name too long.");
868 /* Create a port to listen for the host. */
869 sock = socket(AF_INET, SOCK_STREAM, 0);
871 packet_disconnect("socket: %.100s", strerror(errno));
873 /* Initialize socket address. */
874 memset(&sin, 0, sizeof(sin));
875 sin.sin_family = AF_INET;
876 if (options.gateway_ports == 1)
877 sin.sin_addr.s_addr = htonl(INADDR_ANY);
879 sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
880 sin.sin_port = htons(port);
882 /* Bind the socket to the address. */
883 if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
884 packet_disconnect("bind: %.100s", strerror(errno));
886 /* Start listening for connections on the socket. */
887 if (listen(sock, 5) < 0)
888 packet_disconnect("listen: %.100s", strerror(errno));
890 /* Allocate a channel number for the socket. */
891 ch = channel_allocate(SSH_CHANNEL_PORT_LISTENER, sock,
892 xstrdup("port listener"));
893 strcpy(channels[ch].path, host); /* note: host name stored here */
894 channels[ch].host_port = host_port; /* port on host to connect to */
895 channels[ch].listening_port = port; /* port being listened */
898 /* Initiate forwarding of connections to port "port" on remote host through
899 the secure channel to host:port from local side. */
901 void channel_request_remote_forwarding(int port, const char *host,
905 /* Record locally that connection to this host/port is permitted. */
906 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
907 fatal("channel_request_remote_forwarding: too many forwards");
908 permitted_opens[num_permitted_opens].host = xstrdup(host);
909 permitted_opens[num_permitted_opens].port = remote_port;
910 num_permitted_opens++;
912 /* Send the forward request to the remote side. */
913 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
914 packet_put_int(port);
915 packet_put_string(host, strlen(host));
916 packet_put_int(remote_port);
920 /* Wait for response from the remote side. It will send a disconnect
921 message on failure, and we will never see it here. */
922 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
925 /* This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
926 listening for the port, and sends back a success reply (or disconnect
927 message if there was an error). This never returns if there was an
930 void channel_input_port_forward_request(int is_root)
935 /* Get arguments from the packet. */
936 port = packet_get_int();
937 hostname = packet_get_string(NULL);
938 host_port = packet_get_int();
940 /* Port numbers are 16 bit quantities. */
941 if ((port & 0xffff) != port)
942 packet_disconnect("Requested forwarding of nonexistent port %d.", port);
944 /* Check that an unprivileged user is not trying to forward a privileged
946 if (port < IPPORT_RESERVED && !is_root)
947 packet_disconnect("Requested forwarding of port %d but user is not root.",
950 /* Initiate forwarding. */
951 channel_request_local_forwarding(port, hostname, host_port);
953 /* Free the argument string. */
957 /* This is called after receiving PORT_OPEN message. This attempts to connect
958 to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION or
959 CHANNEL_OPEN_FAILURE. */
961 void channel_input_port_open(int payload_len)
963 int remote_channel, sock, newch, host_port, i;
964 struct sockaddr_in sin;
965 char *host, *originator_string;
967 int host_len, originator_len;
969 /* Get remote channel number. */
970 remote_channel = packet_get_int();
972 /* Get host name to connect to. */
973 host = packet_get_string(&host_len);
975 /* Get port to connect to. */
976 host_port = packet_get_int();
978 /* Get remote originator name. */
979 if (have_hostname_in_open)
980 originator_string = packet_get_string(&originator_len);
982 originator_string = xstrdup("unknown (remote did not supply name)");
984 packet_integrity_check(payload_len,
985 4 + 4 + host_len + 4 + 4 + originator_len,
988 /* Check if opening that port is permitted. */
989 if (!all_opens_permitted)
991 /* Go trough all permitted ports. */
992 for (i = 0; i < num_permitted_opens; i++)
993 if (permitted_opens[i].port == host_port &&
994 strcmp(permitted_opens[i].host, host) == 0)
997 /* Check if we found the requested port among those permitted. */
998 if (i >= num_permitted_opens)
1000 /* The port is not permitted. */
1001 log("Received request to connect to %.100s:%d, but the request was denied.",
1003 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1004 packet_put_int(remote_channel);
1009 memset(&sin, 0, sizeof(sin));
1010 sin.sin_addr.s_addr = inet_addr(host);
1011 if ((sin.sin_addr.s_addr & 0xffffffff) != 0xffffffff)
1013 /* It was a valid numeric host address. */
1014 sin.sin_family = AF_INET;
1018 /* Look up the host address from the name servers. */
1019 hp = gethostbyname(host);
1022 error("%.100s: unknown host.", host);
1025 if (!hp->h_addr_list[0])
1027 error("%.100s: host has no IP address.", host);
1030 sin.sin_family = hp->h_addrtype;
1031 memcpy(&sin.sin_addr, hp->h_addr_list[0],
1032 sizeof(sin.sin_addr));
1034 sin.sin_port = htons(host_port);
1036 /* Create the socket. */
1037 sock = socket(sin.sin_family, SOCK_STREAM, 0);
1040 error("socket: %.100s", strerror(errno));
1044 /* Connect to the host/port. */
1045 if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1047 error("connect %.100s:%d: %.100s", host, host_port,
1053 /* Successful connection. */
1055 /* Allocate a channel for this connection. */
1056 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, originator_string);
1057 channels[newch].remote_id = remote_channel;
1059 /* Send a confirmation to the remote host. */
1060 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1061 packet_put_int(remote_channel);
1062 packet_put_int(newch);
1065 /* Free the argument string. */
1071 /* Free the argument string. */
1074 /* Send refusal to the remote host. */
1075 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1076 packet_put_int(remote_channel);
1080 /* Creates an internet domain socket for listening for X11 connections.
1081 Returns a suitable value for the DISPLAY variable, or NULL if an error
1084 char *x11_create_display_inet(int screen_number)
1086 extern ServerOptions options;
1087 int display_number, port, sock;
1088 struct sockaddr_in sin;
1090 char hostname[MAXHOSTNAMELEN];
1092 for (display_number = options.x11_display_offset; display_number < MAX_DISPLAYS; display_number++)
1094 port = 6000 + display_number;
1095 memset(&sin, 0, sizeof(sin));
1096 sin.sin_family = AF_INET;
1097 sin.sin_addr.s_addr = htonl(INADDR_ANY);
1098 sin.sin_port = htons(port);
1100 sock = socket(AF_INET, SOCK_STREAM, 0);
1103 error("socket: %.100s", strerror(errno));
1107 if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1109 debug("bind port %d: %.100s", port, strerror(errno));
1110 shutdown(sock, SHUT_RDWR);
1116 if (display_number >= MAX_DISPLAYS)
1118 error("Failed to allocate internet-domain X11 display socket.");
1122 /* Start listening for connections on the socket. */
1123 if (listen(sock, 5) < 0)
1125 error("listen: %.100s", strerror(errno));
1126 shutdown(sock, SHUT_RDWR);
1131 /* Set up a suitable value for the DISPLAY variable. */
1132 if (gethostname(hostname, sizeof(hostname)) < 0)
1133 fatal("gethostname: %.100s", strerror(errno));
1134 snprintf(buf, sizeof buf, "%.400s:%d.%d", hostname,
1135 display_number, screen_number);
1137 /* Allocate a channel for the socket. */
1138 (void)channel_allocate(SSH_CHANNEL_X11_LISTENER, sock,
1139 xstrdup("X11 inet listener"));
1141 /* Return a suitable value for the DISPLAY environment variable. */
1142 return xstrdup(buf);
1146 #define X_UNIX_PATH "/tmp/.X11-unix/X"
1151 connect_local_xsocket(unsigned dnr)
1153 static const char *const x_sockets[] = {
1155 "/var/X/.X11-unix/X" "%u",
1156 "/usr/spool/sockets/X11/" "%u",
1160 struct sockaddr_un addr;
1161 const char *const *path;
1163 for (path = x_sockets; *path; ++path)
1165 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1167 error("socket: %.100s", strerror(errno));
1168 memset(&addr, 0, sizeof(addr));
1169 addr.sun_family = AF_UNIX;
1170 snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
1171 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
1175 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
1180 /* This is called when SSH_SMSG_X11_OPEN is received. The packet contains
1181 the remote channel number. We should do whatever we want, and respond
1182 with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE. */
1184 void x11_input_open(int payload_len)
1186 int remote_channel, display_number, sock, newch;
1187 const char *display;
1188 struct sockaddr_in sin;
1189 char buf[1024], *cp, *remote_host;
1193 /* Get remote channel number. */
1194 remote_channel = packet_get_int();
1196 /* Get remote originator name. */
1197 if (have_hostname_in_open)
1198 remote_host = packet_get_string(&remote_len);
1200 remote_host = xstrdup("unknown (remote did not supply name)");
1202 debug("Received X11 open request.");
1203 packet_integrity_check(payload_len, 4 + 4+remote_len, SSH_SMSG_X11_OPEN);
1205 /* Try to open a socket for the local X server. */
1206 display = getenv("DISPLAY");
1209 error("DISPLAY not set.");
1213 /* Now we decode the value of the DISPLAY variable and make a connection
1214 to the real X server. */
1216 /* Check if it is a unix domain socket. Unix domain displays are in one
1217 of the following formats: unix:d[.s], :d[.s], ::d[.s] */
1218 if (strncmp(display, "unix:", 5) == 0 ||
1221 /* Connect to the unix domain socket. */
1222 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1)
1224 error("Could not parse display number from DISPLAY: %.100s",
1228 /* Create a socket. */
1229 sock = connect_local_xsocket(display_number);
1233 /* OK, we now have a connection to the display. */
1237 /* Connect to an inet socket. The DISPLAY value is supposedly
1238 hostname:d[.s], where hostname may also be numeric IP address. */
1239 strncpy(buf, display, sizeof(buf));
1240 buf[sizeof(buf) - 1] = 0;
1241 cp = strchr(buf, ':');
1244 error("Could not find ':' in DISPLAY: %.100s", display);
1248 /* buf now contains the host name. But first we parse the display number. */
1249 if (sscanf(cp + 1, "%d", &display_number) != 1)
1251 error("Could not parse display number from DISPLAY: %.100s",
1256 /* Try to parse the host name as a numeric IP address. */
1257 memset(&sin, 0, sizeof(sin));
1258 sin.sin_addr.s_addr = inet_addr(buf);
1259 if ((sin.sin_addr.s_addr & 0xffffffff) != 0xffffffff)
1261 /* It was a valid numeric host address. */
1262 sin.sin_family = AF_INET;
1266 /* Not a numeric IP address. */
1267 /* Look up the host address from the name servers. */
1268 hp = gethostbyname(buf);
1271 error("%.100s: unknown host.", buf);
1274 if (!hp->h_addr_list[0])
1276 error("%.100s: host has no IP address.", buf);
1279 sin.sin_family = hp->h_addrtype;
1280 memcpy(&sin.sin_addr, hp->h_addr_list[0],
1281 sizeof(sin.sin_addr));
1283 /* Set port number. */
1284 sin.sin_port = htons(6000 + display_number);
1286 /* Create a socket. */
1287 sock = socket(sin.sin_family, SOCK_STREAM, 0);
1290 error("socket: %.100s", strerror(errno));
1293 /* Connect it to the display. */
1294 if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1296 error("connect %.100s:%d: %.100s", buf, 6000 + display_number,
1303 /* We have successfully obtained a connection to the real X display. */
1305 /* Allocate a channel for this connection. */
1306 if (x11_saved_proto == NULL)
1307 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, remote_host);
1309 newch = channel_allocate(SSH_CHANNEL_X11_OPEN, sock, remote_host);
1310 channels[newch].remote_id = remote_channel;
1312 /* Send a confirmation to the remote host. */
1313 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1314 packet_put_int(remote_channel);
1315 packet_put_int(newch);
1321 /* Send refusal to the remote host. */
1322 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1323 packet_put_int(remote_channel);
1327 /* Requests forwarding of X11 connections, generates fake authentication
1328 data, and enables authentication spoofing. */
1330 void x11_request_forwarding_with_spoofing(const char *proto, const char *data)
1332 unsigned int data_len = (unsigned int)strlen(data) / 2;
1333 unsigned int i, value;
1339 cp = getenv("DISPLAY");
1341 cp = strchr(cp, ':');
1343 cp = strchr(cp, '.');
1345 screen_number = atoi(cp + 1);
1349 /* Save protocol name. */
1350 x11_saved_proto = xstrdup(proto);
1352 /* Extract real authentication data and generate fake data of the same
1354 x11_saved_data = xmalloc(data_len);
1355 x11_fake_data = xmalloc(data_len);
1356 for (i = 0; i < data_len; i++)
1358 if (sscanf(data + 2 * i, "%2x", &value) != 1)
1359 fatal("x11_request_forwarding: bad authentication data: %.100s", data);
1361 rand = arc4random();
1362 x11_saved_data[i] = value;
1363 x11_fake_data[i] = rand & 0xff;
1366 x11_saved_data_len = data_len;
1367 x11_fake_data_len = data_len;
1369 /* Convert the fake data into hex. */
1370 new_data = xmalloc(2 * data_len + 1);
1371 for (i = 0; i < data_len; i++)
1372 sprintf(new_data + 2 * i, "%02x", (unsigned char)x11_fake_data[i]);
1374 /* Send the request packet. */
1375 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
1376 packet_put_string(proto, strlen(proto));
1377 packet_put_string(new_data, strlen(new_data));
1378 packet_put_int(screen_number);
1380 packet_write_wait();
1384 /* Sends a message to the server to request authentication fd forwarding. */
1386 void auth_request_forwarding()
1388 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
1390 packet_write_wait();
1393 /* Returns the name of the forwarded authentication socket. Returns NULL
1394 if there is no forwarded authentication socket. The returned value
1395 points to a static buffer. */
1397 char *auth_get_socket_name()
1399 return channel_forwarded_auth_socket_name;
1402 /* removes the agent forwarding socket */
1404 void cleanup_socket(void) {
1405 remove(channel_forwarded_auth_socket_name);
1406 rmdir(channel_forwarded_auth_socket_dir);
1409 /* This if called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
1410 This starts forwarding authentication requests. */
1412 void auth_input_request_forwarding(struct passwd *pw)
1415 struct sockaddr_un sunaddr;
1417 if (auth_get_socket_name() != NULL)
1418 fatal("Protocol error: authentication forwarding requested twice.");
1420 /* Temporarily drop privileged uid for mkdir/bind. */
1421 temporarily_use_uid(pw->pw_uid);
1423 /* Allocate a buffer for the socket name, and format the name. */
1424 channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
1425 channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
1426 strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
1428 /* Create private directory for socket */
1429 if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL)
1430 packet_disconnect("mkdtemp: %.100s", strerror(errno));
1431 snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME,
1432 "%s/agent.%d", channel_forwarded_auth_socket_dir, (int)getpid());
1434 if (atexit(cleanup_socket) < 0) {
1437 packet_disconnect("socket: %.100s", strerror(saved));
1440 /* Create the socket. */
1441 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1443 packet_disconnect("socket: %.100s", strerror(errno));
1445 /* Bind it to the name. */
1446 memset(&sunaddr, 0, sizeof(sunaddr));
1447 sunaddr.sun_family = AF_UNIX;
1448 strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
1449 sizeof(sunaddr.sun_path));
1451 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0)
1452 packet_disconnect("bind: %.100s", strerror(errno));
1454 /* Restore the privileged uid. */
1457 /* Start listening on the socket. */
1458 if (listen(sock, 5) < 0)
1459 packet_disconnect("listen: %.100s", strerror(errno));
1461 /* Allocate a channel for the authentication agent socket. */
1462 newch = channel_allocate(SSH_CHANNEL_AUTH_SOCKET, sock,
1463 xstrdup("auth socket"));
1464 strcpy(channels[newch].path, channel_forwarded_auth_socket_name);
1467 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
1469 void auth_input_open_request()
1471 int remch, sock, newch;
1474 /* Read the remote channel number from the message. */
1475 remch = packet_get_int();
1477 /* Get a connection to the local authentication agent (this may again get
1479 sock = ssh_get_authentication_socket();
1481 /* If we could not connect the agent, send an error message back to
1482 the server. This should never happen unless the agent
1483 dies, because authentication forwarding is only enabled if we have an
1486 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1487 packet_put_int(remch);
1492 debug("Forwarding authentication connection.");
1494 /* Dummy host name. This will be freed when the channel is freed; it will
1495 still be valid in the packet_put_string below since the channel cannot
1496 yet be freed at that point. */
1497 dummyname = xstrdup("authentication agent connection");
1499 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
1500 channels[newch].remote_id = remch;
1502 /* Send a confirmation to the remote host. */
1503 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1504 packet_put_int(remch);
1505 packet_put_int(newch);