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