]> andersk Git - openssh.git/blob - channels.c
- Moved all the bsd-* and fake-* stuff into new libopenbsd-compat.a
[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                 if (compat20)
509                         channel_pre_open_20(c, readset, writeset);
510                 else
511                         channel_pre_open_15(c, readset, writeset);
512         } else if (ret == -1) {
513                 debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
514                 chan_read_failed(c);    /** force close? */
515                 chan_write_failed(c);
516                 debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
517         }
518 }
519
520 /* This is our fake X11 server socket. */
521 void
522 channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
523 {
524         struct sockaddr addr;
525         int newsock, newch;
526         socklen_t addrlen;
527         char buf[16384], *remote_hostname;
528         int remote_port;
529
530         if (FD_ISSET(c->sock, readset)) {
531                 debug("X11 connection requested.");
532                 addrlen = sizeof(addr);
533                 newsock = accept(c->sock, &addr, &addrlen);
534                 if (newsock < 0) {
535                         error("accept: %.100s", strerror(errno));
536                         return;
537                 }
538                 remote_hostname = get_remote_hostname(newsock);
539                 remote_port = get_peer_port(newsock);
540                 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
541                     remote_hostname, remote_port);
542
543                 newch = channel_new("x11",
544                     SSH_CHANNEL_OPENING, newsock, newsock, -1,
545                     c->local_window_max, c->local_maxpacket,
546                     0, xstrdup(buf));
547                 if (compat20) {
548                         packet_start(SSH2_MSG_CHANNEL_OPEN);
549                         packet_put_cstring("x11");
550                         packet_put_int(newch);
551                         packet_put_int(c->local_window_max);
552                         packet_put_int(c->local_maxpacket);
553                         /* originator host and port */
554                         packet_put_cstring(remote_hostname);
555                         if (datafellows & SSH_BUG_X11FWD) {
556                                 debug("ssh2 x11 bug compat mode");
557                         } else {
558                                 packet_put_int(remote_port);
559                         }
560                         packet_send();
561                 } else {
562                         packet_start(SSH_SMSG_X11_OPEN);
563                         packet_put_int(newch);
564                         if (have_hostname_in_open)
565                                 packet_put_string(buf, strlen(buf));
566                         packet_send();
567                 }
568                 xfree(remote_hostname);
569         }
570 }
571
572 /*
573  * This socket is listening for connections to a forwarded TCP/IP port.
574  */
575 void
576 channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
577 {
578         struct sockaddr addr;
579         int newsock, newch;
580         socklen_t addrlen;
581         char buf[1024], *remote_hostname;
582         int remote_port;
583
584         if (FD_ISSET(c->sock, readset)) {
585                 debug("Connection to port %d forwarding "
586                     "to %.100s port %d requested.",
587                     c->listening_port, c->path, c->host_port);
588                 addrlen = sizeof(addr);
589                 newsock = accept(c->sock, &addr, &addrlen);
590                 if (newsock < 0) {
591                         error("accept: %.100s", strerror(errno));
592                         return;
593                 }
594                 remote_hostname = get_remote_hostname(newsock);
595                 remote_port = get_peer_port(newsock);
596                 snprintf(buf, sizeof buf,
597                     "listen port %d for %.100s port %d, "
598                     "connect from %.200s port %d",
599                     c->listening_port, c->path, c->host_port,
600                     remote_hostname, remote_port);
601                 newch = channel_new("direct-tcpip",
602                     SSH_CHANNEL_OPENING, newsock, newsock, -1,
603                     c->local_window_max, c->local_maxpacket,
604                     0, xstrdup(buf));
605                 if (compat20) {
606                         packet_start(SSH2_MSG_CHANNEL_OPEN);
607                         packet_put_cstring("direct-tcpip");
608                         packet_put_int(newch);
609                         packet_put_int(c->local_window_max);
610                         packet_put_int(c->local_maxpacket);
611                         /* target host and port */
612                         packet_put_string(c->path, strlen(c->path));
613                         packet_put_int(c->host_port);
614                         /* originator host and port */
615                         packet_put_cstring(remote_hostname);
616                         packet_put_int(remote_port);
617                         packet_send();
618                 } else {
619                         packet_start(SSH_MSG_PORT_OPEN);
620                         packet_put_int(newch);
621                         packet_put_string(c->path, strlen(c->path));
622                         packet_put_int(c->host_port);
623                         if (have_hostname_in_open) {
624                                 packet_put_string(buf, strlen(buf));
625                         }
626                         packet_send();
627                 }
628                 xfree(remote_hostname);
629         }
630 }
631
632 /*
633  * This is the authentication agent socket listening for connections from
634  * clients.
635  */
636 void
637 channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
638 {
639         struct sockaddr addr;
640         int newsock, newch;
641         socklen_t addrlen;
642
643         if (FD_ISSET(c->sock, readset)) {
644                 addrlen = sizeof(addr);
645                 newsock = accept(c->sock, &addr, &addrlen);
646                 if (newsock < 0) {
647                         error("accept from auth socket: %.100s", strerror(errno));
648                         return;
649                 }
650                 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
651                     xstrdup("accepted auth socket"));
652                 packet_start(SSH_SMSG_AGENT_OPEN);
653                 packet_put_int(newch);
654                 packet_send();
655         }
656 }
657
658 int
659 channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
660 {
661         char buf[16*1024];
662         int len;
663
664         if (c->rfd != -1 &&
665             FD_ISSET(c->rfd, readset)) {
666                 len = read(c->rfd, buf, sizeof(buf));
667                 if (len < 0 && (errno == EINTR || errno == EAGAIN))
668                         return 1;
669                 if (len <= 0) {
670                         debug("channel %d: read<=0 rfd %d len %d",
671                             c->self, c->rfd, len);
672                         if (compat13) {
673                                 buffer_consume(&c->output, buffer_len(&c->output));
674                                 c->type = SSH_CHANNEL_INPUT_DRAINING;
675                                 debug("Channel %d status set to input draining.", c->self);
676                         } else {
677                                 chan_read_failed(c);
678                         }
679                         return -1;
680                 }
681                 buffer_append(&c->input, buf, len);
682         }
683         return 1;
684 }
685 int
686 channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
687 {
688         int len;
689
690         /* Send buffered output data to the socket. */
691         if (c->wfd != -1 &&
692             FD_ISSET(c->wfd, writeset) &&
693             buffer_len(&c->output) > 0) {
694                 len = write(c->wfd, buffer_ptr(&c->output),
695                     buffer_len(&c->output));
696                 if (len < 0 && (errno == EINTR || errno == EAGAIN))
697                         return 1;
698                 if (len <= 0) {
699                         if (compat13) {
700                                 buffer_consume(&c->output, buffer_len(&c->output));
701                                 debug("Channel %d status set to input draining.", c->self);
702                                 c->type = SSH_CHANNEL_INPUT_DRAINING;
703                         } else {
704                                 chan_write_failed(c);
705                         }
706                         return -1;
707                 }
708                 buffer_consume(&c->output, len);
709                 if (compat20 && len > 0) {
710                         c->local_consumed += len;
711                 }
712         }
713         return 1;
714 }
715 int
716 channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
717 {
718         char buf[16*1024];
719         int len;
720
721 /** XXX handle drain efd, too */
722         if (c->efd != -1) {
723                 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
724                     FD_ISSET(c->efd, writeset) &&
725                     buffer_len(&c->extended) > 0) {
726                         len = write(c->efd, buffer_ptr(&c->extended),
727                             buffer_len(&c->extended));
728                         debug("channel %d: written %d to efd %d",
729                             c->self, len, c->efd);
730                         if (len > 0) {
731                                 buffer_consume(&c->extended, len);
732                                 c->local_consumed += len;
733                         }
734                 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
735                     FD_ISSET(c->efd, readset)) {
736                         len = read(c->efd, buf, sizeof(buf));
737                         debug("channel %d: read %d from efd %d",
738                              c->self, len, c->efd);
739                         if (len == 0) {
740                                 debug("channel %d: closing efd %d",
741                                     c->self, c->efd);
742                                 close(c->efd);
743                                 c->efd = -1;
744                         } else if (len > 0)
745                                 buffer_append(&c->extended, buf, len);
746                 }
747         }
748         return 1;
749 }
750 int
751 channel_check_window(Channel *c, fd_set * readset, fd_set * writeset)
752 {
753         if (!(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
754             c->local_window < c->local_window_max/2 &&
755             c->local_consumed > 0) {
756                 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
757                 packet_put_int(c->remote_id);
758                 packet_put_int(c->local_consumed);
759                 packet_send();
760                 debug("channel %d: window %d sent adjust %d",
761                     c->self, c->local_window,
762                     c->local_consumed);
763                 c->local_window += c->local_consumed;
764                 c->local_consumed = 0;
765         }
766         return 1;
767 }
768
769 void
770 channel_post_open_1(Channel *c, fd_set * readset, fd_set * writeset)
771 {
772         channel_handle_rfd(c, readset, writeset);
773         channel_handle_wfd(c, readset, writeset);
774 }
775
776 void
777 channel_post_open_2(Channel *c, fd_set * readset, fd_set * writeset)
778 {
779         channel_handle_rfd(c, readset, writeset);
780         channel_handle_wfd(c, readset, writeset);
781         channel_handle_efd(c, readset, writeset);
782         channel_check_window(c, readset, writeset);
783 }
784
785 void
786 channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
787 {
788         int len;
789         /* Send buffered output data to the socket. */
790         if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
791                 len = write(c->sock, buffer_ptr(&c->output),
792                             buffer_len(&c->output));
793                 if (len <= 0)
794                         buffer_consume(&c->output, buffer_len(&c->output));
795                 else
796                         buffer_consume(&c->output, len);
797         }
798 }
799
800 void
801 channel_handler_init_20(void)
802 {
803         channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_20;
804         channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
805         channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
806         channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
807
808         channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_2;
809         channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
810         channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
811 }
812
813 void
814 channel_handler_init_13(void)
815 {
816         channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_13;
817         channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open_13;
818         channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
819         channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
820         channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
821         channel_pre[SSH_CHANNEL_INPUT_DRAINING] =       &channel_pre_input_draining;
822         channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] =      &channel_pre_output_draining;
823
824         channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_1;
825         channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
826         channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
827         channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
828         channel_post[SSH_CHANNEL_OUTPUT_DRAINING] =     &channel_post_output_drain_13;
829 }
830
831 void
832 channel_handler_init_15(void)
833 {
834         channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_15;
835         channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
836         channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
837         channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
838         channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
839
840         channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
841         channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
842         channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
843         channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_1;
844 }
845
846 void
847 channel_handler_init(void)
848 {
849         int i;
850         for(i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
851                 channel_pre[i] = NULL;
852                 channel_post[i] = NULL;
853         }
854         if (compat20)
855                 channel_handler_init_20();
856         else if (compat13)
857                 channel_handler_init_13();
858         else
859                 channel_handler_init_15();
860 }
861
862 void
863 channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
864 {
865         static int did_init = 0;
866         int i;
867         Channel *c;
868
869         if (!did_init) {
870                 channel_handler_init();
871                 did_init = 1;
872         }
873         for (i = 0; i < channels_alloc; i++) {
874                 c = &channels[i];
875                 if (c->type == SSH_CHANNEL_FREE)
876                         continue;
877                 if (ftab[c->type] == NULL)
878                         continue;
879                 (*ftab[c->type])(c, readset, writeset);
880                 chan_delete_if_full_closed(c);
881         }
882 }
883
884 void
885 channel_prepare_select(fd_set * readset, fd_set * writeset)
886 {
887         channel_handler(channel_pre, readset, writeset);
888 }
889
890 void
891 channel_after_select(fd_set * readset, fd_set * writeset)
892 {
893         channel_handler(channel_post, readset, writeset);
894 }
895
896 /* If there is data to send to the connection, send some of it now. */
897
898 void
899 channel_output_poll()
900 {
901         int len, i;
902         Channel *c;
903
904         for (i = 0; i < channels_alloc; i++) {
905                 c = &channels[i];
906
907                 /* We are only interested in channels that can have buffered incoming data. */
908                 if (compat13) {
909                         if (c->type != SSH_CHANNEL_OPEN &&
910                             c->type != SSH_CHANNEL_INPUT_DRAINING)
911                                 continue;
912                 } else {
913                         if (c->type != SSH_CHANNEL_OPEN)
914                                 continue;
915                         if (c->istate != CHAN_INPUT_OPEN &&
916                             c->istate != CHAN_INPUT_WAIT_DRAIN)
917                                 continue;
918                 }
919                 if (compat20 &&
920                     (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
921                         debug("channel: %d: no data after CLOSE", c->self);
922                         continue;
923                 }
924
925                 /* Get the amount of buffered data for this channel. */
926                 len = buffer_len(&c->input);
927                 if (len > 0) {
928                         /* Send some data for the other side over the secure connection. */
929                         if (compat20) {
930                                 if (len > c->remote_window)
931                                         len = c->remote_window;
932                                 if (len > c->remote_maxpacket)
933                                         len = c->remote_maxpacket;
934                         } else {
935                                 if (packet_is_interactive()) {
936                                         if (len > 1024)
937                                                 len = 512;
938                                 } else {
939                                         /* Keep the packets at reasonable size. */
940                                         if (len > packet_get_maxsize()/2)
941                                                 len = packet_get_maxsize()/2;
942                                 }
943                         }
944                         if (len > 0) {
945                                 packet_start(compat20 ?
946                                     SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
947                                 packet_put_int(c->remote_id);
948                                 packet_put_string(buffer_ptr(&c->input), len);
949                                 packet_send();
950                                 buffer_consume(&c->input, len);
951                                 c->remote_window -= len;
952                                 debug("channel %d: send data len %d", c->self, len);
953                         }
954                 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
955                         if (compat13)
956                                 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
957                         /*
958                          * input-buffer is empty and read-socket shutdown:
959                          * tell peer, that we will not send more data: send IEOF
960                          */
961                         chan_ibuf_empty(c);
962                 }
963                 /* Send extended data, i.e. stderr */
964                 if (compat20 &&
965                     c->remote_window > 0 &&
966                     (len = buffer_len(&c->extended)) > 0 &&
967                     c->extended_usage == CHAN_EXTENDED_READ) {
968                         if (len > c->remote_window)
969                                 len = c->remote_window;
970                         if (len > c->remote_maxpacket)
971                                 len = c->remote_maxpacket;
972                         packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
973                         packet_put_int(c->remote_id);
974                         packet_put_int(SSH2_EXTENDED_DATA_STDERR);
975                         packet_put_string(buffer_ptr(&c->extended), len);
976                         packet_send();
977                         buffer_consume(&c->extended, len);
978                         c->remote_window -= len;
979                 }
980         }
981 }
982
983 /*
984  * This is called when a packet of type CHANNEL_DATA has just been received.
985  * The message type has already been consumed, but channel number and data is
986  * still there.
987  */
988
989 void
990 channel_input_data(int type, int plen)
991 {
992         int id;
993         char *data;
994         unsigned int data_len;
995         Channel *c;
996
997         /* Get the channel number and verify it. */
998         id = packet_get_int();
999         c = channel_lookup(id);
1000         if (c == NULL)
1001                 packet_disconnect("Received data for nonexistent channel %d.", id);
1002
1003         /* Ignore any data for non-open channels (might happen on close) */
1004         if (c->type != SSH_CHANNEL_OPEN &&
1005             c->type != SSH_CHANNEL_X11_OPEN)
1006                 return;
1007
1008         /* same for protocol 1.5 if output end is no longer open */
1009         if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
1010                 return;
1011
1012         /* Get the data. */
1013         data = packet_get_string(&data_len);
1014         packet_done();
1015
1016         if (compat20){
1017                 if (data_len > c->local_maxpacket) {
1018                         log("channel %d: rcvd big packet %d, maxpack %d",
1019                             c->self, data_len, c->local_maxpacket);
1020                 }
1021                 if (data_len > c->local_window) {
1022                         log("channel %d: rcvd too much data %d, win %d",
1023                             c->self, data_len, c->local_window);
1024                         xfree(data);
1025                         return;
1026                 }
1027                 c->local_window -= data_len;
1028         }else{
1029                 packet_integrity_check(plen, 4 + 4 + data_len, type);
1030         }
1031         buffer_append(&c->output, data, data_len);
1032         xfree(data);
1033 }
1034 void
1035 channel_input_extended_data(int type, int plen)
1036 {
1037         int id;
1038         int tcode;
1039         char *data;
1040         unsigned int data_len;
1041         Channel *c;
1042
1043         /* Get the channel number and verify it. */
1044         id = packet_get_int();
1045         c = channel_lookup(id);
1046
1047         if (c == NULL)
1048                 packet_disconnect("Received extended_data for bad channel %d.", id);
1049         if (c->type != SSH_CHANNEL_OPEN) {
1050                 log("channel %d: ext data for non open", id);
1051                 return;
1052         }
1053         tcode = packet_get_int();
1054         if (c->efd == -1 ||
1055             c->extended_usage != CHAN_EXTENDED_WRITE ||
1056             tcode != SSH2_EXTENDED_DATA_STDERR) {
1057                 log("channel %d: bad ext data", c->self);
1058                 return;
1059         }
1060         data = packet_get_string(&data_len);
1061         packet_done();
1062         if (data_len > c->local_window) {
1063                 log("channel %d: rcvd too much extended_data %d, win %d",
1064                     c->self, data_len, c->local_window);
1065                 xfree(data);
1066                 return;
1067         }
1068         debug("channel %d: rcvd ext data %d", c->self, data_len);
1069         c->local_window -= data_len;
1070         buffer_append(&c->extended, data, data_len);
1071         xfree(data);
1072 }
1073
1074
1075 /*
1076  * Returns true if no channel has too much buffered data, and false if one or
1077  * more channel is overfull.
1078  */
1079
1080 int
1081 channel_not_very_much_buffered_data()
1082 {
1083         unsigned int i;
1084         Channel *c;
1085
1086         for (i = 0; i < channels_alloc; i++) {
1087                 c = &channels[i];
1088                 if (c->type == SSH_CHANNEL_OPEN) {
1089                         if (!compat20 && buffer_len(&c->input) > packet_get_maxsize()) {
1090                                 debug("channel %d: big input buffer %d",
1091                                     c->self, buffer_len(&c->input));
1092                                 return 0;
1093                         }
1094                         if (buffer_len(&c->output) > packet_get_maxsize()) {
1095                                 debug("channel %d: big output buffer %d",
1096                                     c->self, buffer_len(&c->output));
1097                                 return 0;
1098                         }
1099                 }
1100         }
1101         return 1;
1102 }
1103
1104 void
1105 channel_input_ieof(int type, int plen)
1106 {
1107         int id;
1108         Channel *c;
1109
1110         packet_integrity_check(plen, 4, type);
1111
1112         id = packet_get_int();
1113         c = channel_lookup(id);
1114         if (c == NULL)
1115                 packet_disconnect("Received ieof for nonexistent channel %d.", id);
1116         chan_rcvd_ieof(c);
1117 }
1118
1119 void
1120 channel_input_close(int type, int plen)
1121 {
1122         int id;
1123         Channel *c;
1124
1125         packet_integrity_check(plen, 4, type);
1126
1127         id = packet_get_int();
1128         c = channel_lookup(id);
1129         if (c == NULL)
1130                 packet_disconnect("Received close for nonexistent channel %d.", id);
1131
1132         /*
1133          * Send a confirmation that we have closed the channel and no more
1134          * data is coming for it.
1135          */
1136         packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1137         packet_put_int(c->remote_id);
1138         packet_send();
1139
1140         /*
1141          * If the channel is in closed state, we have sent a close request,
1142          * and the other side will eventually respond with a confirmation.
1143          * Thus, we cannot free the channel here, because then there would be
1144          * no-one to receive the confirmation.  The channel gets freed when
1145          * the confirmation arrives.
1146          */
1147         if (c->type != SSH_CHANNEL_CLOSED) {
1148                 /*
1149                  * Not a closed channel - mark it as draining, which will
1150                  * cause it to be freed later.
1151                  */
1152                 buffer_consume(&c->input, buffer_len(&c->input));
1153                 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1154         }
1155 }
1156
1157 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1158 void
1159 channel_input_oclose(int type, int plen)
1160 {
1161         int id = packet_get_int();
1162         Channel *c = channel_lookup(id);
1163         packet_integrity_check(plen, 4, type);
1164         if (c == NULL)
1165                 packet_disconnect("Received oclose for nonexistent channel %d.", id);
1166         chan_rcvd_oclose(c);
1167 }
1168
1169 void
1170 channel_input_close_confirmation(int type, int plen)
1171 {
1172         int id = packet_get_int();
1173         Channel *c = channel_lookup(id);
1174
1175         packet_done();
1176         if (c == NULL)
1177                 packet_disconnect("Received close confirmation for "
1178                     "out-of-range channel %d.", id);
1179         if (c->type != SSH_CHANNEL_CLOSED)
1180                 packet_disconnect("Received close confirmation for "
1181                     "non-closed channel %d (type %d).", id, c->type);
1182         channel_free(c->self);
1183 }
1184
1185 void
1186 channel_input_open_confirmation(int type, int plen)
1187 {
1188         int id, remote_id;
1189         Channel *c;
1190
1191         if (!compat20)
1192                 packet_integrity_check(plen, 4 + 4, type);
1193
1194         id = packet_get_int();
1195         c = channel_lookup(id);
1196
1197         if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1198                 packet_disconnect("Received open confirmation for "
1199                     "non-opening channel %d.", id);
1200         remote_id = packet_get_int();
1201         /* Record the remote channel number and mark that the channel is now open. */
1202         c->remote_id = remote_id;
1203         c->type = SSH_CHANNEL_OPEN;
1204
1205         if (compat20) {
1206                 c->remote_window = packet_get_int();
1207                 c->remote_maxpacket = packet_get_int();
1208                 packet_done();
1209                 if (c->cb_fn != NULL && c->cb_event == type) {
1210                         debug("callback start");
1211                         c->cb_fn(c->self, c->cb_arg);
1212                         debug("callback done");
1213                 }
1214                 debug("channel %d: open confirm rwindow %d rmax %d", c->self,
1215                     c->remote_window, c->remote_maxpacket);
1216         }
1217 }
1218
1219 void
1220 channel_input_open_failure(int type, int plen)
1221 {
1222         int id;
1223         Channel *c;
1224
1225         if (!compat20)
1226                 packet_integrity_check(plen, 4, type);
1227
1228         id = packet_get_int();
1229         c = channel_lookup(id);
1230
1231         if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1232                 packet_disconnect("Received open failure for "
1233                     "non-opening channel %d.", id);
1234         if (compat20) {
1235                 int reason = packet_get_int();
1236                 char *msg  = packet_get_string(NULL);
1237                 char *lang  = packet_get_string(NULL);
1238                 log("channel_open_failure: %d: reason %d: %s", id, reason, msg);
1239                 packet_done();
1240                 xfree(msg);
1241                 xfree(lang);
1242         }
1243         /* Free the channel.  This will also close the socket. */
1244         channel_free(id);
1245 }
1246
1247 void
1248 channel_input_channel_request(int type, int plen)
1249 {
1250         int id;
1251         Channel *c;
1252
1253         id = packet_get_int();
1254         c = channel_lookup(id);
1255
1256         if (c == NULL ||
1257             (c->type != SSH_CHANNEL_OPEN && c->type != SSH_CHANNEL_LARVAL))
1258                 packet_disconnect("Received request for "
1259                     "non-open channel %d.", id);
1260         if (c->cb_fn != NULL && c->cb_event == type) {
1261                 debug("callback start");
1262                 c->cb_fn(c->self, c->cb_arg);
1263                 debug("callback done");
1264         } else {
1265                 char *service = packet_get_string(NULL);
1266                 debug("channel: %d rcvd request for %s", c->self, service);
1267 debug("cb_fn %p cb_event %d", c->cb_fn , c->cb_event);
1268                 xfree(service);
1269         }
1270 }
1271
1272 void
1273 channel_input_window_adjust(int type, int plen)
1274 {
1275         Channel *c;
1276         int id, adjust;
1277
1278         if (!compat20)
1279                 return;
1280
1281         /* Get the channel number and verify it. */
1282         id = packet_get_int();
1283         c = channel_lookup(id);
1284
1285         if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
1286                 log("Received window adjust for "
1287                     "non-open channel %d.", id);
1288                 return;
1289         }
1290         adjust = packet_get_int();
1291         packet_done();
1292         debug("channel %d: rcvd adjust %d", id, adjust);
1293         c->remote_window += adjust;
1294 }
1295
1296 /*
1297  * Stops listening for channels, and removes any unix domain sockets that we
1298  * might have.
1299  */
1300
1301 void
1302 channel_stop_listening()
1303 {
1304         int i;
1305         for (i = 0; i < channels_alloc; i++) {
1306                 switch (channels[i].type) {
1307                 case SSH_CHANNEL_AUTH_SOCKET:
1308                         close(channels[i].sock);
1309                         remove(channels[i].path);
1310                         channel_free(i);
1311                         break;
1312                 case SSH_CHANNEL_PORT_LISTENER:
1313                 case SSH_CHANNEL_X11_LISTENER:
1314                         close(channels[i].sock);
1315                         channel_free(i);
1316                         break;
1317                 default:
1318                         break;
1319                 }
1320         }
1321 }
1322
1323 /*
1324  * Closes the sockets/fds of all channels.  This is used to close extra file
1325  * descriptors after a fork.
1326  */
1327
1328 void
1329 channel_close_all()
1330 {
1331         int i;
1332         for (i = 0; i < channels_alloc; i++)
1333                 if (channels[i].type != SSH_CHANNEL_FREE)
1334                         channel_close_fds(&channels[i]);
1335 }
1336
1337 /* Returns the maximum file descriptor number used by the channels. */
1338
1339 int
1340 channel_max_fd()
1341 {
1342         return channel_max_fd_value;
1343 }
1344
1345 /* Returns true if any channel is still open. */
1346
1347 int
1348 channel_still_open()
1349 {
1350         unsigned int i;
1351         for (i = 0; i < channels_alloc; i++)
1352                 switch (channels[i].type) {
1353                 case SSH_CHANNEL_FREE:
1354                 case SSH_CHANNEL_X11_LISTENER:
1355                 case SSH_CHANNEL_PORT_LISTENER:
1356                 case SSH_CHANNEL_CLOSED:
1357                 case SSH_CHANNEL_AUTH_SOCKET:
1358                         continue;
1359                 case SSH_CHANNEL_LARVAL:
1360                         if (!compat20)
1361                                 fatal("cannot happen: SSH_CHANNEL_LARVAL");
1362                         continue;
1363                 case SSH_CHANNEL_OPENING:
1364                 case SSH_CHANNEL_OPEN:
1365                 case SSH_CHANNEL_X11_OPEN:
1366                         return 1;
1367                 case SSH_CHANNEL_INPUT_DRAINING:
1368                 case SSH_CHANNEL_OUTPUT_DRAINING:
1369                         if (!compat13)
1370                                 fatal("cannot happen: OUT_DRAIN");
1371                         return 1;
1372                 default:
1373                         fatal("channel_still_open: bad channel type %d", channels[i].type);
1374                         /* NOTREACHED */
1375                 }
1376         return 0;
1377 }
1378
1379 /*
1380  * Returns a message describing the currently open forwarded connections,
1381  * suitable for sending to the client.  The message contains crlf pairs for
1382  * newlines.
1383  */
1384
1385 char *
1386 channel_open_message()
1387 {
1388         Buffer buffer;
1389         int i;
1390         char buf[512], *cp;
1391
1392         buffer_init(&buffer);
1393         snprintf(buf, sizeof buf, "The following connections are open:\r\n");
1394         buffer_append(&buffer, buf, strlen(buf));
1395         for (i = 0; i < channels_alloc; i++) {
1396                 Channel *c = &channels[i];
1397                 switch (c->type) {
1398                 case SSH_CHANNEL_FREE:
1399                 case SSH_CHANNEL_X11_LISTENER:
1400                 case SSH_CHANNEL_PORT_LISTENER:
1401                 case SSH_CHANNEL_CLOSED:
1402                 case SSH_CHANNEL_AUTH_SOCKET:
1403                         continue;
1404                 case SSH_CHANNEL_LARVAL:
1405                 case SSH_CHANNEL_OPENING:
1406                 case SSH_CHANNEL_OPEN:
1407                 case SSH_CHANNEL_X11_OPEN:
1408                 case SSH_CHANNEL_INPUT_DRAINING:
1409                 case SSH_CHANNEL_OUTPUT_DRAINING:
1410                         snprintf(buf, sizeof buf, "  #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
1411                             c->self, c->remote_name,
1412                             c->type, c->remote_id,
1413                             c->istate, buffer_len(&c->input),
1414                             c->ostate, buffer_len(&c->output),
1415                             c->rfd, c->wfd);
1416                         buffer_append(&buffer, buf, strlen(buf));
1417                         continue;
1418                 default:
1419                         fatal("channel_open_message: bad channel type %d", c->type);
1420                         /* NOTREACHED */
1421                 }
1422         }
1423         buffer_append(&buffer, "\0", 1);
1424         cp = xstrdup(buffer_ptr(&buffer));
1425         buffer_free(&buffer);
1426         return cp;
1427 }
1428
1429 /*
1430  * Initiate forwarding of connections to local port "port" through the secure
1431  * channel to host:port from remote side.
1432  */
1433
1434 void
1435 channel_request_local_forwarding(u_short port, const char *host,
1436                                  u_short host_port, int gateway_ports)
1437 {
1438         int success, ch, sock, on = 1;
1439         struct addrinfo hints, *ai, *aitop;
1440         char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1441         struct linger linger;
1442
1443         if (strlen(host) > sizeof(channels[0].path) - 1)
1444                 packet_disconnect("Forward host name too long.");
1445
1446         /*
1447          * getaddrinfo returns a loopback address if the hostname is
1448          * set to NULL and hints.ai_flags is not AI_PASSIVE
1449          */
1450         memset(&hints, 0, sizeof(hints));
1451         hints.ai_family = IPv4or6;
1452         hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
1453         hints.ai_socktype = SOCK_STREAM;
1454         snprintf(strport, sizeof strport, "%d", port);
1455         if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
1456                 packet_disconnect("getaddrinfo: fatal error");
1457
1458         success = 0;
1459         for (ai = aitop; ai; ai = ai->ai_next) {
1460                 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1461                         continue;
1462                 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1463                     strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1464                         error("channel_request_local_forwarding: getnameinfo failed");
1465                         continue;
1466                 }
1467                 /* Create a port to listen for the host. */
1468                 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1469                 if (sock < 0) {
1470                         /* this is no error since kernel may not support ipv6 */
1471                         verbose("socket: %.100s", strerror(errno));
1472                         continue;
1473                 }
1474                 /*
1475                  * Set socket options.  We would like the socket to disappear
1476                  * as soon as it has been closed for whatever reason.
1477                  */
1478                 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
1479                 linger.l_onoff = 1;
1480                 linger.l_linger = 5;
1481                 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
1482                 debug("Local forwarding listening on %s port %s.", ntop, strport);
1483
1484                 /* Bind the socket to the address. */
1485                 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1486                         /* address can be in use ipv6 address is already bound */
1487                         if (!ai->ai_next)
1488                                 error("bind: %.100s", strerror(errno));
1489                         else
1490                                 verbose("bind: %.100s", strerror(errno));
1491                                 
1492                         close(sock);
1493                         continue;
1494                 }
1495                 /* Start listening for connections on the socket. */
1496                 if (listen(sock, 5) < 0) {
1497                         error("listen: %.100s", strerror(errno));
1498                         close(sock);
1499                         continue;
1500                 }
1501                 /* Allocate a channel number for the socket. */
1502                 ch = channel_new(
1503                     "port listener", SSH_CHANNEL_PORT_LISTENER,
1504                     sock, sock, -1,
1505                     CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1506                     0, xstrdup("port listener"));
1507                 strlcpy(channels[ch].path, host, sizeof(channels[ch].path));
1508                 channels[ch].host_port = host_port;
1509                 channels[ch].listening_port = port;
1510                 success = 1;
1511         }
1512         if (success == 0)
1513                 packet_disconnect("cannot listen port: %d", port);
1514         freeaddrinfo(aitop);
1515 }
1516
1517 /*
1518  * Initiate forwarding of connections to port "port" on remote host through
1519  * the secure channel to host:port from local side.
1520  */
1521
1522 void
1523 channel_request_remote_forwarding(u_short listen_port, const char *host_to_connect,
1524                                   u_short port_to_connect)
1525 {
1526         int payload_len;
1527         /* Record locally that connection to this host/port is permitted. */
1528         if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
1529                 fatal("channel_request_remote_forwarding: too many forwards");
1530
1531         permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
1532         permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
1533         permitted_opens[num_permitted_opens].listen_port = listen_port;
1534         num_permitted_opens++;
1535
1536         /* Send the forward request to the remote side. */
1537         if (compat20) {
1538                 const char *address_to_bind = "0.0.0.0";
1539                 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1540                 packet_put_cstring("tcpip-forward");
1541                 packet_put_char(0);                     /* boolean: want reply */
1542                 packet_put_cstring(address_to_bind);
1543                 packet_put_int(listen_port);
1544         } else {
1545                 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1546                 packet_put_int(listen_port);
1547                 packet_put_cstring(host_to_connect);
1548                 packet_put_int(port_to_connect);
1549                 packet_send();
1550                 packet_write_wait();
1551                 /*
1552                  * Wait for response from the remote side.  It will send a disconnect
1553                  * message on failure, and we will never see it here.
1554                  */
1555                 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1556         }
1557 }
1558
1559 /*
1560  * This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
1561  * listening for the port, and sends back a success reply (or disconnect
1562  * message if there was an error).  This never returns if there was an error.
1563  */
1564
1565 void
1566 channel_input_port_forward_request(int is_root, int gateway_ports)
1567 {
1568         u_short port, host_port;
1569         char *hostname;
1570
1571         /* Get arguments from the packet. */
1572         port = packet_get_int();
1573         hostname = packet_get_string(NULL);
1574         host_port = packet_get_int();
1575
1576         /*
1577          * Check that an unprivileged user is not trying to forward a
1578          * privileged port.
1579          */
1580         if (port < IPPORT_RESERVED && !is_root)
1581                 packet_disconnect("Requested forwarding of port %d but user is not root.",
1582                                   port);
1583         /*
1584          * Initiate forwarding,
1585          */
1586         channel_request_local_forwarding(port, hostname, host_port, gateway_ports);
1587
1588         /* Free the argument string. */
1589         xfree(hostname);
1590 }
1591
1592 /* XXX move to aux.c */
1593 int
1594 channel_connect_to(const char *host, u_short host_port)
1595 {
1596         struct addrinfo hints, *ai, *aitop;
1597         char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1598         int gaierr;
1599         int sock = -1;
1600
1601         memset(&hints, 0, sizeof(hints));
1602         hints.ai_family = IPv4or6;
1603         hints.ai_socktype = SOCK_STREAM;
1604         snprintf(strport, sizeof strport, "%d", host_port);
1605         if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
1606                 error("%.100s: unknown host (%s)", host, gai_strerror(gaierr));
1607                 return -1;
1608         }
1609         for (ai = aitop; ai; ai = ai->ai_next) {
1610                 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1611                         continue;
1612                 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1613                     strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1614                         error("channel_connect_to: getnameinfo failed");
1615                         continue;
1616                 }
1617                 /* Create the socket. */
1618                 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1619                 if (sock < 0) {
1620                         error("socket: %.100s", strerror(errno));
1621                         continue;
1622                 }
1623                 /* Connect to the host/port. */
1624                 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1625                         error("connect %.100s port %s: %.100s", ntop, strport,
1626                             strerror(errno));
1627                         close(sock);
1628                         continue;       /* fail -- try next */  
1629                 }
1630                 break; /* success */
1631
1632         }
1633         freeaddrinfo(aitop);
1634         if (!ai) {
1635                 error("connect %.100s port %d: failed.", host, host_port);      
1636                 return -1;
1637         }
1638         /* success */
1639         return sock;
1640 }
1641
1642 /*
1643  * This is called after receiving PORT_OPEN message.  This attempts to
1644  * connect to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION
1645  * or CHANNEL_OPEN_FAILURE.
1646  */
1647
1648 void
1649 channel_input_port_open(int type, int plen)
1650 {
1651         u_short host_port;
1652         char *host, *originator_string;
1653         int remote_channel, sock = -1, newch, i, denied;
1654         unsigned int host_len, originator_len;
1655
1656         /* Get remote channel number. */
1657         remote_channel = packet_get_int();
1658
1659         /* Get host name to connect to. */
1660         host = packet_get_string(&host_len);
1661
1662         /* Get port to connect to. */
1663         host_port = packet_get_int();
1664
1665         /* Get remote originator name. */
1666         if (have_hostname_in_open) {
1667                 originator_string = packet_get_string(&originator_len);
1668                 originator_len += 4;    /* size of packet_int */
1669         } else {
1670                 originator_string = xstrdup("unknown (remote did not supply name)");
1671                 originator_len = 0;     /* no originator supplied */
1672         }
1673
1674         packet_integrity_check(plen,
1675             4 + 4 + host_len + 4 + originator_len, SSH_MSG_PORT_OPEN);
1676
1677         /* Check if opening that port is permitted. */
1678         denied = 0;
1679         if (!all_opens_permitted) {
1680                 /* Go trough all permitted ports. */
1681                 for (i = 0; i < num_permitted_opens; i++)
1682                         if (permitted_opens[i].port_to_connect == host_port &&
1683                             strcmp(permitted_opens[i].host_to_connect, host) == 0)
1684                                 break;
1685
1686                 /* Check if we found the requested port among those permitted. */
1687                 if (i >= num_permitted_opens) {
1688                         /* The port is not permitted. */
1689                         log("Received request to connect to %.100s:%d, but the request was denied.",
1690                             host, host_port);
1691                         denied = 1;
1692                 }
1693         }
1694         sock = denied ? -1 : channel_connect_to(host, host_port);
1695         if (sock > 0) {
1696                 /* Allocate a channel for this connection. */
1697                 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, originator_string);
1698                 channels[newch].remote_id = remote_channel;
1699
1700                 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1701                 packet_put_int(remote_channel);
1702                 packet_put_int(newch);
1703                 packet_send();
1704         } else {
1705                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1706                 packet_put_int(remote_channel);
1707                 packet_send();
1708         }
1709         xfree(host);
1710 }
1711
1712 /*
1713  * Creates an internet domain socket for listening for X11 connections.
1714  * Returns a suitable value for the DISPLAY variable, or NULL if an error
1715  * occurs.
1716  */
1717
1718 #define NUM_SOCKS       10
1719
1720 char *
1721 x11_create_display_inet(int screen_number, int x11_display_offset)
1722 {
1723         int display_number, sock;
1724         u_short port;
1725         struct addrinfo hints, *ai, *aitop;
1726         char strport[NI_MAXSERV];
1727         int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
1728         char display[512];
1729         char hostname[MAXHOSTNAMELEN];
1730
1731         for (display_number = x11_display_offset;
1732              display_number < MAX_DISPLAYS;
1733              display_number++) {
1734                 port = 6000 + display_number;
1735                 memset(&hints, 0, sizeof(hints));
1736                 hints.ai_family = IPv4or6;
1737                 hints.ai_flags = AI_PASSIVE;            /* XXX loopback only ? */
1738                 hints.ai_socktype = SOCK_STREAM;
1739                 snprintf(strport, sizeof strport, "%d", port);
1740                 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
1741                         error("getaddrinfo: %.100s", gai_strerror(gaierr));
1742                         return NULL;
1743                 }
1744                 for (ai = aitop; ai; ai = ai->ai_next) {
1745                         if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1746                                 continue;
1747                         sock = socket(ai->ai_family, SOCK_STREAM, 0);
1748                         if (sock < 0) {
1749                                 if (errno != EINVAL) {
1750                                         error("socket: %.100s", strerror(errno));
1751                                         return NULL;
1752                                 } else {
1753                                         debug("Socket family %d not supported [X11 disp create]", ai->ai_family);
1754                                         continue;
1755                                 }
1756                         }
1757                         if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1758                                 debug("bind port %d: %.100s", port, strerror(errno));
1759                                 shutdown(sock, SHUT_RDWR);
1760                                 close(sock);
1761
1762                                 if (ai->ai_next)
1763                                         continue;
1764
1765                                 for (n = 0; n < num_socks; n++) {
1766                                         shutdown(socks[n], SHUT_RDWR);
1767                                         close(socks[n]);
1768                                 }
1769                                 num_socks = 0;
1770                                 break;
1771                         }
1772                         socks[num_socks++] = sock;
1773 #ifndef DONT_TRY_OTHER_AF
1774                         if (num_socks == NUM_SOCKS)
1775                                 break;
1776 #else
1777                         break;
1778 #endif
1779                 }
1780                 if (num_socks > 0)
1781                         break;
1782         }
1783         if (display_number >= MAX_DISPLAYS) {
1784                 error("Failed to allocate internet-domain X11 display socket.");
1785                 return NULL;
1786         }
1787         /* Start listening for connections on the socket. */
1788         for (n = 0; n < num_socks; n++) {
1789                 sock = socks[n];
1790                 if (listen(sock, 5) < 0) {
1791                         error("listen: %.100s", strerror(errno));
1792                         shutdown(sock, SHUT_RDWR);
1793                         close(sock);
1794                         return NULL;
1795                 }
1796         }
1797
1798         /* Set up a suitable value for the DISPLAY variable. */
1799
1800         if (gethostname(hostname, sizeof(hostname)) < 0)
1801                 fatal("gethostname: %.100s", strerror(errno));
1802
1803 #ifdef IPADDR_IN_DISPLAY
1804         /* 
1805          * HPUX detects the local hostname in the DISPLAY variable and tries
1806          * to set up a shared memory connection to the server, which it
1807          * incorrectly supposes to be local.
1808          *
1809          * The workaround - as used in later $$H and other programs - is
1810          * is to set display to the host's IP address.
1811          */
1812         {
1813                 struct hostent *he;
1814                 struct in_addr my_addr;
1815
1816                 he = gethostbyname(hostname);
1817                 if (he == NULL) {
1818                         error("[X11-broken-fwd-hostname-workaround] Could not get "
1819                                 "IP address for hostname %s.", hostname);
1820
1821                         packet_send_debug("[X11-broken-fwd-hostname-workaround]"
1822                                 "Could not get IP address for hostname %s.", hostname);
1823
1824                         shutdown(sock, SHUT_RDWR);
1825                         close(sock);
1826
1827                         return NULL;
1828                 }
1829
1830                 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
1831
1832                 /* Set DISPLAY to <ip address>:screen.display */
1833                 snprintf(display, sizeof(display), "%.50s:%d.%d", inet_ntoa(my_addr), 
1834                         display_number, screen_number);
1835         }
1836 #else /* IPADDR_IN_DISPLAY */
1837         /* Just set DISPLAY to hostname:screen.display */
1838         snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
1839                 display_number, screen_number);
1840 #endif /* IPADDR_IN_DISPLAY */
1841
1842         /* Allocate a channel for each socket. */
1843         for (n = 0; n < num_socks; n++) {
1844                 sock = socks[n];
1845                 (void) channel_new("x11 listener",
1846                     SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
1847                     CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
1848                     0, xstrdup("X11 inet listener"));
1849         }
1850
1851         /* Return a suitable value for the DISPLAY environment variable. */
1852         return xstrdup(display);
1853 }
1854
1855 #ifndef X_UNIX_PATH
1856 #define X_UNIX_PATH "/tmp/.X11-unix/X"
1857 #endif
1858
1859 static
1860 int
1861 connect_local_xsocket(unsigned int dnr)
1862 {
1863         static const char *const x_sockets[] = {
1864                 X_UNIX_PATH "%u",
1865                 "/var/X/.X11-unix/X" "%u",
1866                 "/usr/spool/sockets/X11/" "%u",
1867                 NULL
1868         };
1869         int sock;
1870         struct sockaddr_un addr;
1871         const char *const * path;
1872
1873         for (path = x_sockets; *path; ++path) {
1874                 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1875                 if (sock < 0)
1876                         error("socket: %.100s", strerror(errno));
1877                 memset(&addr, 0, sizeof(addr));
1878                 addr.sun_family = AF_UNIX;
1879                 snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
1880                 if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
1881                         return sock;
1882                 close(sock);
1883         }
1884         error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
1885         return -1;
1886 }
1887
1888 int
1889 x11_connect_display(void)
1890 {
1891         int display_number, sock = 0;
1892         const char *display;
1893         char buf[1024], *cp;
1894         struct addrinfo hints, *ai, *aitop;
1895         char strport[NI_MAXSERV];
1896         int gaierr;
1897
1898         /* Try to open a socket for the local X server. */
1899         display = getenv("DISPLAY");
1900         if (!display) {
1901                 error("DISPLAY not set.");
1902                 return -1;
1903         }
1904         /*
1905          * Now we decode the value of the DISPLAY variable and make a
1906          * connection to the real X server.
1907          */
1908
1909         /*
1910          * Check if it is a unix domain socket.  Unix domain displays are in
1911          * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
1912          */
1913         if (strncmp(display, "unix:", 5) == 0 ||
1914             display[0] == ':') {
1915                 /* Connect to the unix domain socket. */
1916                 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
1917                         error("Could not parse display number from DISPLAY: %.100s",
1918                               display);
1919                         return -1;
1920                 }
1921                 /* Create a socket. */
1922                 sock = connect_local_xsocket(display_number);
1923                 if (sock < 0)
1924                         return -1;
1925
1926                 /* OK, we now have a connection to the display. */
1927                 return sock;
1928         }
1929         /*
1930          * Connect to an inet socket.  The DISPLAY value is supposedly
1931          * hostname:d[.s], where hostname may also be numeric IP address.
1932          */
1933         strncpy(buf, display, sizeof(buf));
1934         buf[sizeof(buf) - 1] = 0;
1935         cp = strchr(buf, ':');
1936         if (!cp) {
1937                 error("Could not find ':' in DISPLAY: %.100s", display);
1938                 return -1;
1939         }
1940         *cp = 0;
1941         /* buf now contains the host name.  But first we parse the display number. */
1942         if (sscanf(cp + 1, "%d", &display_number) != 1) {
1943                 error("Could not parse display number from DISPLAY: %.100s",
1944                       display);
1945                 return -1;
1946         }
1947
1948         /* Look up the host address */
1949         memset(&hints, 0, sizeof(hints));
1950         hints.ai_family = IPv4or6;
1951         hints.ai_socktype = SOCK_STREAM;
1952         snprintf(strport, sizeof strport, "%d", 6000 + display_number);
1953         if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
1954                 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
1955                 return -1;
1956         }
1957         for (ai = aitop; ai; ai = ai->ai_next) {
1958                 /* Create a socket. */
1959                 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1960                 if (sock < 0) {
1961                         debug("socket: %.100s", strerror(errno));
1962                         continue;
1963                 }
1964                 /* Connect it to the display. */
1965                 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1966                         debug("connect %.100s port %d: %.100s", buf,
1967                             6000 + display_number, strerror(errno));
1968                         close(sock);
1969                         continue;
1970                 }
1971                 /* Success */
1972                 break;
1973         }
1974         freeaddrinfo(aitop);
1975         if (!ai) {
1976                 error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
1977                     strerror(errno));
1978                 return -1;
1979         }
1980         return sock;
1981 }
1982
1983 /*
1984  * This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
1985  * the remote channel number.  We should do whatever we want, and respond
1986  * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
1987  */
1988
1989 void
1990 x11_input_open(int type, int plen)
1991 {
1992         int remote_channel, sock = 0, newch;
1993         char *remote_host;
1994         unsigned int remote_len;
1995
1996         /* Get remote channel number. */
1997         remote_channel = packet_get_int();
1998
1999         /* Get remote originator name. */
2000         if (have_hostname_in_open) {
2001                 remote_host = packet_get_string(&remote_len);
2002                 remote_len += 4;
2003         } else {
2004                 remote_host = xstrdup("unknown (remote did not supply name)");
2005                 remote_len = 0;
2006         }
2007
2008         debug("Received X11 open request.");
2009         packet_integrity_check(plen, 4 + remote_len, SSH_SMSG_X11_OPEN);
2010
2011         /* Obtain a connection to the real X display. */
2012         sock = x11_connect_display();
2013         if (sock == -1) {
2014                 /* Send refusal to the remote host. */
2015                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2016                 packet_put_int(remote_channel);
2017                 packet_send();
2018         } else {
2019                 /* Allocate a channel for this connection. */
2020                 newch = channel_allocate(
2021                      (x11_saved_proto == NULL) ?
2022                      SSH_CHANNEL_OPEN : SSH_CHANNEL_X11_OPEN,
2023                      sock, remote_host);
2024                 channels[newch].remote_id = remote_channel;
2025
2026                 /* Send a confirmation to the remote host. */
2027                 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2028                 packet_put_int(remote_channel);
2029                 packet_put_int(newch);
2030                 packet_send();
2031         }
2032 }
2033
2034 /*
2035  * Requests forwarding of X11 connections, generates fake authentication
2036  * data, and enables authentication spoofing.
2037  */
2038
2039 void
2040 x11_request_forwarding_with_spoofing(int client_session_id,
2041     const char *proto, const char *data)
2042 {
2043         unsigned int data_len = (unsigned int) strlen(data) / 2;
2044         unsigned int i, value;
2045         char *new_data;
2046         int screen_number;
2047         const char *cp;
2048         u_int32_t rand = 0;
2049
2050         cp = getenv("DISPLAY");
2051         if (cp)
2052                 cp = strchr(cp, ':');
2053         if (cp)
2054                 cp = strchr(cp, '.');
2055         if (cp)
2056                 screen_number = atoi(cp + 1);
2057         else
2058                 screen_number = 0;
2059
2060         /* Save protocol name. */
2061         x11_saved_proto = xstrdup(proto);
2062
2063         /*
2064          * Extract real authentication data and generate fake data of the
2065          * same length.
2066          */
2067         x11_saved_data = xmalloc(data_len);
2068         x11_fake_data = xmalloc(data_len);
2069         for (i = 0; i < data_len; i++) {
2070                 if (sscanf(data + 2 * i, "%2x", &value) != 1)
2071                         fatal("x11_request_forwarding: bad authentication data: %.100s", data);
2072                 if (i % 4 == 0)
2073                         rand = arc4random();
2074                 x11_saved_data[i] = value;
2075                 x11_fake_data[i] = rand & 0xff;
2076                 rand >>= 8;
2077         }
2078         x11_saved_data_len = data_len;
2079         x11_fake_data_len = data_len;
2080
2081         /* Convert the fake data into hex. */
2082         new_data = xmalloc(2 * data_len + 1);
2083         for (i = 0; i < data_len; i++)
2084                 sprintf(new_data + 2 * i, "%02x", (unsigned char) x11_fake_data[i]);
2085
2086         /* Send the request packet. */
2087         if (compat20) {
2088                 channel_request_start(client_session_id, "x11-req", 0);
2089                 packet_put_char(0);     /* XXX bool single connection */
2090         } else {
2091                 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
2092         }
2093         packet_put_cstring(proto);
2094         packet_put_cstring(new_data);
2095         packet_put_int(screen_number);
2096         packet_send();
2097         packet_write_wait();
2098         xfree(new_data);
2099 }
2100
2101 /* Sends a message to the server to request authentication fd forwarding. */
2102
2103 void
2104 auth_request_forwarding()
2105 {
2106         packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
2107         packet_send();
2108         packet_write_wait();
2109 }
2110
2111 /*
2112  * Returns the name of the forwarded authentication socket.  Returns NULL if
2113  * there is no forwarded authentication socket.  The returned value points to
2114  * a static buffer.
2115  */
2116
2117 char *
2118 auth_get_socket_name()
2119 {
2120         return channel_forwarded_auth_socket_name;
2121 }
2122
2123 /* removes the agent forwarding socket */
2124
2125 void
2126 cleanup_socket(void)
2127 {
2128         remove(channel_forwarded_auth_socket_name);
2129         rmdir(channel_forwarded_auth_socket_dir);
2130 }
2131
2132 /*
2133  * This if called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
2134  * This starts forwarding authentication requests.
2135  */
2136
2137 void
2138 auth_input_request_forwarding(struct passwd * pw)
2139 {
2140         int sock, newch;
2141         struct sockaddr_un sunaddr;
2142
2143         if (auth_get_socket_name() != NULL)
2144                 fatal("Protocol error: authentication forwarding requested twice.");
2145
2146         /* Temporarily drop privileged uid for mkdir/bind. */
2147         temporarily_use_uid(pw->pw_uid);
2148
2149         /* Allocate a buffer for the socket name, and format the name. */
2150         channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
2151         channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
2152         strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
2153
2154         /* Create private directory for socket */
2155         if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL)
2156                 packet_disconnect("mkdtemp: %.100s", strerror(errno));
2157         snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME, "%s/agent.%d",
2158                  channel_forwarded_auth_socket_dir, (int) getpid());
2159
2160         if (atexit(cleanup_socket) < 0) {
2161                 int saved = errno;
2162                 cleanup_socket();
2163                 packet_disconnect("socket: %.100s", strerror(saved));
2164         }
2165         /* Create the socket. */
2166         sock = socket(AF_UNIX, SOCK_STREAM, 0);
2167         if (sock < 0)
2168                 packet_disconnect("socket: %.100s", strerror(errno));
2169
2170         /* Bind it to the name. */
2171         memset(&sunaddr, 0, sizeof(sunaddr));
2172         sunaddr.sun_family = AF_UNIX;
2173         strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
2174                 sizeof(sunaddr.sun_path));
2175
2176         if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
2177                 packet_disconnect("bind: %.100s", strerror(errno));
2178
2179         /* Restore the privileged uid. */
2180         restore_uid();
2181
2182         /* Start listening on the socket. */
2183         if (listen(sock, 5) < 0)
2184                 packet_disconnect("listen: %.100s", strerror(errno));
2185
2186         /* Allocate a channel for the authentication agent socket. */
2187         newch = channel_allocate(SSH_CHANNEL_AUTH_SOCKET, sock,
2188                                  xstrdup("auth socket"));
2189         strlcpy(channels[newch].path, channel_forwarded_auth_socket_name,
2190             sizeof(channels[newch].path));
2191 }
2192
2193 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
2194
2195 void
2196 auth_input_open_request(int type, int plen)
2197 {
2198         int remch, sock, newch;
2199         char *dummyname;
2200
2201         packet_integrity_check(plen, 4, type);
2202
2203         /* Read the remote channel number from the message. */
2204         remch = packet_get_int();
2205
2206         /*
2207          * Get a connection to the local authentication agent (this may again
2208          * get forwarded).
2209          */
2210         sock = ssh_get_authentication_socket();
2211
2212         /*
2213          * If we could not connect the agent, send an error message back to
2214          * the server. This should never happen unless the agent dies,
2215          * because authentication forwarding is only enabled if we have an
2216          * agent.
2217          */
2218         if (sock < 0) {
2219                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2220                 packet_put_int(remch);
2221                 packet_send();
2222                 return;
2223         }
2224         debug("Forwarding authentication connection.");
2225
2226         /*
2227          * Dummy host name.  This will be freed when the channel is freed; it
2228          * will still be valid in the packet_put_string below since the
2229          * channel cannot yet be freed at that point.
2230          */
2231         dummyname = xstrdup("authentication agent connection");
2232
2233         newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
2234         channels[newch].remote_id = remch;
2235
2236         /* Send a confirmation to the remote host. */
2237         packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2238         packet_put_int(remch);
2239         packet_put_int(newch);
2240         packet_send();
2241 }
2242
2243 void
2244 channel_start_open(int id)
2245 {
2246         Channel *c = channel_lookup(id);
2247         if (c == NULL) {
2248                 log("channel_open: %d: bad id", id);
2249                 return;
2250         }
2251         debug("send channel open %d", id);
2252         packet_start(SSH2_MSG_CHANNEL_OPEN);
2253         packet_put_cstring(c->ctype);
2254         packet_put_int(c->self);
2255         packet_put_int(c->local_window);
2256         packet_put_int(c->local_maxpacket);
2257 }
2258 void
2259 channel_open(int id)
2260 {
2261         /* XXX REMOVE ME */
2262         channel_start_open(id);
2263         packet_send();
2264 }
2265 void
2266 channel_request(int id, char *service, int wantconfirm)
2267 {
2268         channel_request_start(id, service, wantconfirm);
2269         packet_send();
2270         debug("channel request %d: %s", id, service) ;
2271 }
2272 void
2273 channel_request_start(int id, char *service, int wantconfirm)
2274 {
2275         Channel *c = channel_lookup(id);
2276         if (c == NULL) {
2277                 log("channel_request: %d: bad id", id);
2278                 return;
2279         }
2280         packet_start(SSH2_MSG_CHANNEL_REQUEST);
2281         packet_put_int(c->remote_id);
2282         packet_put_cstring(service);
2283         packet_put_char(wantconfirm);
2284 }
2285 void
2286 channel_register_callback(int id, int mtype, channel_callback_fn *fn, void *arg)
2287 {
2288         Channel *c = channel_lookup(id);
2289         if (c == NULL) {
2290                 log("channel_register_callback: %d: bad id", id);
2291                 return;
2292         }
2293         c->cb_event = mtype;
2294         c->cb_fn = fn;
2295         c->cb_arg = arg;
2296 }
2297 void
2298 channel_register_cleanup(int id, channel_callback_fn *fn)
2299 {
2300         Channel *c = channel_lookup(id);
2301         if (c == NULL) {
2302                 log("channel_register_cleanup: %d: bad id", id);
2303                 return;
2304         }
2305         c->dettach_user = fn;
2306 }
2307 void
2308 channel_cancel_cleanup(int id)
2309 {
2310         Channel *c = channel_lookup(id);
2311         if (c == NULL) {
2312                 log("channel_cancel_cleanup: %d: bad id", id);
2313                 return;
2314         }
2315         c->dettach_user = NULL;
2316 }
2317
2318 void
2319 channel_set_fds(int id, int rfd, int wfd, int efd, int extusage)
2320 {
2321         Channel *c = channel_lookup(id);
2322         if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
2323                 fatal("channel_activate for non-larval channel %d.", id);
2324
2325         channel_register_fds(c, rfd, wfd, efd, extusage);
2326         c->type = SSH_CHANNEL_OPEN;
2327         /* XXX window size? */
2328         c->local_window = c->local_window_max = c->local_maxpacket/2;
2329         packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2330         packet_put_int(c->remote_id);
2331         packet_put_int(c->local_window);
2332         packet_send();
2333 }
This page took 0.232925 seconds and 5 git commands to generate.