]> andersk Git - openssh.git/blob - channels.c
- Add tests for RAND_add function when searching for OpenSSL
[openssh.git] / channels.c
1 /*
2  * 
3  * channels.c
4  * 
5  * Author: Tatu Ylonen <ylo@cs.hut.fi>
6  * 
7  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
8  *                    All rights reserved
9  * 
10  * Created: Fri Mar 24 16:35:24 1995 ylo
11  * 
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.
15  * 
16  */
17
18 #include "includes.h"
19 RCSID("$Id$");
20
21 #include "ssh.h"
22 #include "packet.h"
23 #include "xmalloc.h"
24 #include "buffer.h"
25 #include "authfd.h"
26 #include "uidswap.h"
27 #include "readconf.h"
28 #include "servconf.h"
29
30 #include "channels.h"
31 #include "nchan.h"
32 #include "compat.h"
33
34 /* Maximum number of fake X11 displays to try. */
35 #define MAX_DISPLAYS  1000
36
37 /* Max len of agent socket */
38 #define MAX_SOCKET_NAME 100
39
40 /* default buffer for tcp-fwd-channel */
41 #define CHAN_WINDOW_DEFAULT      (8*1024)
42 #define CHAN_PACKET_DEFAULT      (CHAN_WINDOW_DEFAULT/2)
43
44 /*
45  * Pointer to an array containing all allocated channels.  The array is
46  * dynamically extended as needed.
47  */
48 static Channel *channels = NULL;
49
50 /*
51  * Size of the channel array.  All slots of the array must always be
52  * initialized (at least the type field); unused slots are marked with type
53  * SSH_CHANNEL_FREE.
54  */
55 static int channels_alloc = 0;
56
57 /*
58  * Maximum file descriptor value used in any of the channels.  This is
59  * updated in channel_allocate.
60  */
61 static int channel_max_fd_value = 0;
62
63 /* Name and directory of socket for authentication agent forwarding. */
64 static char *channel_forwarded_auth_socket_name = NULL;
65 static char *channel_forwarded_auth_socket_dir = NULL;
66
67 /* Saved X11 authentication protocol name. */
68 char *x11_saved_proto = NULL;
69
70 /* Saved X11 authentication data.  This is the real data. */
71 char *x11_saved_data = NULL;
72 unsigned int x11_saved_data_len = 0;
73
74 /*
75  * Fake X11 authentication data.  This is what the server will be sending us;
76  * we should replace any occurrences of this by the real data.
77  */
78 char *x11_fake_data = NULL;
79 unsigned int x11_fake_data_len;
80
81 /*
82  * Data structure for storing which hosts are permitted for forward requests.
83  * The local sides of any remote forwards are stored in this array to prevent
84  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
85  * network (which might be behind a firewall).
86  */
87 typedef struct {
88         char *host_to_connect;          /* Connect to 'host'. */
89         u_short port_to_connect;        /* Connect to 'port'. */
90         u_short listen_port;            /* Remote side should listen port number. */
91 } ForwardPermission;
92
93 /* List of all permitted host/port pairs to connect. */
94 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
95 /* Number of permitted host/port pairs in the array. */
96 static int num_permitted_opens = 0;
97 /*
98  * If this is true, all opens are permitted.  This is the case on the server
99  * on which we have to trust the client anyway, and the user could do
100  * anything after logging in anyway.
101  */
102 static int all_opens_permitted = 0;
103
104 /* This is set to true if both sides support SSH_PROTOFLAG_HOST_IN_FWD_OPEN. */
105 static int have_hostname_in_open = 0;
106
107 /* Sets specific protocol options. */
108
109 void 
110 channel_set_options(int hostname_in_open)
111 {
112         have_hostname_in_open = hostname_in_open;
113 }
114
115 /*
116  * Permits opening to any host/port in SSH_MSG_PORT_OPEN.  This is usually
117  * called by the server, because the user could connect to any port anyway,
118  * and the server has no way to know but to trust the client anyway.
119  */
120
121 void 
122 channel_permit_all_opens()
123 {
124         all_opens_permitted = 1;
125 }
126
127 /* lookup channel by id */
128
129 Channel *
130 channel_lookup(int id)
131 {
132         Channel *c;
133         if (id < 0 && id > channels_alloc) {
134                 log("channel_lookup: %d: bad id", id);
135                 return NULL;
136         }
137         c = &channels[id];
138         if (c->type == SSH_CHANNEL_FREE) {
139                 log("channel_lookup: %d: bad id: channel free", id);
140                 return NULL;
141         }
142         return c;
143 }
144
145 /*
146  * Allocate a new channel object and set its type and socket. This will cause
147  * remote_name to be freed.
148  */
149
150 int 
151 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
152     int window, int maxpack, int extended_usage, char *remote_name)
153 {
154         int i, found;
155         Channel *c;
156
157         /* Update the maximum file descriptor value. */
158         if (rfd > channel_max_fd_value)
159                 channel_max_fd_value = rfd;
160         if (wfd > channel_max_fd_value)
161                 channel_max_fd_value = wfd;
162         if (efd > channel_max_fd_value)
163                 channel_max_fd_value = efd;
164         /* XXX set close-on-exec -markus */
165
166         /* Do initial allocation if this is the first call. */
167         if (channels_alloc == 0) {
168                 channels_alloc = 10;
169                 channels = xmalloc(channels_alloc * sizeof(Channel));
170                 for (i = 0; i < channels_alloc; i++)
171                         channels[i].type = SSH_CHANNEL_FREE;
172                 /*
173                  * Kludge: arrange a call to channel_stop_listening if we
174                  * terminate with fatal().
175                  */
176                 fatal_add_cleanup((void (*) (void *)) channel_stop_listening, NULL);
177         }
178         /* Try to find a free slot where to put the new channel. */
179         for (found = -1, i = 0; i < channels_alloc; i++)
180                 if (channels[i].type == SSH_CHANNEL_FREE) {
181                         /* Found a free slot. */
182                         found = i;
183                         break;
184                 }
185         if (found == -1) {
186                 /* There are no free slots.  Take last+1 slot and expand the array.  */
187                 found = channels_alloc;
188                 channels_alloc += 10;
189                 debug("channel: expanding %d", channels_alloc);
190                 channels = xrealloc(channels, channels_alloc * sizeof(Channel));
191                 for (i = found; i < channels_alloc; i++)
192                         channels[i].type = SSH_CHANNEL_FREE;
193         }
194         /* Initialize and return new channel number. */
195         c = &channels[found];
196         buffer_init(&c->input);
197         buffer_init(&c->output);
198         buffer_init(&c->extended);
199         chan_init_iostates(c);
200         c->self = found;
201         c->type = type;
202         c->ctype = ctype;
203         c->local_window = window;
204         c->local_window_max = window;
205         c->local_consumed = 0;
206         c->local_maxpacket = maxpack;
207         c->remote_window = 0;
208         c->remote_maxpacket = 0;
209         c->rfd = rfd;
210         c->wfd = wfd;
211         c->sock = (rfd == wfd) ? rfd : -1;
212         c->efd = efd;
213         c->extended_usage = extended_usage;
214         c->remote_id = -1;
215         c->remote_name = remote_name;
216         c->remote_window = 0;
217         c->remote_maxpacket = 0;
218         c->cb_fn = NULL;
219         c->cb_arg = NULL;
220         c->cb_event = 0;
221         c->dettach_user = NULL;
222         debug("channel %d: new [%s]", found, remote_name);
223         return found;
224 }
225 int 
226 channel_allocate(int type, int sock, char *remote_name)
227 {
228         return channel_new("", type, sock, sock, -1, 0, 0, 0, remote_name);
229 }
230
231 /* Free the channel and close its socket. */
232
233 void 
234 channel_free(int id)
235 {
236         Channel *c = channel_lookup(id);
237         if (c == NULL)
238                 packet_disconnect("channel free: bad local channel %d", id);
239         debug("channel_free: channel %d: status: %s", id, channel_open_message());
240         if (c->sock != -1) {
241                 shutdown(c->sock, SHUT_RDWR);
242                 close(c->sock);
243         }
244         buffer_free(&c->input);
245         buffer_free(&c->output);
246         buffer_free(&c->extended);
247         c->type = SSH_CHANNEL_FREE;
248         if (c->remote_name) {
249                 xfree(c->remote_name);
250                 c->remote_name = NULL;
251         }
252 }
253
254 /*
255  * 'channel_pre*' are called just before select() to add any bits relevant to
256  * channels in the select bitmasks.
257  */
258 /*
259  * 'channel_post*': perform any appropriate operations for channels which
260  * have events pending.
261  */
262 typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
263 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
264 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
265
266 void
267 channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
268 {
269         FD_SET(c->sock, readset);
270 }
271
272 void
273 channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
274 {
275         if (buffer_len(&c->input) < packet_get_maxsize())
276                 FD_SET(c->sock, readset);
277         if (buffer_len(&c->output) > 0)
278                 FD_SET(c->sock, writeset);
279 }
280
281 void
282 channel_pre_open_15(Channel *c, fd_set * readset, fd_set * writeset)
283 {
284         /* test whether sockets are 'alive' for read/write */
285         if (c->istate == CHAN_INPUT_OPEN)
286                 if (buffer_len(&c->input) < packet_get_maxsize())
287                         FD_SET(c->sock, readset);
288         if (c->ostate == CHAN_OUTPUT_OPEN ||
289             c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
290                 if (buffer_len(&c->output) > 0) {
291                         FD_SET(c->sock, writeset);
292                 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
293                         chan_obuf_empty(c);
294                 }
295         }
296 }
297
298 void
299 channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
300 {
301         if (buffer_len(&c->input) == 0) {
302                 packet_start(SSH_MSG_CHANNEL_CLOSE);
303                 packet_put_int(c->remote_id);
304                 packet_send();
305                 c->type = SSH_CHANNEL_CLOSED;
306                 debug("Closing channel %d after input drain.", c->self);
307         }
308 }
309
310 void
311 channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
312 {
313         if (buffer_len(&c->output) == 0)
314                 channel_free(c->self);
315         else 
316                 FD_SET(c->sock, writeset);
317 }
318
319 /*
320  * This is a special state for X11 authentication spoofing.  An opened X11
321  * connection (when authentication spoofing is being done) remains in this
322  * state until the first packet has been completely read.  The authentication
323  * data in that packet is then substituted by the real data if it matches the
324  * fake data, and the channel is put into normal mode.
325  */
326 int
327 x11_open_helper(Channel *c)
328 {
329         unsigned char *ucp;
330         unsigned int proto_len, data_len;
331
332         /* Check if the fixed size part of the packet is in buffer. */
333         if (buffer_len(&c->output) < 12)
334                 return 0;
335
336         /* Parse the lengths of variable-length fields. */
337         ucp = (unsigned char *) buffer_ptr(&c->output);
338         if (ucp[0] == 0x42) {   /* Byte order MSB first. */
339                 proto_len = 256 * ucp[6] + ucp[7];
340                 data_len = 256 * ucp[8] + ucp[9];
341         } else if (ucp[0] == 0x6c) {    /* Byte order LSB first. */
342                 proto_len = ucp[6] + 256 * ucp[7];
343                 data_len = ucp[8] + 256 * ucp[9];
344         } else {
345                 debug("Initial X11 packet contains bad byte order byte: 0x%x",
346                       ucp[0]);
347                 return -1;
348         }
349
350         /* Check if the whole packet is in buffer. */
351         if (buffer_len(&c->output) <
352             12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
353                 return 0;
354
355         /* Check if authentication protocol matches. */
356         if (proto_len != strlen(x11_saved_proto) ||
357             memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
358                 debug("X11 connection uses different authentication protocol.");
359                 return -1;
360         }
361         /* Check if authentication data matches our fake data. */
362         if (data_len != x11_fake_data_len ||
363             memcmp(ucp + 12 + ((proto_len + 3) & ~3),
364                 x11_fake_data, x11_fake_data_len) != 0) {
365                 debug("X11 auth data does not match fake data.");
366                 return -1;
367         }
368         /* Check fake data length */
369         if (x11_fake_data_len != x11_saved_data_len) {
370                 error("X11 fake_data_len %d != saved_data_len %d",
371                     x11_fake_data_len, x11_saved_data_len);
372                 return -1;
373         }
374         /*
375          * Received authentication protocol and data match
376          * our fake data. Substitute the fake data with real
377          * data.
378          */
379         memcpy(ucp + 12 + ((proto_len + 3) & ~3),
380             x11_saved_data, x11_saved_data_len);
381         return 1;
382 }
383
384 void
385 channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
386 {
387         int ret = x11_open_helper(c);
388         if (ret == 1) {
389                 /* Start normal processing for the channel. */
390                 c->type = SSH_CHANNEL_OPEN;
391         } else if (ret == -1) {
392                 /*
393                  * We have received an X11 connection that has bad
394                  * authentication information.
395                  */
396                 log("X11 connection rejected because of wrong authentication.\r\n");
397                 buffer_clear(&c->input);
398                 buffer_clear(&c->output);
399                 close(c->sock);
400                 c->sock = -1;
401                 c->type = SSH_CHANNEL_CLOSED;
402                 packet_start(SSH_MSG_CHANNEL_CLOSE);
403                 packet_put_int(c->remote_id);
404                 packet_send();
405         }
406 }
407
408 void
409 channel_pre_x11_open_15(Channel *c, fd_set * readset, fd_set * writeset)
410 {
411         int ret = x11_open_helper(c);
412         if (ret == 1) {
413                 c->type = SSH_CHANNEL_OPEN;
414         } else if (ret == -1) {
415                 debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
416                 chan_read_failed(c);
417                 chan_write_failed(c);
418                 debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
419         }
420 }
421
422 /* This is our fake X11 server socket. */
423 void
424 channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
425 {
426         struct sockaddr addr;
427         int newsock, newch;
428         socklen_t addrlen;
429         char buf[16384], *remote_hostname;
430
431         if (FD_ISSET(c->sock, readset)) {
432                 debug("X11 connection requested.");
433                 addrlen = sizeof(addr);
434                 newsock = accept(c->sock, &addr, &addrlen);
435                 if (newsock < 0) {
436                         error("accept: %.100s", strerror(errno));
437                         return;
438                 }
439                 remote_hostname = get_remote_hostname(newsock);
440                 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
441                 remote_hostname, get_peer_port(newsock));
442                 xfree(remote_hostname);
443                 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
444                                          xstrdup(buf));
445                 packet_start(SSH_SMSG_X11_OPEN);
446                 packet_put_int(newch);
447                 if (have_hostname_in_open)
448                         packet_put_string(buf, strlen(buf));
449                 packet_send();
450         }
451 }
452
453 /*
454  * This socket is listening for connections to a forwarded TCP/IP port.
455  */
456 void
457 channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
458 {
459         struct sockaddr addr;
460         int newsock, newch;
461         socklen_t addrlen;
462         char buf[1024], *remote_hostname;
463         int remote_port;
464
465         if (FD_ISSET(c->sock, readset)) {
466                 debug("Connection to port %d forwarding "
467                     "to %.100s port %d requested.",
468                     c->listening_port, c->path, c->host_port);
469                 addrlen = sizeof(addr);
470                 newsock = accept(c->sock, &addr, &addrlen);
471                 if (newsock < 0) {
472                         error("accept: %.100s", strerror(errno));
473                         return;
474                 }
475                 remote_hostname = get_remote_hostname(newsock);
476                 remote_port = get_peer_port(newsock);
477                 snprintf(buf, sizeof buf,
478                     "listen port %d for %.100s port %d, "
479                     "connect from %.200s port %d",
480                     c->listening_port, c->path, c->host_port,
481                     remote_hostname, remote_port);
482                 newch = channel_new("direct-tcpip",
483                     SSH_CHANNEL_OPENING, newsock, newsock, -1,
484                     c->local_window_max, c->local_maxpacket,
485                     0, xstrdup(buf));
486
487                 packet_start(SSH_MSG_PORT_OPEN);
488                 packet_put_int(newch);
489                 packet_put_string(c->path, strlen(c->path));
490                 packet_put_int(c->host_port);
491                 if (have_hostname_in_open) {
492                         packet_put_string(buf, strlen(buf));
493                 }
494                 packet_send();
495                 xfree(remote_hostname);
496         }
497 }
498
499 /*
500  * This is the authentication agent socket listening for connections from
501  * clients.
502  */
503 void
504 channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
505 {
506         struct sockaddr addr;
507         int newsock, newch;
508         socklen_t addrlen;
509
510         if (FD_ISSET(c->sock, readset)) {
511                 addrlen = sizeof(addr);
512                 newsock = accept(c->sock, &addr, &addrlen);
513                 if (newsock < 0) {
514                         error("accept from auth socket: %.100s", strerror(errno));
515                         return;
516                 }
517                 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
518                     xstrdup("accepted auth socket"));
519                 packet_start(SSH_SMSG_AGENT_OPEN);
520                 packet_put_int(newch);
521                 packet_send();
522         }
523 }
524
525 int
526 channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
527 {
528         char buf[16*1024];
529         int len;
530
531         if (c->rfd != -1 &&
532             FD_ISSET(c->rfd, readset)) {
533                 len = read(c->rfd, buf, sizeof(buf));
534                 if (len <= 0) {
535                         debug("channel %d: read<0 rfd %d len %d",
536                             c->self, c->rfd, len);
537                         if (compat13) {
538                                 buffer_consume(&c->output, buffer_len(&c->output));
539                                 c->type = SSH_CHANNEL_INPUT_DRAINING;
540                                 debug("Channel %d status set to input draining.", c->self);
541                         } else {
542                                 chan_read_failed(c);
543                         }
544                         return -1;
545                 }
546                 buffer_append(&c->input, buf, len);
547         }
548         return 1;
549 }
550 int
551 channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
552 {
553         int len;
554
555         /* Send buffered output data to the socket. */
556         if (c->wfd != -1 &&
557             FD_ISSET(c->wfd, writeset) &&
558             buffer_len(&c->output) > 0) {
559                 len = write(c->wfd, buffer_ptr(&c->output),
560                             buffer_len(&c->output));
561                 if (len <= 0) {
562                         if (compat13) {
563                                 buffer_consume(&c->output, buffer_len(&c->output));
564                                 debug("Channel %d status set to input draining.", c->self);
565                                 c->type = SSH_CHANNEL_INPUT_DRAINING;
566                         } else {
567                                 chan_write_failed(c);
568                         }
569                         return -1;
570                 }
571                 buffer_consume(&c->output, len);
572         }
573         return 1;
574 }
575
576 void
577 channel_post_open_1(Channel *c, fd_set * readset, fd_set * writeset)
578 {
579         channel_handle_rfd(c, readset, writeset);
580         channel_handle_wfd(c, readset, writeset);
581 }
582
583 void
584 channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
585 {
586         int len;
587         /* Send buffered output data to the socket. */
588         if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
589                 len = write(c->sock, buffer_ptr(&c->output),
590                             buffer_len(&c->output));
591                 if (len <= 0)
592                         buffer_consume(&c->output, buffer_len(&c->output));
593                 else
594                         buffer_consume(&c->output, len);
595         }
596 }
597
598 void
599 channel_handler_init_13(void)
600 {
601         channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_13;
602         channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open_13;
603         channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
604         channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
605         channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
606         channel_pre[SSH_CHANNEL_INPUT_DRAINING] =       &channel_pre_input_draining;
607         channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] =      &channel_pre_output_draining;
608
609         channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_1;
610         channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
611         channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
612         channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
613         channel_post[SSH_CHANNEL_OUTPUT_DRAINING] =     &channel_post_output_drain_13;
614 }
615
616 void
617 channel_handler_init_15(void)
618 {
619         channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_15;
620         channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open_15;
621         channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
622         channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
623         channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
624
625         channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
626         channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
627         channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
628         channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_1;
629 }
630
631 void
632 channel_handler_init(void)
633 {
634         int i;
635         for(i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
636                 channel_pre[i] = NULL;
637                 channel_post[i] = NULL;
638         }
639         if (compat13)
640                 channel_handler_init_13();
641         else
642                 channel_handler_init_15();
643 }
644
645 void 
646 channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
647 {
648         static int did_init = 0;
649         int i;
650         Channel *c;
651
652         if (!did_init) {
653                 channel_handler_init();
654                 did_init = 1;
655         }
656         for (i = 0; i < channels_alloc; i++) {
657                 c = &channels[i];
658                 if (c->type == SSH_CHANNEL_FREE)
659                         continue;
660                 if (ftab[c->type] == NULL)
661                         continue;
662                 (*ftab[c->type])(c, readset, writeset);
663                 if (!compat13)
664                         chan_delete_if_full_closed(c);
665         }
666 }
667
668 void 
669 channel_prepare_select(fd_set * readset, fd_set * writeset)
670 {
671         channel_handler(channel_pre, readset, writeset);
672 }
673
674 void 
675 channel_after_select(fd_set * readset, fd_set * writeset)
676 {
677         channel_handler(channel_post, readset, writeset);
678 }
679
680 /* If there is data to send to the connection, send some of it now. */
681
682 void 
683 channel_output_poll()
684 {
685         int len, i;
686         Channel *c;
687
688         for (i = 0; i < channels_alloc; i++) {
689                 c = &channels[i];
690
691                 /* We are only interested in channels that can have buffered incoming data. */
692                 if (compat13) {
693                         if (c->type != SSH_CHANNEL_OPEN &&
694                             c->type != SSH_CHANNEL_INPUT_DRAINING)
695                                 continue;
696                 } else {
697                         if (c->type != SSH_CHANNEL_OPEN)
698                                 continue;
699                         if (c->istate != CHAN_INPUT_OPEN &&
700                             c->istate != CHAN_INPUT_WAIT_DRAIN)
701                                 continue;
702                 }
703
704                 /* Get the amount of buffered data for this channel. */
705                 len = buffer_len(&c->input);
706                 if (len > 0) {
707                         /* Send some data for the other side over the secure connection. */
708                         if (packet_is_interactive()) {
709                                 if (len > 1024)
710                                         len = 512;
711                         } else {
712                                 /* Keep the packets at reasonable size. */
713                                 if (len > packet_get_maxsize())
714                                         len = packet_get_maxsize()/2;
715                         }
716                         if (len > 0) {
717                                 packet_start(SSH_MSG_CHANNEL_DATA);
718                                 packet_put_int(c->remote_id);
719                                 packet_put_string(buffer_ptr(&c->input), len);
720                                 packet_send();
721                                 buffer_consume(&c->input, len);
722                                 c->remote_window -= len;
723 debug("channel %d: send data len %d", c->self, len);
724                         }
725                 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
726                         if (compat13)
727                                 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
728                         /*
729                          * input-buffer is empty and read-socket shutdown:
730                          * tell peer, that we will not send more data: send IEOF
731                          */
732                         chan_ibuf_empty(c);
733                 }
734         }
735 }
736
737 /*
738  * This is called when a packet of type CHANNEL_DATA has just been received.
739  * The message type has already been consumed, but channel number and data is
740  * still there.
741  */
742
743 void 
744 channel_input_data(int type, int plen)
745 {
746         int id;
747         char *data;
748         unsigned int data_len;
749         Channel *c;
750
751         /* Get the channel number and verify it. */
752         id = packet_get_int();
753         c = channel_lookup(id);
754         if (c == NULL)
755                 packet_disconnect("Received data for nonexistent channel %d.", id);
756
757         /* Ignore any data for non-open channels (might happen on close) */
758         if (c->type != SSH_CHANNEL_OPEN &&
759             c->type != SSH_CHANNEL_X11_OPEN)
760                 return;
761
762         /* same for protocol 1.5 if output end is no longer open */
763         if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
764                 return;
765
766         /* Get the data. */
767         data = packet_get_string(&data_len);
768
769         packet_integrity_check(plen, 4 + 4 + data_len, SSH_MSG_CHANNEL_DATA);
770         buffer_append(&c->output, data, data_len);
771         xfree(data);
772 }
773
774 /*
775  * Returns true if no channel has too much buffered data, and false if one or
776  * more channel is overfull.
777  */
778
779 int 
780 channel_not_very_much_buffered_data()
781 {
782         unsigned int i;
783         Channel *c;
784
785         for (i = 0; i < channels_alloc; i++) {
786                 c = &channels[i];
787                 if (c->type == SSH_CHANNEL_OPEN) {
788                         if (buffer_len(&c->input) > packet_get_maxsize()) {
789                                 debug("channel %d: big input buffer %d",
790                                     c->self, buffer_len(&c->input));
791                                 return 0;
792                         }
793                         if (buffer_len(&c->output) > packet_get_maxsize()) {
794                                 debug("channel %d: big output buffer %d",
795                                     c->self, buffer_len(&c->output));
796                                 return 0;
797                         }
798                 }
799         }
800         return 1;
801 }
802
803 void 
804 channel_input_ieof(int type, int plen)
805 {
806         int id;
807         Channel *c;
808
809         packet_integrity_check(plen, 4, type);
810
811         id = packet_get_int();
812         c = channel_lookup(id);
813         if (c == NULL)
814                 packet_disconnect("Received ieof for nonexistent channel %d.", id);
815         chan_rcvd_ieof(c);
816 }
817
818 void 
819 channel_input_close(int type, int plen)
820 {
821         int id;
822         Channel *c;
823
824         packet_integrity_check(plen, 4, type);
825
826         id = packet_get_int();
827         c = channel_lookup(id);
828         if (c == NULL)
829                 packet_disconnect("Received close for nonexistent channel %d.", id);
830
831         /*
832          * Send a confirmation that we have closed the channel and no more
833          * data is coming for it.
834          */
835         packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
836         packet_put_int(c->remote_id);
837         packet_send();
838
839         /*
840          * If the channel is in closed state, we have sent a close request,
841          * and the other side will eventually respond with a confirmation.
842          * Thus, we cannot free the channel here, because then there would be
843          * no-one to receive the confirmation.  The channel gets freed when
844          * the confirmation arrives.
845          */
846         if (c->type != SSH_CHANNEL_CLOSED) {
847                 /*
848                  * Not a closed channel - mark it as draining, which will
849                  * cause it to be freed later.
850                  */
851                 buffer_consume(&c->input, buffer_len(&c->input));
852                 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
853         }
854 }
855
856 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
857 void 
858 channel_input_oclose(int type, int plen)
859 {
860         int id = packet_get_int();
861         Channel *c = channel_lookup(id);
862         packet_integrity_check(plen, 4, type);
863         if (c == NULL)
864                 packet_disconnect("Received oclose for nonexistent channel %d.", id);
865         chan_rcvd_oclose(c);
866 }
867
868 void 
869 channel_input_close_confirmation(int type, int plen)
870 {
871         int id = packet_get_int();
872         Channel *c = channel_lookup(id);
873
874         if (c == NULL)
875                 packet_disconnect("Received close confirmation for "
876                     "out-of-range channel %d.", id);
877         if (c->type != SSH_CHANNEL_CLOSED)
878                 packet_disconnect("Received close confirmation for "
879                     "non-closed channel %d (type %d).", id, c->type);
880         channel_free(c->self);
881 }
882
883 void 
884 channel_input_open_confirmation(int type, int plen)
885 {
886         int id, remote_id;
887         Channel *c;
888
889         packet_integrity_check(plen, 4 + 4, type);
890
891         id = packet_get_int();
892         c = channel_lookup(id);
893
894         if (c==NULL || c->type != SSH_CHANNEL_OPENING)
895                 packet_disconnect("Received open confirmation for "
896                     "non-opening channel %d.", id);
897         remote_id = packet_get_int();
898         /* Record the remote channel number and mark that the channel is now open. */
899         c->remote_id = remote_id;
900         c->type = SSH_CHANNEL_OPEN;
901 }
902
903 void 
904 channel_input_open_failure(int type, int plen)
905 {
906         int id;
907         Channel *c;
908
909         packet_integrity_check(plen, 4, type);
910
911         id = packet_get_int();
912         c = channel_lookup(id);
913
914         if (c==NULL || c->type != SSH_CHANNEL_OPENING)
915                 packet_disconnect("Received open failure for "
916                     "non-opening channel %d.", id);
917
918         /* Free the channel.  This will also close the socket. */
919         channel_free(id);
920 }
921
922 /*
923  * Stops listening for channels, and removes any unix domain sockets that we
924  * might have.
925  */
926
927 void 
928 channel_stop_listening()
929 {
930         int i;
931         for (i = 0; i < channels_alloc; i++) {
932                 switch (channels[i].type) {
933                 case SSH_CHANNEL_AUTH_SOCKET:
934                         close(channels[i].sock);
935                         remove(channels[i].path);
936                         channel_free(i);
937                         break;
938                 case SSH_CHANNEL_PORT_LISTENER:
939                 case SSH_CHANNEL_X11_LISTENER:
940                         close(channels[i].sock);
941                         channel_free(i);
942                         break;
943                 default:
944                         break;
945                 }
946         }
947 }
948
949 /*
950  * Closes the sockets of all channels.  This is used to close extra file
951  * descriptors after a fork.
952  */
953
954 void 
955 channel_close_all()
956 {
957         int i;
958         for (i = 0; i < channels_alloc; i++) {
959                 if (channels[i].type != SSH_CHANNEL_FREE)
960                         close(channels[i].sock);
961         }
962 }
963
964 /* Returns the maximum file descriptor number used by the channels. */
965
966 int 
967 channel_max_fd()
968 {
969         return channel_max_fd_value;
970 }
971
972 /* Returns true if any channel is still open. */
973
974 int 
975 channel_still_open()
976 {
977         unsigned int i;
978         for (i = 0; i < channels_alloc; i++)
979                 switch (channels[i].type) {
980                 case SSH_CHANNEL_FREE:
981                 case SSH_CHANNEL_X11_LISTENER:
982                 case SSH_CHANNEL_PORT_LISTENER:
983                 case SSH_CHANNEL_CLOSED:
984                 case SSH_CHANNEL_AUTH_SOCKET:
985                         continue;
986                 case SSH_CHANNEL_OPENING:
987                 case SSH_CHANNEL_OPEN:
988                 case SSH_CHANNEL_X11_OPEN:
989                         return 1;
990                 case SSH_CHANNEL_INPUT_DRAINING:
991                 case SSH_CHANNEL_OUTPUT_DRAINING:
992                         if (!compat13)
993                                 fatal("cannot happen: OUT_DRAIN");
994                         return 1;
995                 default:
996                         fatal("channel_still_open: bad channel type %d", channels[i].type);
997                         /* NOTREACHED */
998                 }
999         return 0;
1000 }
1001
1002 /*
1003  * Returns a message describing the currently open forwarded connections,
1004  * suitable for sending to the client.  The message contains crlf pairs for
1005  * newlines.
1006  */
1007
1008 char *
1009 channel_open_message()
1010 {
1011         Buffer buffer;
1012         int i;
1013         char buf[512], *cp;
1014
1015         buffer_init(&buffer);
1016         snprintf(buf, sizeof buf, "The following connections are open:\r\n");
1017         buffer_append(&buffer, buf, strlen(buf));
1018         for (i = 0; i < channels_alloc; i++) {
1019                 Channel *c = &channels[i];
1020                 switch (c->type) {
1021                 case SSH_CHANNEL_FREE:
1022                 case SSH_CHANNEL_X11_LISTENER:
1023                 case SSH_CHANNEL_PORT_LISTENER:
1024                 case SSH_CHANNEL_CLOSED:
1025                 case SSH_CHANNEL_AUTH_SOCKET:
1026                         continue;
1027                 case SSH_CHANNEL_OPENING:
1028                 case SSH_CHANNEL_OPEN:
1029                 case SSH_CHANNEL_X11_OPEN:
1030                 case SSH_CHANNEL_INPUT_DRAINING:
1031                 case SSH_CHANNEL_OUTPUT_DRAINING:
1032                         snprintf(buf, sizeof buf, "  #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
1033                             c->self, c->remote_name,
1034                             c->type, c->remote_id,
1035                             c->istate, buffer_len(&c->input),
1036                             c->ostate, buffer_len(&c->output),
1037                             c->rfd, c->wfd);
1038                         buffer_append(&buffer, buf, strlen(buf));
1039                         continue;
1040                 default:
1041                         fatal("channel_open_message: bad channel type %d", c->type);
1042                         /* NOTREACHED */
1043                 }
1044         }
1045         buffer_append(&buffer, "\0", 1);
1046         cp = xstrdup(buffer_ptr(&buffer));
1047         buffer_free(&buffer);
1048         return cp;
1049 }
1050
1051 /*
1052  * Initiate forwarding of connections to local port "port" through the secure
1053  * channel to host:port from remote side.
1054  */
1055
1056 void 
1057 channel_request_local_forwarding(u_short port, const char *host,
1058                                  u_short host_port, int gateway_ports)
1059 {
1060         int success, ch, sock, on = 1;
1061         struct addrinfo hints, *ai, *aitop;
1062         char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1063         struct linger linger;
1064
1065         if (strlen(host) > sizeof(channels[0].path) - 1)
1066                 packet_disconnect("Forward host name too long.");
1067
1068         /*
1069          * getaddrinfo returns a loopback address if the hostname is
1070          * set to NULL and hints.ai_flags is not AI_PASSIVE
1071          */
1072         memset(&hints, 0, sizeof(hints));
1073         hints.ai_family = IPv4or6;
1074         hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
1075         hints.ai_socktype = SOCK_STREAM;
1076         snprintf(strport, sizeof strport, "%d", port);
1077         if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
1078                 packet_disconnect("getaddrinfo: fatal error");
1079
1080         success = 0;
1081         for (ai = aitop; ai; ai = ai->ai_next) {
1082                 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1083                         continue;
1084                 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1085                     strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1086                         error("channel_request_local_forwarding: getnameinfo failed");
1087                         continue;
1088                 }
1089                 /* Create a port to listen for the host. */
1090                 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1091                 if (sock < 0) {
1092                         /* this is no error since kernel may not support ipv6 */
1093                         verbose("socket: %.100s", strerror(errno));
1094                         continue;
1095                 }
1096                 /*
1097                  * Set socket options.  We would like the socket to disappear
1098                  * as soon as it has been closed for whatever reason.
1099                  */
1100                 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
1101                 linger.l_onoff = 1;
1102                 linger.l_linger = 5;
1103                 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
1104                 debug("Local forwarding listening on %s port %s.", ntop, strport);
1105
1106                 /* Bind the socket to the address. */
1107                 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1108                         /* address can be in use ipv6 address is already bound */
1109                         if (!ai->ai_next)
1110                                 error("bind: %.100s", strerror(errno));
1111                         else
1112                                 verbose("bind: %.100s", strerror(errno));
1113                                 
1114                         close(sock);
1115                         continue;
1116                 }
1117                 /* Start listening for connections on the socket. */
1118                 if (listen(sock, 5) < 0) {
1119                         error("listen: %.100s", strerror(errno));
1120                         close(sock);
1121                         continue;
1122                 }
1123                 /* Allocate a channel number for the socket. */
1124                 ch = channel_new(
1125                     "port listener", SSH_CHANNEL_PORT_LISTENER,
1126                     sock, sock, -1,
1127                     CHAN_WINDOW_DEFAULT, CHAN_PACKET_DEFAULT,
1128                     0, xstrdup("port listener"));
1129                 strlcpy(channels[ch].path, host, sizeof(channels[ch].path));
1130                 channels[ch].host_port = host_port;
1131                 channels[ch].listening_port = port;
1132                 success = 1;
1133         }
1134         if (success == 0)
1135                 packet_disconnect("cannot listen port: %d", port);
1136         freeaddrinfo(aitop);
1137 }
1138
1139 /*
1140  * Initiate forwarding of connections to port "port" on remote host through
1141  * the secure channel to host:port from local side.
1142  */
1143
1144 void 
1145 channel_request_remote_forwarding(u_short listen_port, const char *host_to_connect,
1146                                   u_short port_to_connect)
1147 {
1148         int payload_len;
1149         /* Record locally that connection to this host/port is permitted. */
1150         if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
1151                 fatal("channel_request_remote_forwarding: too many forwards");
1152
1153         permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
1154         permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
1155         permitted_opens[num_permitted_opens].listen_port = listen_port;
1156         num_permitted_opens++;
1157
1158         /* Send the forward request to the remote side. */
1159         packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1160         packet_put_int(port_to_connect);
1161         packet_put_string(host_to_connect, strlen(host_to_connect));
1162         packet_put_int(listen_port);
1163         packet_send();
1164         packet_write_wait();
1165         /*
1166          * Wait for response from the remote side.  It will send a disconnect
1167          * message on failure, and we will never see it here.
1168          */
1169         packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1170 }
1171
1172 /*
1173  * This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
1174  * listening for the port, and sends back a success reply (or disconnect
1175  * message if there was an error).  This never returns if there was an error.
1176  */
1177
1178 void 
1179 channel_input_port_forward_request(int is_root)
1180 {
1181         u_short port, host_port;
1182         char *hostname;
1183
1184         /* Get arguments from the packet. */
1185         port = packet_get_int();
1186         hostname = packet_get_string(NULL);
1187         host_port = packet_get_int();
1188
1189         /*
1190          * Check that an unprivileged user is not trying to forward a
1191          * privileged port.
1192          */
1193         if (port < IPPORT_RESERVED && !is_root)
1194                 packet_disconnect("Requested forwarding of port %d but user is not root.",
1195                                   port);
1196         /*
1197          * Initiate forwarding,
1198          * bind port to localhost only (gateway ports == 0).
1199          */
1200         channel_request_local_forwarding(port, hostname, host_port, 0);
1201
1202         /* Free the argument string. */
1203         xfree(hostname);
1204 }
1205
1206 /* XXX move to aux.c */
1207 int
1208 channel_connect_to(const char *host, u_short host_port)
1209 {
1210         struct addrinfo hints, *ai, *aitop;
1211         char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1212         int gaierr;
1213         int sock = -1;
1214
1215         memset(&hints, 0, sizeof(hints));
1216         hints.ai_family = IPv4or6;
1217         hints.ai_socktype = SOCK_STREAM;
1218         snprintf(strport, sizeof strport, "%d", host_port);
1219         if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
1220                 error("%.100s: unknown host (%s)", host, gai_strerror(gaierr));
1221                 return -1;
1222         }
1223         for (ai = aitop; ai; ai = ai->ai_next) {
1224                 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1225                         continue;
1226                 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1227                     strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1228                         error("channel_connect_to: getnameinfo failed");
1229                         continue;
1230                 }
1231                 /* Create the socket. */
1232                 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1233                 if (sock < 0) {
1234                         error("socket: %.100s", strerror(errno));
1235                         continue;
1236                 }
1237                 /* Connect to the host/port. */
1238                 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1239                         error("connect %.100s port %s: %.100s", ntop, strport,
1240                             strerror(errno));
1241                         close(sock);
1242                         continue;       /* fail -- try next */  
1243                 }
1244                 break; /* success */
1245
1246         }
1247         freeaddrinfo(aitop);
1248         if (!ai) {
1249                 error("connect %.100s port %d: failed.", host, host_port);      
1250                 return -1;
1251         }
1252         /* success */
1253         return sock;
1254 }
1255
1256 /*
1257  * This is called after receiving PORT_OPEN message.  This attempts to
1258  * connect to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION
1259  * or CHANNEL_OPEN_FAILURE.
1260  */
1261
1262 void 
1263 channel_input_port_open(int type, int plen)
1264 {
1265         u_short host_port;
1266         char *host, *originator_string;
1267         int remote_channel, sock = -1, newch, i, denied;
1268         unsigned int host_len, originator_len;
1269
1270         /* Get remote channel number. */
1271         remote_channel = packet_get_int();
1272
1273         /* Get host name to connect to. */
1274         host = packet_get_string(&host_len);
1275
1276         /* Get port to connect to. */
1277         host_port = packet_get_int();
1278
1279         /* Get remote originator name. */
1280         if (have_hostname_in_open) {
1281                 originator_string = packet_get_string(&originator_len);
1282                 originator_len += 4;    /* size of packet_int */
1283         } else {
1284                 originator_string = xstrdup("unknown (remote did not supply name)");
1285                 originator_len = 0;     /* no originator supplied */
1286         }
1287
1288         packet_integrity_check(plen,
1289             4 + 4 + host_len + 4 + originator_len, SSH_MSG_PORT_OPEN);
1290
1291         /* Check if opening that port is permitted. */
1292         denied = 0;
1293         if (!all_opens_permitted) {
1294                 /* Go trough all permitted ports. */
1295                 for (i = 0; i < num_permitted_opens; i++)
1296                         if (permitted_opens[i].port_to_connect == host_port &&
1297                             strcmp(permitted_opens[i].host_to_connect, host) == 0)
1298                                 break;
1299
1300                 /* Check if we found the requested port among those permitted. */
1301                 if (i >= num_permitted_opens) {
1302                         /* The port is not permitted. */
1303                         log("Received request to connect to %.100s:%d, but the request was denied.",
1304                             host, host_port);
1305                         denied = 1;
1306                 }
1307         }
1308         sock = denied ? -1 : channel_connect_to(host, host_port);
1309         if (sock > 0) {
1310                 /* Allocate a channel for this connection. */
1311                 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, originator_string);
1312                 channels[newch].remote_id = remote_channel;
1313
1314                 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1315                 packet_put_int(remote_channel);
1316                 packet_put_int(newch);
1317                 packet_send();
1318         } else {
1319                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1320                 packet_put_int(remote_channel);
1321                 packet_send();
1322         }
1323         xfree(host);
1324 }
1325
1326 /*
1327  * Creates an internet domain socket for listening for X11 connections.
1328  * Returns a suitable value for the DISPLAY variable, or NULL if an error
1329  * occurs.
1330  */
1331
1332 #define NUM_SOCKS       10
1333
1334 char *
1335 x11_create_display_inet(int screen_number, int x11_display_offset)
1336 {
1337         int display_number, sock;
1338         u_short port;
1339         struct addrinfo hints, *ai, *aitop;
1340         char strport[NI_MAXSERV];
1341         int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
1342         char display[512];
1343         char hostname[MAXHOSTNAMELEN];
1344
1345         for (display_number = x11_display_offset;
1346              display_number < MAX_DISPLAYS;
1347              display_number++) {
1348                 port = 6000 + display_number;
1349                 memset(&hints, 0, sizeof(hints));
1350                 hints.ai_family = IPv4or6;
1351                 hints.ai_flags = AI_PASSIVE;            /* XXX loopback only ? */
1352                 hints.ai_socktype = SOCK_STREAM;
1353                 snprintf(strport, sizeof strport, "%d", port);
1354                 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
1355                         error("getaddrinfo: %.100s", gai_strerror(gaierr));
1356                         return NULL;
1357                 }
1358                 for (ai = aitop; ai; ai = ai->ai_next) {
1359                         if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1360                                 continue;
1361                         sock = socket(ai->ai_family, SOCK_STREAM, 0);
1362                         if (sock < 0) {
1363                                 if (errno != EINVAL) {
1364                                         error("socket: %.100s", strerror(errno));
1365                                         return NULL;
1366                                 } else {
1367                                         debug("Socket family %d not supported [X11 disp create]", ai->ai_family);
1368                                         continue;
1369                                 }
1370                         }
1371                         if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1372                                 debug("bind port %d: %.100s", port, strerror(errno));
1373                                 shutdown(sock, SHUT_RDWR);
1374                                 close(sock);
1375
1376                                 if (ai->ai_next)
1377                                         continue;
1378
1379                                 for (n = 0; n < num_socks; n++) {
1380                                         shutdown(socks[n], SHUT_RDWR);
1381                                         close(socks[n]);
1382                                 }
1383                                 num_socks = 0;
1384                                 break;
1385                         }
1386                         socks[num_socks++] = sock;
1387 #ifndef DONT_TRY_OTHER_AF
1388                         if (num_socks == NUM_SOCKS)
1389                                 break;
1390 #else
1391                         break;
1392 #endif
1393                 }
1394                 if (num_socks > 0)
1395                         break;
1396         }
1397         if (display_number >= MAX_DISPLAYS) {
1398                 error("Failed to allocate internet-domain X11 display socket.");
1399                 return NULL;
1400         }
1401         /* Start listening for connections on the socket. */
1402         for (n = 0; n < num_socks; n++) {
1403                 sock = socks[n];
1404                 if (listen(sock, 5) < 0) {
1405                         error("listen: %.100s", strerror(errno));
1406                         shutdown(sock, SHUT_RDWR);
1407                         close(sock);
1408                         return NULL;
1409                 }
1410         }
1411
1412         /* Set up a suitable value for the DISPLAY variable. */
1413
1414         if (gethostname(hostname, sizeof(hostname)) < 0)
1415                 fatal("gethostname: %.100s", strerror(errno));
1416
1417 #ifdef IPADDR_IN_DISPLAY
1418         /* 
1419          * HPUX detects the local hostname in the DISPLAY variable and tries
1420          * to set up a shared memory connection to the server, which it
1421          * incorrectly supposes to be local.
1422          *
1423          * The workaround - as used in later $$H and other programs - is
1424          * is to set display to the host's IP address.
1425          */
1426         {
1427                 struct hostent *he;
1428                 struct in_addr my_addr;
1429
1430                 he = gethostbyname(hostname);
1431                 if (he == NULL) {
1432                         error("[X11-broken-fwd-hostname-workaround] Could not get "
1433                                 "IP address for hostname %s.", hostname);
1434
1435                         packet_send_debug("[X11-broken-fwd-hostname-workaround]"
1436                                 "Could not get IP address for hostname %s.", hostname);
1437
1438                         shutdown(sock, SHUT_RDWR);
1439                         close(sock);
1440
1441                         return NULL;
1442                 }
1443
1444                 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
1445
1446                 /* Set DISPLAY to <ip address>:screen.display */
1447                 snprintf(display, sizeof(display), "%.50s:%d.%d", inet_ntoa(my_addr), 
1448                         display_number, screen_number);
1449         }
1450 #else /* IPADDR_IN_DISPLAY */
1451         /* Just set DISPLAY to hostname:screen.display */
1452         snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
1453                 display_number, screen_number);
1454 #endif /* IPADDR_IN_DISPLAY */
1455
1456         /* Allocate a channel for each socket. */
1457         for (n = 0; n < num_socks; n++) {
1458                 sock = socks[n];
1459                 (void) channel_allocate(SSH_CHANNEL_X11_LISTENER, sock,
1460                                         xstrdup("X11 inet listener"));
1461         }
1462
1463         /* Return a suitable value for the DISPLAY environment variable. */
1464         return xstrdup(display);
1465 }
1466
1467 #ifndef X_UNIX_PATH
1468 #define X_UNIX_PATH "/tmp/.X11-unix/X"
1469 #endif
1470
1471 static
1472 int
1473 connect_local_xsocket(unsigned int dnr)
1474 {
1475         static const char *const x_sockets[] = {
1476                 X_UNIX_PATH "%u",
1477                 "/var/X/.X11-unix/X" "%u",
1478                 "/usr/spool/sockets/X11/" "%u",
1479                 NULL
1480         };
1481         int sock;
1482         struct sockaddr_un addr;
1483         const char *const * path;
1484
1485         for (path = x_sockets; *path; ++path) {
1486                 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1487                 if (sock < 0)
1488                         error("socket: %.100s", strerror(errno));
1489                 memset(&addr, 0, sizeof(addr));
1490                 addr.sun_family = AF_UNIX;
1491                 snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
1492                 if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
1493                         return sock;
1494                 close(sock);
1495         }
1496         error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
1497         return -1;
1498 }
1499
1500
1501 /*
1502  * This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
1503  * the remote channel number.  We should do whatever we want, and respond
1504  * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
1505  */
1506
1507 void 
1508 x11_input_open(int type, int plen)
1509 {
1510         int remote_channel, display_number, sock = 0, newch;
1511         const char *display;
1512         char buf[1024], *cp, *remote_host;
1513         unsigned int remote_len;
1514         struct addrinfo hints, *ai, *aitop;
1515         char strport[NI_MAXSERV];
1516         int gaierr;
1517
1518         /* Get remote channel number. */
1519         remote_channel = packet_get_int();
1520
1521         /* Get remote originator name. */
1522         if (have_hostname_in_open) {
1523                 remote_host = packet_get_string(&remote_len);
1524                 remote_len += 4;
1525         } else {
1526                 remote_host = xstrdup("unknown (remote did not supply name)");
1527                 remote_len = 0;
1528         }
1529
1530         debug("Received X11 open request.");
1531         packet_integrity_check(plen, 4 + remote_len, SSH_SMSG_X11_OPEN);
1532
1533         /* Try to open a socket for the local X server. */
1534         display = getenv("DISPLAY");
1535         if (!display) {
1536                 error("DISPLAY not set.");
1537                 goto fail;
1538         }
1539         /*
1540          * Now we decode the value of the DISPLAY variable and make a
1541          * connection to the real X server.
1542          */
1543
1544         /*
1545          * Check if it is a unix domain socket.  Unix domain displays are in
1546          * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
1547          */
1548         if (strncmp(display, "unix:", 5) == 0 ||
1549             display[0] == ':') {
1550                 /* Connect to the unix domain socket. */
1551                 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
1552                         error("Could not parse display number from DISPLAY: %.100s",
1553                               display);
1554                         goto fail;
1555                 }
1556                 /* Create a socket. */
1557                 sock = connect_local_xsocket(display_number);
1558                 if (sock < 0)
1559                         goto fail;
1560
1561                 /* OK, we now have a connection to the display. */
1562                 goto success;
1563         }
1564         /*
1565          * Connect to an inet socket.  The DISPLAY value is supposedly
1566          * hostname:d[.s], where hostname may also be numeric IP address.
1567          */
1568         strncpy(buf, display, sizeof(buf));
1569         buf[sizeof(buf) - 1] = 0;
1570         cp = strchr(buf, ':');
1571         if (!cp) {
1572                 error("Could not find ':' in DISPLAY: %.100s", display);
1573                 goto fail;
1574         }
1575         *cp = 0;
1576         /* buf now contains the host name.  But first we parse the display number. */
1577         if (sscanf(cp + 1, "%d", &display_number) != 1) {
1578                 error("Could not parse display number from DISPLAY: %.100s",
1579                       display);
1580                 goto fail;
1581         }
1582
1583         /* Look up the host address */
1584         memset(&hints, 0, sizeof(hints));
1585         hints.ai_family = IPv4or6;
1586         hints.ai_socktype = SOCK_STREAM;
1587         snprintf(strport, sizeof strport, "%d", 6000 + display_number);
1588         if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
1589                 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
1590                 goto fail;
1591         }
1592         for (ai = aitop; ai; ai = ai->ai_next) {
1593                 /* Create a socket. */
1594                 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1595                 if (sock < 0) {
1596                         debug("socket: %.100s", strerror(errno));
1597                         continue;
1598                 }
1599                 /* Connect it to the display. */
1600                 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1601                         debug("connect %.100s port %d: %.100s", buf,
1602                             6000 + display_number, strerror(errno));
1603                         close(sock);
1604                         continue;
1605                 }
1606                 /* Success */
1607                 break;
1608         }
1609         freeaddrinfo(aitop);
1610         if (!ai) {
1611                 error("connect %.100s port %d: %.100s", buf, 6000 + display_number, 
1612                     strerror(errno));
1613                 goto fail;
1614         }
1615 success:
1616         /* We have successfully obtained a connection to the real X display. */
1617
1618         /* Allocate a channel for this connection. */
1619         if (x11_saved_proto == NULL)
1620                 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, remote_host);
1621         else
1622                 newch = channel_allocate(SSH_CHANNEL_X11_OPEN, sock, remote_host);
1623         channels[newch].remote_id = remote_channel;
1624
1625         /* Send a confirmation to the remote host. */
1626         packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1627         packet_put_int(remote_channel);
1628         packet_put_int(newch);
1629         packet_send();
1630
1631         return;
1632
1633 fail:
1634         /* Send refusal to the remote host. */
1635         packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1636         packet_put_int(remote_channel);
1637         packet_send();
1638 }
1639
1640 /*
1641  * Requests forwarding of X11 connections, generates fake authentication
1642  * data, and enables authentication spoofing.
1643  */
1644
1645 void 
1646 x11_request_forwarding_with_spoofing(const char *proto, const char *data)
1647 {
1648         unsigned int data_len = (unsigned int) strlen(data) / 2;
1649         unsigned int i, value;
1650         char *new_data;
1651         int screen_number;
1652         const char *cp;
1653         u_int32_t rand = 0;
1654
1655         cp = getenv("DISPLAY");
1656         if (cp)
1657                 cp = strchr(cp, ':');
1658         if (cp)
1659                 cp = strchr(cp, '.');
1660         if (cp)
1661                 screen_number = atoi(cp + 1);
1662         else
1663                 screen_number = 0;
1664
1665         /* Save protocol name. */
1666         x11_saved_proto = xstrdup(proto);
1667
1668         /*
1669          * Extract real authentication data and generate fake data of the
1670          * same length.
1671          */
1672         x11_saved_data = xmalloc(data_len);
1673         x11_fake_data = xmalloc(data_len);
1674         for (i = 0; i < data_len; i++) {
1675                 if (sscanf(data + 2 * i, "%2x", &value) != 1)
1676                         fatal("x11_request_forwarding: bad authentication data: %.100s", data);
1677                 if (i % 4 == 0)
1678                         rand = arc4random();
1679                 x11_saved_data[i] = value;
1680                 x11_fake_data[i] = rand & 0xff;
1681                 rand >>= 8;
1682         }
1683         x11_saved_data_len = data_len;
1684         x11_fake_data_len = data_len;
1685
1686         /* Convert the fake data into hex. */
1687         new_data = xmalloc(2 * data_len + 1);
1688         for (i = 0; i < data_len; i++)
1689                 sprintf(new_data + 2 * i, "%02x", (unsigned char) x11_fake_data[i]);
1690
1691         /* Send the request packet. */
1692         packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
1693         packet_put_string(proto, strlen(proto));
1694         packet_put_string(new_data, strlen(new_data));
1695         packet_put_int(screen_number);
1696         packet_send();
1697         packet_write_wait();
1698         xfree(new_data);
1699 }
1700
1701 /* Sends a message to the server to request authentication fd forwarding. */
1702
1703 void 
1704 auth_request_forwarding()
1705 {
1706         packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
1707         packet_send();
1708         packet_write_wait();
1709 }
1710
1711 /*
1712  * Returns the name of the forwarded authentication socket.  Returns NULL if
1713  * there is no forwarded authentication socket.  The returned value points to
1714  * a static buffer.
1715  */
1716
1717 char *
1718 auth_get_socket_name()
1719 {
1720         return channel_forwarded_auth_socket_name;
1721 }
1722
1723 /* removes the agent forwarding socket */
1724
1725 void 
1726 cleanup_socket(void)
1727 {
1728         remove(channel_forwarded_auth_socket_name);
1729         rmdir(channel_forwarded_auth_socket_dir);
1730 }
1731
1732 /*
1733  * This if called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
1734  * This starts forwarding authentication requests.
1735  */
1736
1737 void 
1738 auth_input_request_forwarding(struct passwd * pw)
1739 {
1740         int sock, newch;
1741         struct sockaddr_un sunaddr;
1742
1743         if (auth_get_socket_name() != NULL)
1744                 fatal("Protocol error: authentication forwarding requested twice.");
1745
1746         /* Temporarily drop privileged uid for mkdir/bind. */
1747         temporarily_use_uid(pw->pw_uid);
1748
1749         /* Allocate a buffer for the socket name, and format the name. */
1750         channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
1751         channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
1752         strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
1753
1754         /* Create private directory for socket */
1755         if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL)
1756                 packet_disconnect("mkdtemp: %.100s", strerror(errno));
1757         snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME, "%s/agent.%d",
1758                  channel_forwarded_auth_socket_dir, (int) getpid());
1759
1760         if (atexit(cleanup_socket) < 0) {
1761                 int saved = errno;
1762                 cleanup_socket();
1763                 packet_disconnect("socket: %.100s", strerror(saved));
1764         }
1765         /* Create the socket. */
1766         sock = socket(AF_UNIX, SOCK_STREAM, 0);
1767         if (sock < 0)
1768                 packet_disconnect("socket: %.100s", strerror(errno));
1769
1770         /* Bind it to the name. */
1771         memset(&sunaddr, 0, sizeof(sunaddr));
1772         sunaddr.sun_family = AF_UNIX;
1773         strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
1774                 sizeof(sunaddr.sun_path));
1775
1776         if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
1777                 packet_disconnect("bind: %.100s", strerror(errno));
1778
1779         /* Restore the privileged uid. */
1780         restore_uid();
1781
1782         /* Start listening on the socket. */
1783         if (listen(sock, 5) < 0)
1784                 packet_disconnect("listen: %.100s", strerror(errno));
1785
1786         /* Allocate a channel for the authentication agent socket. */
1787         newch = channel_allocate(SSH_CHANNEL_AUTH_SOCKET, sock,
1788                                  xstrdup("auth socket"));
1789         strlcpy(channels[newch].path, channel_forwarded_auth_socket_name,
1790             sizeof(channels[newch].path));
1791 }
1792
1793 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
1794
1795 void 
1796 auth_input_open_request(int type, int plen)
1797 {
1798         int remch, sock, newch;
1799         char *dummyname;
1800
1801         packet_integrity_check(plen, 4, type);
1802
1803         /* Read the remote channel number from the message. */
1804         remch = packet_get_int();
1805
1806         /*
1807          * Get a connection to the local authentication agent (this may again
1808          * get forwarded).
1809          */
1810         sock = ssh_get_authentication_socket();
1811
1812         /*
1813          * If we could not connect the agent, send an error message back to
1814          * the server. This should never happen unless the agent dies,
1815          * because authentication forwarding is only enabled if we have an
1816          * agent.
1817          */
1818         if (sock < 0) {
1819                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1820                 packet_put_int(remch);
1821                 packet_send();
1822                 return;
1823         }
1824         debug("Forwarding authentication connection.");
1825
1826         /*
1827          * Dummy host name.  This will be freed when the channel is freed; it
1828          * will still be valid in the packet_put_string below since the
1829          * channel cannot yet be freed at that point.
1830          */
1831         dummyname = xstrdup("authentication agent connection");
1832
1833         newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
1834         channels[newch].remote_id = remch;
1835
1836         /* Send a confirmation to the remote host. */
1837         packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1838         packet_put_int(remch);
1839         packet_put_int(newch);
1840         packet_send();
1841 }
This page took 0.194767 seconds and 5 git commands to generate.