]> andersk Git - openssh.git/blob - channels.c
- markus@cvs.openbsd.org 2001/05/28 23:14:49
[openssh.git] / channels.c
1 /*
2  * Author: Tatu Ylonen <ylo@cs.hut.fi>
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  * This file contains functions for generic socket connection forwarding.
6  * There is also code for initiating connection forwarding for X11 connections,
7  * arbitrary tcp/ip connections, and the authentication agent connection.
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  *
15  *
16  * SSH2 support added by Markus Friedl.
17  * Copyright (c) 1999,2000 Markus Friedl.  All rights reserved.
18  * Copyright (c) 1999 Dug Song.  All rights reserved.
19  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
20  *
21  * Redistribution and use in source and binary forms, with or without
22  * modification, are permitted provided that the following conditions
23  * are met:
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  */
41
42 #include "includes.h"
43 RCSID("$OpenBSD: channels.c,v 1.118 2001/05/28 23:14:49 markus Exp $");
44
45 #include <openssl/rsa.h>
46 #include <openssl/dsa.h>
47
48 #include "ssh.h"
49 #include "ssh1.h"
50 #include "ssh2.h"
51 #include "packet.h"
52 #include "xmalloc.h"
53 #include "buffer.h"
54 #include "bufaux.h"
55 #include "uidswap.h"
56 #include "log.h"
57 #include "misc.h"
58 #include "channels.h"
59 #include "nchan.h"
60 #include "compat.h"
61 #include "canohost.h"
62 #include "key.h"
63 #include "authfd.h"
64
65 /* Maximum number of fake X11 displays to try. */
66 #define MAX_DISPLAYS  1000
67
68 /* Max len of agent socket */
69 #define MAX_SOCKET_NAME 100
70
71 /*
72  * Pointer to an array containing all allocated channels.  The array is
73  * dynamically extended as needed.
74  */
75 static Channel **channels = NULL;
76
77 /*
78  * Size of the channel array.  All slots of the array must always be
79  * initialized (at least the type field); unused slots set to NULL
80  */
81 static int channels_alloc = 0;
82
83 /*
84  * Maximum file descriptor value used in any of the channels.  This is
85  * updated in channel_new.
86  */
87 static int channel_max_fd = 0;
88
89 /* Name and directory of socket for authentication agent forwarding. */
90 static char *channel_forwarded_auth_socket_name = NULL;
91 static char *channel_forwarded_auth_socket_dir = NULL;
92
93 /* Saved X11 authentication protocol name. */
94 char *x11_saved_proto = NULL;
95
96 /* Saved X11 authentication data.  This is the real data. */
97 char *x11_saved_data = NULL;
98 u_int x11_saved_data_len = 0;
99
100 /*
101  * Fake X11 authentication data.  This is what the server will be sending us;
102  * we should replace any occurrences of this by the real data.
103  */
104 char *x11_fake_data = NULL;
105 u_int x11_fake_data_len;
106
107 /*
108  * Data structure for storing which hosts are permitted for forward requests.
109  * The local sides of any remote forwards are stored in this array to prevent
110  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
111  * network (which might be behind a firewall).
112  */
113 typedef struct {
114         char *host_to_connect;          /* Connect to 'host'. */
115         u_short port_to_connect;        /* Connect to 'port'. */
116         u_short listen_port;            /* Remote side should listen port number. */
117 } ForwardPermission;
118
119 /* List of all permitted host/port pairs to connect. */
120 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
121 /* Number of permitted host/port pairs in the array. */
122 static int num_permitted_opens = 0;
123 /*
124  * If this is true, all opens are permitted.  This is the case on the server
125  * on which we have to trust the client anyway, and the user could do
126  * anything after logging in anyway.
127  */
128 static int all_opens_permitted = 0;
129
130 /* This is set to true if both sides support SSH_PROTOFLAG_HOST_IN_FWD_OPEN. */
131 static int have_hostname_in_open = 0;
132
133 /* AF_UNSPEC or AF_INET or AF_INET6 */
134 extern int IPv4or6;
135
136 void     port_open_helper(Channel *c, char *rtype);
137
138 /* Sets specific protocol options. */
139
140 void
141 channel_set_options(int hostname_in_open)
142 {
143         have_hostname_in_open = hostname_in_open;
144 }
145
146 /* lookup channel by id */
147
148 Channel *
149 channel_lookup(int id)
150 {
151         Channel *c;
152
153         if (id < 0 || id > channels_alloc) {
154                 log("channel_lookup: %d: bad id", id);
155                 return NULL;
156         }
157         c = channels[id];
158         if (c == NULL) {
159                 log("channel_lookup: %d: bad id: channel free", id);
160                 return NULL;
161         }
162         return c;
163 }
164
165 /*
166  * Register filedescriptors for a channel, used when allocating a channel or
167  * when the channel consumer/producer is ready, e.g. shell exec'd
168  */
169
170 void
171 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
172     int extusage, int nonblock)
173 {
174         /* Update the maximum file descriptor value. */
175         channel_max_fd = MAX(channel_max_fd, rfd);
176         channel_max_fd = MAX(channel_max_fd, wfd);
177         channel_max_fd = MAX(channel_max_fd, efd);
178
179         /* XXX set close-on-exec -markus */
180
181         c->rfd = rfd;
182         c->wfd = wfd;
183         c->sock = (rfd == wfd) ? rfd : -1;
184         c->efd = efd;
185         c->extended_usage = extusage;
186
187         /* XXX ugly hack: nonblock is only set by the server */
188         if (nonblock && isatty(c->rfd)) {
189                 debug("channel %d: rfd %d isatty", c->self, c->rfd);
190                 c->isatty = 1;
191                 if (!isatty(c->wfd)) {
192                         error("channel %d: wfd %d is not a tty?",
193                             c->self, c->wfd);
194                 }
195         } else {
196                 c->isatty = 0;
197         }
198
199         /* enable nonblocking mode */
200         if (nonblock) {
201                 if (rfd != -1)
202                         set_nonblock(rfd);
203                 if (wfd != -1)
204                         set_nonblock(wfd);
205                 if (efd != -1)
206                         set_nonblock(efd);
207         }
208 }
209
210 /*
211  * Allocate a new channel object and set its type and socket. This will cause
212  * remote_name to be freed.
213  */
214
215 Channel *
216 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
217     int window, int maxpack, int extusage, char *remote_name, int nonblock)
218 {
219         int i, found;
220         Channel *c;
221
222         /* Do initial allocation if this is the first call. */
223         if (channels_alloc == 0) {
224                 chan_init();
225                 channels_alloc = 10;
226                 channels = xmalloc(channels_alloc * sizeof(Channel *));
227                 for (i = 0; i < channels_alloc; i++)
228                         channels[i] = NULL;
229                 /*
230                  * Kludge: arrange a call to channel_stop_listening if we
231                  * terminate with fatal().
232                  */
233                 fatal_add_cleanup((void (*) (void *)) channel_stop_listening, NULL);
234         }
235         /* Try to find a free slot where to put the new channel. */
236         for (found = -1, i = 0; i < channels_alloc; i++)
237                 if (channels[i] == NULL) {
238                         /* Found a free slot. */
239                         found = i;
240                         break;
241                 }
242         if (found == -1) {
243                 /* There are no free slots.  Take last+1 slot and expand the array.  */
244                 found = channels_alloc;
245                 channels_alloc += 10;
246                 debug2("channel: expanding %d", channels_alloc);
247                 channels = xrealloc(channels, channels_alloc * sizeof(Channel *));
248                 for (i = found; i < channels_alloc; i++)
249                         channels[i] = NULL;
250         }
251         /* Initialize and return new channel. */
252         c = channels[found] = xmalloc(sizeof(Channel));
253         buffer_init(&c->input);
254         buffer_init(&c->output);
255         buffer_init(&c->extended);
256         chan_init_iostates(c);
257         channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
258         c->self = found;
259         c->type = type;
260         c->ctype = ctype;
261         c->local_window = window;
262         c->local_window_max = window;
263         c->local_consumed = 0;
264         c->local_maxpacket = maxpack;
265         c->remote_id = -1;
266         c->remote_name = remote_name;
267         c->remote_window = 0;
268         c->remote_maxpacket = 0;
269         c->cb_fn = NULL;
270         c->cb_arg = NULL;
271         c->cb_event = 0;
272         c->dettach_user = NULL;
273         c->input_filter = NULL;
274         debug("channel %d: new [%s]", found, remote_name);
275         return c;
276 }
277
278 /* Close all channel fd/socket. */
279
280 void
281 channel_close_fds(Channel *c)
282 {
283         debug3("channel_close_fds: channel %d: r %d w %d e %d",
284             c->self, c->rfd, c->wfd, c->efd);
285
286         if (c->sock != -1) {
287                 close(c->sock);
288                 c->sock = -1;
289         }
290         if (c->rfd != -1) {
291                 close(c->rfd);
292                 c->rfd = -1;
293         }
294         if (c->wfd != -1) {
295                 close(c->wfd);
296                 c->wfd = -1;
297         }
298         if (c->efd != -1) {
299                 close(c->efd);
300                 c->efd = -1;
301         }
302 }
303
304 /* Free the channel and close its fd/socket. */
305
306 void
307 channel_free(Channel *c)
308 {
309         char *s;
310         int i, n;
311
312         for (n = 0, i = 0; i < channels_alloc; i++)
313                 if (channels[i])
314                         n++;
315
316         debug("channel_free: channel %d: (%s) nchannels: %d", c->self,
317             c->remote_name ? c->remote_name : "???", n);
318
319         s = channel_open_message();
320         debug3("channel_free: status: %s", c->self, s);
321         xfree(s);
322
323         if (c->dettach_user != NULL) {
324                 debug("channel_free: channel %d: dettaching channel user", c->self);
325                 c->dettach_user(c->self, NULL);
326         }
327         if (c->sock != -1)
328                 shutdown(c->sock, SHUT_RDWR);
329         channel_close_fds(c);
330         buffer_free(&c->input);
331         buffer_free(&c->output);
332         buffer_free(&c->extended);
333         if (c->remote_name) {
334                 xfree(c->remote_name);
335                 c->remote_name = NULL;
336         }
337         channels[c->self] = NULL;
338         xfree(c);
339 }
340
341 /*
342  * 'channel_pre*' are called just before select() to add any bits relevant to
343  * channels in the select bitmasks.
344  */
345 /*
346  * 'channel_post*': perform any appropriate operations for channels which
347  * have events pending.
348  */
349 typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
350 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
351 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
352
353 void
354 channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
355 {
356         FD_SET(c->sock, readset);
357 }
358
359 void
360 channel_pre_connecting(Channel *c, fd_set * readset, fd_set * writeset)
361 {
362         debug3("channel %d: waiting for connection", c->self);
363         FD_SET(c->sock, writeset);
364 }
365
366 void
367 channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
368 {
369         if (buffer_len(&c->input) < packet_get_maxsize())
370                 FD_SET(c->sock, readset);
371         if (buffer_len(&c->output) > 0)
372                 FD_SET(c->sock, writeset);
373 }
374
375 void
376 channel_pre_open_15(Channel *c, fd_set * readset, fd_set * writeset)
377 {
378         /* test whether sockets are 'alive' for read/write */
379         if (c->istate == CHAN_INPUT_OPEN)
380                 if (buffer_len(&c->input) < packet_get_maxsize())
381                         FD_SET(c->sock, readset);
382         if (c->ostate == CHAN_OUTPUT_OPEN ||
383             c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
384                 if (buffer_len(&c->output) > 0) {
385                         FD_SET(c->sock, writeset);
386                 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
387                         chan_obuf_empty(c);
388                 }
389         }
390 }
391
392 void
393 channel_pre_open_20(Channel *c, fd_set * readset, fd_set * writeset)
394 {
395         if (c->istate == CHAN_INPUT_OPEN &&
396             c->remote_window > 0 &&
397             buffer_len(&c->input) < c->remote_window)
398                 FD_SET(c->rfd, readset);
399         if (c->ostate == CHAN_OUTPUT_OPEN ||
400             c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
401                 if (buffer_len(&c->output) > 0) {
402                         FD_SET(c->wfd, writeset);
403                 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
404                         chan_obuf_empty(c);
405                 }
406         }
407         /** XXX check close conditions, too */
408         if (c->efd != -1) {
409                 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
410                     buffer_len(&c->extended) > 0)
411                         FD_SET(c->efd, writeset);
412                 else if (c->extended_usage == CHAN_EXTENDED_READ &&
413                     buffer_len(&c->extended) < c->remote_window)
414                         FD_SET(c->efd, readset);
415         }
416 }
417
418 void
419 channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
420 {
421         if (buffer_len(&c->input) == 0) {
422                 packet_start(SSH_MSG_CHANNEL_CLOSE);
423                 packet_put_int(c->remote_id);
424                 packet_send();
425                 c->type = SSH_CHANNEL_CLOSED;
426                 debug("channel %d: closing after input drain.", c->self);
427         }
428 }
429
430 void
431 channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
432 {
433         if (buffer_len(&c->output) == 0)
434                 chan_mark_dead(c);
435         else
436                 FD_SET(c->sock, writeset);
437 }
438
439 /*
440  * This is a special state for X11 authentication spoofing.  An opened X11
441  * connection (when authentication spoofing is being done) remains in this
442  * state until the first packet has been completely read.  The authentication
443  * data in that packet is then substituted by the real data if it matches the
444  * fake data, and the channel is put into normal mode.
445  * XXX All this happens at the client side.
446  */
447 int
448 x11_open_helper(Channel *c)
449 {
450         u_char *ucp;
451         u_int proto_len, data_len;
452
453         /* Check if the fixed size part of the packet is in buffer. */
454         if (buffer_len(&c->output) < 12)
455                 return 0;
456
457         /* Parse the lengths of variable-length fields. */
458         ucp = (u_char *) buffer_ptr(&c->output);
459         if (ucp[0] == 0x42) {   /* Byte order MSB first. */
460                 proto_len = 256 * ucp[6] + ucp[7];
461                 data_len = 256 * ucp[8] + ucp[9];
462         } else if (ucp[0] == 0x6c) {    /* Byte order LSB first. */
463                 proto_len = ucp[6] + 256 * ucp[7];
464                 data_len = ucp[8] + 256 * ucp[9];
465         } else {
466                 debug("Initial X11 packet contains bad byte order byte: 0x%x",
467                       ucp[0]);
468                 return -1;
469         }
470
471         /* Check if the whole packet is in buffer. */
472         if (buffer_len(&c->output) <
473             12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
474                 return 0;
475
476         /* Check if authentication protocol matches. */
477         if (proto_len != strlen(x11_saved_proto) ||
478             memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
479                 debug("X11 connection uses different authentication protocol.");
480                 return -1;
481         }
482         /* Check if authentication data matches our fake data. */
483         if (data_len != x11_fake_data_len ||
484             memcmp(ucp + 12 + ((proto_len + 3) & ~3),
485                 x11_fake_data, x11_fake_data_len) != 0) {
486                 debug("X11 auth data does not match fake data.");
487                 return -1;
488         }
489         /* Check fake data length */
490         if (x11_fake_data_len != x11_saved_data_len) {
491                 error("X11 fake_data_len %d != saved_data_len %d",
492                     x11_fake_data_len, x11_saved_data_len);
493                 return -1;
494         }
495         /*
496          * Received authentication protocol and data match
497          * our fake data. Substitute the fake data with real
498          * data.
499          */
500         memcpy(ucp + 12 + ((proto_len + 3) & ~3),
501             x11_saved_data, x11_saved_data_len);
502         return 1;
503 }
504
505 void
506 channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
507 {
508         int ret = x11_open_helper(c);
509         if (ret == 1) {
510                 /* Start normal processing for the channel. */
511                 c->type = SSH_CHANNEL_OPEN;
512                 channel_pre_open_13(c, readset, writeset);
513         } else if (ret == -1) {
514                 /*
515                  * We have received an X11 connection that has bad
516                  * authentication information.
517                  */
518                 log("X11 connection rejected because of wrong authentication.");
519                 buffer_clear(&c->input);
520                 buffer_clear(&c->output);
521                 close(c->sock);
522                 c->sock = -1;
523                 c->type = SSH_CHANNEL_CLOSED;
524                 packet_start(SSH_MSG_CHANNEL_CLOSE);
525                 packet_put_int(c->remote_id);
526                 packet_send();
527         }
528 }
529
530 void
531 channel_pre_x11_open(Channel *c, fd_set * readset, fd_set * writeset)
532 {
533         int ret = x11_open_helper(c);
534         if (ret == 1) {
535                 c->type = SSH_CHANNEL_OPEN;
536                 if (compat20)
537                         channel_pre_open_20(c, readset, writeset);
538                 else
539                         channel_pre_open_15(c, readset, writeset);
540         } else if (ret == -1) {
541                 debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
542                 chan_read_failed(c);    /** force close? */
543                 chan_write_failed(c);
544                 debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
545         }
546 }
547
548 /* try to decode a socks4 header */
549 int
550 channel_decode_socks4(Channel *c, fd_set * readset, fd_set * writeset)
551 {
552         u_char *p, *host;
553         int len, have, i, found;
554         char username[256];     
555         struct {
556                 u_int8_t version;
557                 u_int8_t command;
558                 u_int16_t dest_port;
559                 struct in_addr dest_addr;
560         } s4_req, s4_rsp;
561
562         debug2("channel %d: decode socks4", c->self);
563
564         have = buffer_len(&c->input);
565         len = sizeof(s4_req);
566         if (have < len)
567                 return 0;
568         p = buffer_ptr(&c->input);
569         for (found = 0, i = len; i < have; i++) {
570                 if (p[i] == '\0') {
571                         found = 1;
572                         break;
573                 }
574                 if (i > 1024) {
575                         /* the peer is probably sending garbage */
576                         debug("channel %d: decode socks4: too long",
577                             c->self);
578                         return -1;
579                 }
580         }
581         if (!found)
582                 return 0;
583         buffer_get(&c->input, (char *)&s4_req.version, 1);
584         buffer_get(&c->input, (char *)&s4_req.command, 1);
585         buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
586         buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
587         have = buffer_len(&c->input);
588         p = buffer_ptr(&c->input);
589         len = strlen(p);
590         debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
591         if (len > have)
592                 fatal("channel %d: decode socks4: len %d > have %d",
593                     c->self, len, have);
594         strlcpy(username, p, sizeof(username));
595         buffer_consume(&c->input, len);
596         buffer_consume(&c->input, 1);           /* trailing '\0' */
597
598         host = inet_ntoa(s4_req.dest_addr);
599         strlcpy(c->path, host, sizeof(c->path));
600         c->host_port = ntohs(s4_req.dest_port);
601         
602         debug("channel %d: dynamic request: socks4 host %s port %u command %u",
603             c->self, host, c->host_port, s4_req.command);
604
605         if (s4_req.command != 1) {
606                 debug("channel %d: cannot handle: socks4 cn %d",
607                     c->self, s4_req.command);
608                 return -1;
609         }
610         s4_rsp.version = 0;                     /* vn: 0 for reply */
611         s4_rsp.command = 90;                    /* cd: req granted */
612         s4_rsp.dest_port = 0;                   /* ignored */
613         s4_rsp.dest_addr.s_addr = INADDR_ANY;   /* ignored */
614         buffer_append(&c->output, (char *)&s4_rsp, sizeof(s4_rsp));
615         return 1;
616 }
617
618 /* dynamic port forwarding */
619 void
620 channel_pre_dynamic(Channel *c, fd_set * readset, fd_set * writeset)
621 {
622         u_char *p;
623         int have, ret;
624
625         have = buffer_len(&c->input);
626
627         debug2("channel %d: pre_dynamic: have %d", c->self, have);
628         /* buffer_dump(&c->input); */
629         /* check if the fixed size part of the packet is in buffer. */
630         if (have < 4) {
631                 /* need more */
632                 FD_SET(c->sock, readset);
633                 return;
634         }
635         /* try to guess the protocol */
636         p = buffer_ptr(&c->input);
637         switch (p[0]) {
638         case 0x04:
639                 ret = channel_decode_socks4(c, readset, writeset);
640                 break;
641         default:
642                 ret = -1;
643                 break;
644         }
645         if (ret < 0) {
646                 chan_mark_dead(c);
647         } else if (ret == 0) {
648                 debug2("channel %d: pre_dynamic: need more", c->self);
649                 /* need more */
650                 FD_SET(c->sock, readset);
651         } else {
652                 /* switch to the next state */
653                 c->type = SSH_CHANNEL_OPENING;
654                 port_open_helper(c, "direct-tcpip");
655         }
656 }
657
658 /* This is our fake X11 server socket. */
659 void
660 channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
661 {
662         Channel *nc;
663         struct sockaddr addr;
664         int newsock;
665         socklen_t addrlen;
666         char buf[16384], *remote_ipaddr;
667         int remote_port;
668
669         if (FD_ISSET(c->sock, readset)) {
670                 debug("X11 connection requested.");
671                 addrlen = sizeof(addr);
672                 newsock = accept(c->sock, &addr, &addrlen);
673                 if (newsock < 0) {
674                         error("accept: %.100s", strerror(errno));
675                         return;
676                 }
677                 remote_ipaddr = get_peer_ipaddr(newsock);
678                 remote_port = get_peer_port(newsock);
679                 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
680                     remote_ipaddr, remote_port);
681
682                 nc = channel_new("accepted x11 socket",
683                     SSH_CHANNEL_OPENING, newsock, newsock, -1,
684                     c->local_window_max, c->local_maxpacket,
685                     0, xstrdup(buf), 1);
686                 if (nc == NULL) {
687                         close(newsock);
688                         xfree(remote_ipaddr);
689                         return;
690                 }
691                 if (compat20) {
692                         packet_start(SSH2_MSG_CHANNEL_OPEN);
693                         packet_put_cstring("x11");
694                         packet_put_int(nc->self);
695                         packet_put_int(c->local_window_max);
696                         packet_put_int(c->local_maxpacket);
697                         /* originator ipaddr and port */
698                         packet_put_cstring(remote_ipaddr);
699                         if (datafellows & SSH_BUG_X11FWD) {
700                                 debug("ssh2 x11 bug compat mode");
701                         } else {
702                                 packet_put_int(remote_port);
703                         }
704                         packet_send();
705                 } else {
706                         packet_start(SSH_SMSG_X11_OPEN);
707                         packet_put_int(nc->self);
708                         if (have_hostname_in_open)
709                                 packet_put_string(buf, strlen(buf));
710                         packet_send();
711                 }
712                 xfree(remote_ipaddr);
713         }
714 }
715
716 void
717 port_open_helper(Channel *c, char *rtype)
718 {
719         int direct;
720         char buf[1024];
721         char *remote_ipaddr = get_peer_ipaddr(c->sock);
722         u_short remote_port = get_peer_port(c->sock);
723
724         direct = (strcmp(rtype, "direct-tcpip") == 0);
725
726         snprintf(buf, sizeof buf,
727             "%s: listening port %d for %.100s port %d, "
728             "connect from %.200s port %d",
729             rtype, c->listening_port, c->path, c->host_port,
730             remote_ipaddr, remote_port);
731
732         xfree(c->remote_name);
733         c->remote_name = xstrdup(buf);
734
735         if (compat20) {
736                 packet_start(SSH2_MSG_CHANNEL_OPEN);
737                 packet_put_cstring(rtype);
738                 packet_put_int(c->self);
739                 packet_put_int(c->local_window_max);
740                 packet_put_int(c->local_maxpacket);
741                 if (direct) {
742                         /* target host, port */
743                         packet_put_cstring(c->path);
744                         packet_put_int(c->host_port);
745                 } else {
746                         /* listen address, port */
747                         packet_put_cstring(c->path);
748                         packet_put_int(c->listening_port);
749                 }
750                 /* originator host and port */
751                 packet_put_cstring(remote_ipaddr);
752                 packet_put_int(remote_port);
753                 packet_send();
754         } else {
755                 packet_start(SSH_MSG_PORT_OPEN);
756                 packet_put_int(c->self);
757                 packet_put_cstring(c->path);
758                 packet_put_int(c->host_port);
759                 if (have_hostname_in_open)
760                         packet_put_cstring(c->remote_name);
761                 packet_send();
762         }
763         xfree(remote_ipaddr);
764 }
765
766 /*
767  * This socket is listening for connections to a forwarded TCP/IP port.
768  */
769 void
770 channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
771 {
772         Channel *nc;
773         struct sockaddr addr;
774         int newsock, nextstate;
775         socklen_t addrlen;
776         char *rtype;
777
778         if (FD_ISSET(c->sock, readset)) {
779                 debug("Connection to port %d forwarding "
780                     "to %.100s port %d requested.",
781                     c->listening_port, c->path, c->host_port);
782
783                 rtype = (c->type == SSH_CHANNEL_RPORT_LISTENER) ?
784                     "forwarded-tcpip" : "direct-tcpip";
785                 nextstate = (c->host_port == 0 &&
786                     c->type != SSH_CHANNEL_RPORT_LISTENER) ?
787                     SSH_CHANNEL_DYNAMIC : SSH_CHANNEL_OPENING;
788
789                 addrlen = sizeof(addr);
790                 newsock = accept(c->sock, &addr, &addrlen);
791                 if (newsock < 0) {
792                         error("accept: %.100s", strerror(errno));
793                         return;
794                 }
795                 nc = channel_new(rtype,
796                     nextstate, newsock, newsock, -1,
797                     c->local_window_max, c->local_maxpacket,
798                     0, xstrdup(rtype), 1);
799                 if (nc == NULL) {
800                         error("channel_post_port_listener: no new channel:");
801                         close(newsock);
802                         return;
803                 }
804                 nc->listening_port = c->listening_port;
805                 nc->host_port = c->host_port;
806                 strlcpy(nc->path, c->path, sizeof(nc->path));
807
808                 if (nextstate != SSH_CHANNEL_DYNAMIC)
809                         port_open_helper(nc, rtype);
810         }
811 }
812
813 /*
814  * This is the authentication agent socket listening for connections from
815  * clients.
816  */
817 void
818 channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
819 {
820         Channel *nc;
821         int newsock;
822         struct sockaddr addr;
823         socklen_t addrlen;
824
825         if (FD_ISSET(c->sock, readset)) {
826                 addrlen = sizeof(addr);
827                 newsock = accept(c->sock, &addr, &addrlen);
828                 if (newsock < 0) {
829                         error("accept from auth socket: %.100s", strerror(errno));
830                         return;
831                 }
832                 nc = channel_new("accepted auth socket",
833                     SSH_CHANNEL_OPENING, newsock, newsock, -1,
834                     c->local_window_max, c->local_maxpacket,
835                     0, xstrdup("accepted auth socket"), 1);
836                 if (nc == NULL) {
837                         error("channel_post_auth_listener: channel_new failed");
838                         close(newsock);
839                 }
840                 if (compat20) {
841                         packet_start(SSH2_MSG_CHANNEL_OPEN);
842                         packet_put_cstring("auth-agent@openssh.com");
843                         packet_put_int(nc->self);
844                         packet_put_int(c->local_window_max);
845                         packet_put_int(c->local_maxpacket);
846                 } else {
847                         packet_start(SSH_SMSG_AGENT_OPEN);
848                         packet_put_int(nc->self);
849                 }
850                 packet_send();
851         }
852 }
853
854 void
855 channel_post_connecting(Channel *c, fd_set * readset, fd_set * writeset)
856 {
857         int err = 0;
858         int sz = sizeof(err);
859
860         if (FD_ISSET(c->sock, writeset)) {
861                 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, (char *)&err,
862                     &sz) < 0) {
863                         err = errno;
864                         error("getsockopt SO_ERROR failed");
865                 }
866                 if (err == 0) {
867                         debug("channel %d: connected", c->self);
868                         c->type = SSH_CHANNEL_OPEN;
869                         if (compat20) {
870                                 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
871                                 packet_put_int(c->remote_id);
872                                 packet_put_int(c->self);
873                                 packet_put_int(c->local_window);
874                                 packet_put_int(c->local_maxpacket);
875                         } else {
876                                 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
877                                 packet_put_int(c->remote_id);
878                                 packet_put_int(c->self);
879                         }
880                 } else {
881                         debug("channel %d: not connected: %s",
882                             c->self, strerror(err));
883                         if (compat20) {
884                                 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
885                                 packet_put_int(c->remote_id);
886                                 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
887                                 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
888                                         packet_put_cstring(strerror(err));
889                                         packet_put_cstring("");
890                                 }
891                         } else {
892                                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
893                                 packet_put_int(c->remote_id);
894                         }
895                         chan_mark_dead(c);
896                 }
897                 packet_send();
898         }
899 }
900
901 int
902 channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
903 {
904         char buf[16*1024];
905         int len;
906
907         if (c->rfd != -1 &&
908             FD_ISSET(c->rfd, readset)) {
909                 len = read(c->rfd, buf, sizeof(buf));
910                 if (len < 0 && (errno == EINTR || errno == EAGAIN))
911                         return 1;
912                 if (len <= 0) {
913                         debug("channel %d: read<=0 rfd %d len %d",
914                             c->self, c->rfd, len);
915                         if (c->type != SSH_CHANNEL_OPEN) {
916                                 debug("channel %d: not open", c->self);
917                                 chan_mark_dead(c);
918                                 return -1;
919                         } else if (compat13) {
920                                 buffer_consume(&c->output, buffer_len(&c->output));
921                                 c->type = SSH_CHANNEL_INPUT_DRAINING;
922                                 debug("channel %d: status set to input draining.", c->self);
923                         } else {
924                                 chan_read_failed(c);
925                         }
926                         return -1;
927                 }
928                 if(c->input_filter != NULL) {
929                         if (c->input_filter(c, buf, len) == -1) {
930                                 debug("channel %d: filter stops", c->self);
931                                 chan_read_failed(c);
932                         }
933                 } else {
934                         buffer_append(&c->input, buf, len);
935                 }
936         }
937         return 1;
938 }
939 int
940 channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
941 {
942         struct termios tio;
943         int len;
944
945         /* Send buffered output data to the socket. */
946         if (c->wfd != -1 &&
947             FD_ISSET(c->wfd, writeset) &&
948             buffer_len(&c->output) > 0) {
949                 len = write(c->wfd, buffer_ptr(&c->output),
950                     buffer_len(&c->output));
951                 if (len < 0 && (errno == EINTR || errno == EAGAIN))
952                         return 1;
953                 if (len <= 0) {
954                         if (c->type != SSH_CHANNEL_OPEN) {
955                                 debug("channel %d: not open", c->self);
956                                 chan_mark_dead(c);
957                                 return -1;
958                         } else if (compat13) {
959                                 buffer_consume(&c->output, buffer_len(&c->output));
960                                 debug("channel %d: status set to input draining.", c->self);
961                                 c->type = SSH_CHANNEL_INPUT_DRAINING;
962                         } else {
963                                 chan_write_failed(c);
964                         }
965                         return -1;
966                 }
967                 if (compat20 && c->isatty) {
968                         if (tcgetattr(c->wfd, &tio) == 0 &&
969                             !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
970                                 /*
971                                  * Simulate echo to reduce the impact of
972                                  * traffic analysis. We need to match the
973                                  * size of a SSH2_MSG_CHANNEL_DATA message
974                                  * (4 byte channel id + data)
975                                  */
976                                 packet_send_ignore(4 + len);
977                                 packet_send();
978                         }
979                 }
980                 buffer_consume(&c->output, len);
981                 if (compat20 && len > 0) {
982                         c->local_consumed += len;
983                 }
984         }
985         return 1;
986 }
987 int
988 channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
989 {
990         char buf[16*1024];
991         int len;
992
993 /** XXX handle drain efd, too */
994         if (c->efd != -1) {
995                 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
996                     FD_ISSET(c->efd, writeset) &&
997                     buffer_len(&c->extended) > 0) {
998                         len = write(c->efd, buffer_ptr(&c->extended),
999                             buffer_len(&c->extended));
1000                         debug2("channel %d: written %d to efd %d",
1001                             c->self, len, c->efd);
1002                         if (len < 0 && (errno == EINTR || errno == EAGAIN))
1003                                 return 1;
1004                         if (len <= 0) {
1005                                 debug2("channel %d: closing write-efd %d",
1006                                     c->self, c->efd);
1007                                 close(c->efd);
1008                                 c->efd = -1;
1009                         } else {
1010                                 buffer_consume(&c->extended, len);
1011                                 c->local_consumed += len;
1012                         }
1013                 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
1014                     FD_ISSET(c->efd, readset)) {
1015                         len = read(c->efd, buf, sizeof(buf));
1016                         debug2("channel %d: read %d from efd %d",
1017                              c->self, len, c->efd);
1018                         if (len < 0 && (errno == EINTR || errno == EAGAIN))
1019                                 return 1;
1020                         if (len <= 0) {
1021                                 debug2("channel %d: closing read-efd %d",
1022                                     c->self, c->efd);
1023                                 close(c->efd);
1024                                 c->efd = -1;
1025                         } else {
1026                                 buffer_append(&c->extended, buf, len);
1027                         }
1028                 }
1029         }
1030         return 1;
1031 }
1032 int
1033 channel_check_window(Channel *c)
1034 {
1035         if (c->type == SSH_CHANNEL_OPEN &&
1036             !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1037             c->local_window < c->local_window_max/2 &&
1038             c->local_consumed > 0) {
1039                 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1040                 packet_put_int(c->remote_id);
1041                 packet_put_int(c->local_consumed);
1042                 packet_send();
1043                 debug2("channel %d: window %d sent adjust %d",
1044                     c->self, c->local_window,
1045                     c->local_consumed);
1046                 c->local_window += c->local_consumed;
1047                 c->local_consumed = 0;
1048         }
1049         return 1;
1050 }
1051
1052 void
1053 channel_post_open_1(Channel *c, fd_set * readset, fd_set * writeset)
1054 {
1055         channel_handle_rfd(c, readset, writeset);
1056         channel_handle_wfd(c, readset, writeset);
1057 }
1058
1059 void
1060 channel_post_open_2(Channel *c, fd_set * readset, fd_set * writeset)
1061 {
1062         channel_handle_rfd(c, readset, writeset);
1063         channel_handle_wfd(c, readset, writeset);
1064         channel_handle_efd(c, readset, writeset);
1065
1066         channel_check_window(c);
1067 }
1068
1069 void
1070 channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
1071 {
1072         int len;
1073         /* Send buffered output data to the socket. */
1074         if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1075                 len = write(c->sock, buffer_ptr(&c->output),
1076                             buffer_len(&c->output));
1077                 if (len <= 0)
1078                         buffer_consume(&c->output, buffer_len(&c->output));
1079                 else
1080                         buffer_consume(&c->output, len);
1081         }
1082 }
1083
1084 void
1085 channel_handler_init_20(void)
1086 {
1087         channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_20;
1088         channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
1089         channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
1090         channel_pre[SSH_CHANNEL_RPORT_LISTENER] =       &channel_pre_listener;
1091         channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
1092         channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1093         channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1094         channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1095
1096         channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_2;
1097         channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
1098         channel_post[SSH_CHANNEL_RPORT_LISTENER] =      &channel_post_port_listener;
1099         channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
1100         channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1101         channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1102         channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open_2;
1103 }
1104
1105 void
1106 channel_handler_init_13(void)
1107 {
1108         channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_13;
1109         channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open_13;
1110         channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
1111         channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
1112         channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1113         channel_pre[SSH_CHANNEL_INPUT_DRAINING] =       &channel_pre_input_draining;
1114         channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] =      &channel_pre_output_draining;
1115         channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1116         channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1117
1118         channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_1;
1119         channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
1120         channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
1121         channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1122         channel_post[SSH_CHANNEL_OUTPUT_DRAINING] =     &channel_post_output_drain_13;
1123         channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1124         channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open_1;
1125 }
1126
1127 void
1128 channel_handler_init_15(void)
1129 {
1130         channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_15;
1131         channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
1132         channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
1133         channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
1134         channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1135         channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1136         channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1137
1138         channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
1139         channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
1140         channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1141         channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_1;
1142         channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1143         channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open_1;
1144 }
1145
1146 void
1147 channel_handler_init(void)
1148 {
1149         int i;
1150         for(i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1151                 channel_pre[i] = NULL;
1152                 channel_post[i] = NULL;
1153         }
1154         if (compat20)
1155                 channel_handler_init_20();
1156         else if (compat13)
1157                 channel_handler_init_13();
1158         else
1159                 channel_handler_init_15();
1160 }
1161
1162 void
1163 channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
1164 {
1165         static int did_init = 0;
1166         int i;
1167         Channel *c;
1168
1169         if (!did_init) {
1170                 channel_handler_init();
1171                 did_init = 1;
1172         }
1173         for (i = 0; i < channels_alloc; i++) {
1174                 c = channels[i];
1175                 if (c == NULL)
1176                         continue;
1177                 if (ftab[c->type] != NULL)
1178                         (*ftab[c->type])(c, readset, writeset);
1179                 if (chan_is_dead(c)) {
1180                         /*
1181                          * we have to remove the fd's from the select mask
1182                          * before the channels are free'd and the fd's are
1183                          * closed
1184                          */
1185                         if (c->wfd != -1)
1186                                 FD_CLR(c->wfd, writeset);
1187                         if (c->rfd != -1)
1188                                 FD_CLR(c->rfd, readset);
1189                         if (c->efd != -1) {
1190                                 if (c->extended_usage == CHAN_EXTENDED_READ)
1191                                         FD_CLR(c->efd, readset);
1192                                 if (c->extended_usage == CHAN_EXTENDED_WRITE)
1193                                         FD_CLR(c->efd, writeset);
1194                         }
1195                         channel_free(c);
1196                 }
1197         }
1198 }
1199
1200 void
1201 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1202     int rekeying)
1203 {
1204         int n;
1205         u_int sz;
1206
1207         n = MAX(*maxfdp, channel_max_fd);
1208
1209         sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1210         if (*readsetp == NULL || n > *maxfdp) {
1211                 if (*readsetp)
1212                         xfree(*readsetp);
1213                 if (*writesetp)
1214                         xfree(*writesetp);
1215                 *readsetp = xmalloc(sz);
1216                 *writesetp = xmalloc(sz);
1217                 *maxfdp = n;
1218         }
1219         memset(*readsetp, 0, sz);
1220         memset(*writesetp, 0, sz);
1221
1222         if (!rekeying)
1223                 channel_handler(channel_pre, *readsetp, *writesetp);
1224 }
1225
1226 void
1227 channel_after_select(fd_set * readset, fd_set * writeset)
1228 {
1229         channel_handler(channel_post, readset, writeset);
1230 }
1231
1232 /* If there is data to send to the connection, enqueue some of it now. */
1233
1234 void
1235 channel_output_poll()
1236 {
1237         int len, i;
1238         Channel *c;
1239
1240         for (i = 0; i < channels_alloc; i++) {
1241
1242                 c = channels[i];
1243                 if (c == NULL)
1244                         continue;
1245
1246                 /* We are only interested in channels that can have buffered incoming data. */
1247                 if (compat13) {
1248                         if (c->type != SSH_CHANNEL_OPEN &&
1249                             c->type != SSH_CHANNEL_INPUT_DRAINING)
1250                                 continue;
1251                 } else {
1252                         if (c->type != SSH_CHANNEL_OPEN)
1253                                 continue;
1254                 }
1255                 if (compat20 &&
1256                     (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1257                         /* XXX is this true? */
1258                         debug2("channel %d: no data after CLOSE", c->self);
1259                         continue;
1260                 }
1261
1262                 /* Get the amount of buffered data for this channel. */
1263                 if ((c->istate == CHAN_INPUT_OPEN ||
1264                     c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1265                     (len = buffer_len(&c->input)) > 0) {
1266                         /* Send some data for the other side over the secure connection. */
1267                         if (compat20) {
1268                                 if (len > c->remote_window)
1269                                         len = c->remote_window;
1270                                 if (len > c->remote_maxpacket)
1271                                         len = c->remote_maxpacket;
1272                         } else {
1273                                 if (packet_is_interactive()) {
1274                                         if (len > 1024)
1275                                                 len = 512;
1276                                 } else {
1277                                         /* Keep the packets at reasonable size. */
1278                                         if (len > packet_get_maxsize()/2)
1279                                                 len = packet_get_maxsize()/2;
1280                                 }
1281                         }
1282                         if (len > 0) {
1283                                 packet_start(compat20 ?
1284                                     SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1285                                 packet_put_int(c->remote_id);
1286                                 packet_put_string(buffer_ptr(&c->input), len);
1287                                 packet_send();
1288                                 buffer_consume(&c->input, len);
1289                                 c->remote_window -= len;
1290                         }
1291                 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1292                         if (compat13)
1293                                 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1294                         /*
1295                          * input-buffer is empty and read-socket shutdown:
1296                          * tell peer, that we will not send more data: send IEOF
1297                          */
1298                         chan_ibuf_empty(c);
1299                 }
1300                 /* Send extended data, i.e. stderr */
1301                 if (compat20 &&
1302                     c->remote_window > 0 &&
1303                     (len = buffer_len(&c->extended)) > 0 &&
1304                     c->extended_usage == CHAN_EXTENDED_READ) {
1305                         debug2("channel %d: rwin %d elen %d euse %d",
1306                             c->self, c->remote_window, buffer_len(&c->extended),
1307                             c->extended_usage);
1308                         if (len > c->remote_window)
1309                                 len = c->remote_window;
1310                         if (len > c->remote_maxpacket)
1311                                 len = c->remote_maxpacket;
1312                         packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
1313                         packet_put_int(c->remote_id);
1314                         packet_put_int(SSH2_EXTENDED_DATA_STDERR);
1315                         packet_put_string(buffer_ptr(&c->extended), len);
1316                         packet_send();
1317                         buffer_consume(&c->extended, len);
1318                         c->remote_window -= len;
1319                         debug2("channel %d: sent ext data %d", c->self, len);
1320                 }
1321         }
1322 }
1323
1324 /*
1325  * This is called when a packet of type CHANNEL_DATA has just been received.
1326  * The message type has already been consumed, but channel number and data is
1327  * still there.
1328  */
1329
1330 void
1331 channel_input_data(int type, int plen, void *ctxt)
1332 {
1333         int id;
1334         char *data;
1335         u_int data_len;
1336         Channel *c;
1337
1338         /* Get the channel number and verify it. */
1339         id = packet_get_int();
1340         c = channel_lookup(id);
1341         if (c == NULL)
1342                 packet_disconnect("Received data for nonexistent channel %d.", id);
1343
1344         /* Ignore any data for non-open channels (might happen on close) */
1345         if (c->type != SSH_CHANNEL_OPEN &&
1346             c->type != SSH_CHANNEL_X11_OPEN)
1347                 return;
1348
1349         /* same for protocol 1.5 if output end is no longer open */
1350         if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
1351                 return;
1352
1353         /* Get the data. */
1354         data = packet_get_string(&data_len);
1355         packet_done();
1356
1357         if (compat20){
1358                 if (data_len > c->local_maxpacket) {
1359                         log("channel %d: rcvd big packet %d, maxpack %d",
1360                             c->self, data_len, c->local_maxpacket);
1361                 }
1362                 if (data_len > c->local_window) {
1363                         log("channel %d: rcvd too much data %d, win %d",
1364                             c->self, data_len, c->local_window);
1365                         xfree(data);
1366                         return;
1367                 }
1368                 c->local_window -= data_len;
1369         }else{
1370                 packet_integrity_check(plen, 4 + 4 + data_len, type);
1371         }
1372         buffer_append(&c->output, data, data_len);
1373         xfree(data);
1374 }
1375 void
1376 channel_input_extended_data(int type, int plen, void *ctxt)
1377 {
1378         int id;
1379         int tcode;
1380         char *data;
1381         u_int data_len;
1382         Channel *c;
1383
1384         /* Get the channel number and verify it. */
1385         id = packet_get_int();
1386         c = channel_lookup(id);
1387
1388         if (c == NULL)
1389                 packet_disconnect("Received extended_data for bad channel %d.", id);
1390         if (c->type != SSH_CHANNEL_OPEN) {
1391                 log("channel %d: ext data for non open", id);
1392                 return;
1393         }
1394         tcode = packet_get_int();
1395         if (c->efd == -1 ||
1396             c->extended_usage != CHAN_EXTENDED_WRITE ||
1397             tcode != SSH2_EXTENDED_DATA_STDERR) {
1398                 log("channel %d: bad ext data", c->self);
1399                 return;
1400         }
1401         data = packet_get_string(&data_len);
1402         packet_done();
1403         if (data_len > c->local_window) {
1404                 log("channel %d: rcvd too much extended_data %d, win %d",
1405                     c->self, data_len, c->local_window);
1406                 xfree(data);
1407                 return;
1408         }
1409         debug2("channel %d: rcvd ext data %d", c->self, data_len);
1410         c->local_window -= data_len;
1411         buffer_append(&c->extended, data, data_len);
1412         xfree(data);
1413 }
1414
1415
1416 /*
1417  * Returns true if no channel has too much buffered data, and false if one or
1418  * more channel is overfull.
1419  */
1420
1421 int
1422 channel_not_very_much_buffered_data()
1423 {
1424         u_int i;
1425         Channel *c;
1426
1427         for (i = 0; i < channels_alloc; i++) {
1428                 c = channels[i];
1429                 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
1430                         if (!compat20 && buffer_len(&c->input) > packet_get_maxsize()) {
1431                                 debug("channel %d: big input buffer %d",
1432                                     c->self, buffer_len(&c->input));
1433                                 return 0;
1434                         }
1435                         if (buffer_len(&c->output) > packet_get_maxsize()) {
1436                                 debug("channel %d: big output buffer %d",
1437                                     c->self, buffer_len(&c->output));
1438                                 return 0;
1439                         }
1440                 }
1441         }
1442         return 1;
1443 }
1444
1445 void
1446 channel_input_ieof(int type, int plen, void *ctxt)
1447 {
1448         int id;
1449         Channel *c;
1450
1451         packet_integrity_check(plen, 4, type);
1452
1453         id = packet_get_int();
1454         c = channel_lookup(id);
1455         if (c == NULL)
1456                 packet_disconnect("Received ieof for nonexistent channel %d.", id);
1457         chan_rcvd_ieof(c);
1458 }
1459
1460 void
1461 channel_input_close(int type, int plen, void *ctxt)
1462 {
1463         int id;
1464         Channel *c;
1465
1466         packet_integrity_check(plen, 4, type);
1467
1468         id = packet_get_int();
1469         c = channel_lookup(id);
1470         if (c == NULL)
1471                 packet_disconnect("Received close for nonexistent channel %d.", id);
1472
1473         /*
1474          * Send a confirmation that we have closed the channel and no more
1475          * data is coming for it.
1476          */
1477         packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1478         packet_put_int(c->remote_id);
1479         packet_send();
1480
1481         /*
1482          * If the channel is in closed state, we have sent a close request,
1483          * and the other side will eventually respond with a confirmation.
1484          * Thus, we cannot free the channel here, because then there would be
1485          * no-one to receive the confirmation.  The channel gets freed when
1486          * the confirmation arrives.
1487          */
1488         if (c->type != SSH_CHANNEL_CLOSED) {
1489                 /*
1490                  * Not a closed channel - mark it as draining, which will
1491                  * cause it to be freed later.
1492                  */
1493                 buffer_consume(&c->input, buffer_len(&c->input));
1494                 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1495         }
1496 }
1497
1498 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1499 void
1500 channel_input_oclose(int type, int plen, void *ctxt)
1501 {
1502         int id = packet_get_int();
1503         Channel *c = channel_lookup(id);
1504         packet_integrity_check(plen, 4, type);
1505         if (c == NULL)
1506                 packet_disconnect("Received oclose for nonexistent channel %d.", id);
1507         chan_rcvd_oclose(c);
1508 }
1509
1510 void
1511 channel_input_close_confirmation(int type, int plen, void *ctxt)
1512 {
1513         int id = packet_get_int();
1514         Channel *c = channel_lookup(id);
1515
1516         packet_done();
1517         if (c == NULL)
1518                 packet_disconnect("Received close confirmation for "
1519                     "out-of-range channel %d.", id);
1520         if (c->type != SSH_CHANNEL_CLOSED)
1521                 packet_disconnect("Received close confirmation for "
1522                     "non-closed channel %d (type %d).", id, c->type);
1523         channel_free(c);
1524 }
1525
1526 void
1527 channel_input_open_confirmation(int type, int plen, void *ctxt)
1528 {
1529         int id, remote_id;
1530         Channel *c;
1531
1532         if (!compat20)
1533                 packet_integrity_check(plen, 4 + 4, type);
1534
1535         id = packet_get_int();
1536         c = channel_lookup(id);
1537
1538         if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1539                 packet_disconnect("Received open confirmation for "
1540                     "non-opening channel %d.", id);
1541         remote_id = packet_get_int();
1542         /* Record the remote channel number and mark that the channel is now open. */
1543         c->remote_id = remote_id;
1544         c->type = SSH_CHANNEL_OPEN;
1545
1546         if (compat20) {
1547                 c->remote_window = packet_get_int();
1548                 c->remote_maxpacket = packet_get_int();
1549                 packet_done();
1550                 if (c->cb_fn != NULL && c->cb_event == type) {
1551                         debug2("callback start");
1552                         c->cb_fn(c->self, c->cb_arg);
1553                         debug2("callback done");
1554                 }
1555                 debug("channel %d: open confirm rwindow %d rmax %d", c->self,
1556                     c->remote_window, c->remote_maxpacket);
1557         }
1558 }
1559
1560 char *
1561 reason2txt(int reason)
1562 {
1563         switch(reason) {
1564         case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
1565                 return "administratively prohibited";
1566         case SSH2_OPEN_CONNECT_FAILED:
1567                 return "connect failed";
1568         case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
1569                 return "unknown channel type";
1570         case SSH2_OPEN_RESOURCE_SHORTAGE:
1571                 return "resource shortage";
1572         }
1573         return "unknown reason";
1574 }
1575
1576 void
1577 channel_input_open_failure(int type, int plen, void *ctxt)
1578 {
1579         int id, reason;
1580         char *msg = NULL, *lang = NULL;
1581         Channel *c;
1582
1583         if (!compat20)
1584                 packet_integrity_check(plen, 4, type);
1585
1586         id = packet_get_int();
1587         c = channel_lookup(id);
1588
1589         if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1590                 packet_disconnect("Received open failure for "
1591                     "non-opening channel %d.", id);
1592         if (compat20) {
1593                 reason = packet_get_int();
1594                 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1595                         msg  = packet_get_string(NULL);
1596                         lang = packet_get_string(NULL);
1597                 }
1598                 packet_done();
1599                 log("channel %d: open failed: %s%s%s", id,
1600                     reason2txt(reason), msg ? ": ": "", msg ? msg : "");
1601                 if (msg != NULL)
1602                         xfree(msg);
1603                 if (lang != NULL)
1604                         xfree(lang);
1605         }
1606         /* Free the channel.  This will also close the socket. */
1607         channel_free(c);
1608 }
1609
1610 void
1611 channel_input_channel_request(int type, int plen, void *ctxt)
1612 {
1613         int id;
1614         Channel *c;
1615
1616         id = packet_get_int();
1617         c = channel_lookup(id);
1618
1619         if (c == NULL ||
1620             (c->type != SSH_CHANNEL_OPEN && c->type != SSH_CHANNEL_LARVAL))
1621                 packet_disconnect("Received request for "
1622                     "non-open channel %d.", id);
1623         if (c->cb_fn != NULL && c->cb_event == type) {
1624                 debug2("callback start");
1625                 c->cb_fn(c->self, c->cb_arg);
1626                 debug2("callback done");
1627         } else {
1628                 char *service = packet_get_string(NULL);
1629                 debug("channel %d: rcvd request for %s", c->self, service);
1630                 debug("cb_fn %p cb_event %d", c->cb_fn , c->cb_event);
1631                 xfree(service);
1632         }
1633 }
1634
1635 void
1636 channel_input_window_adjust(int type, int plen, void *ctxt)
1637 {
1638         Channel *c;
1639         int id, adjust;
1640
1641         if (!compat20)
1642                 return;
1643
1644         /* Get the channel number and verify it. */
1645         id = packet_get_int();
1646         c = channel_lookup(id);
1647
1648         if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
1649                 log("Received window adjust for "
1650                     "non-open channel %d.", id);
1651                 return;
1652         }
1653         adjust = packet_get_int();
1654         packet_done();
1655         debug2("channel %d: rcvd adjust %d", id, adjust);
1656         c->remote_window += adjust;
1657 }
1658
1659 /*
1660  * Stops listening for channels, and removes any unix domain sockets that we
1661  * might have.
1662  */
1663
1664 void
1665 channel_stop_listening()
1666 {
1667         int i;
1668         Channel *c;
1669
1670         for (i = 0; i < channels_alloc; i++) {
1671                 c = channels[i];
1672                 if (c != NULL) {
1673                         switch (c->type) {
1674                         case SSH_CHANNEL_AUTH_SOCKET:
1675                                 close(c->sock);
1676                                 unlink(c->path);
1677                                 channel_free(c);
1678                                 break;
1679                         case SSH_CHANNEL_PORT_LISTENER:
1680                         case SSH_CHANNEL_RPORT_LISTENER:
1681                         case SSH_CHANNEL_X11_LISTENER:
1682                                 close(c->sock);
1683                                 channel_free(c);
1684                                 break;
1685                         default:
1686                                 break;
1687                         }
1688                 }
1689         }
1690 }
1691
1692 /*
1693  * Closes the sockets/fds of all channels.  This is used to close extra file
1694  * descriptors after a fork.
1695  */
1696
1697 void
1698 channel_close_all()
1699 {
1700         int i;
1701
1702         for (i = 0; i < channels_alloc; i++)
1703                 if (channels[i] != NULL)
1704                         channel_close_fds(channels[i]);
1705 }
1706
1707 /* Returns true if any channel is still open. */
1708
1709 int
1710 channel_still_open()
1711 {
1712         int i;
1713         Channel *c;
1714
1715         for (i = 0; i < channels_alloc; i++) {
1716                 c = channels[i];
1717                 if (c == NULL)
1718                         continue;
1719                 switch (c->type) {
1720                 case SSH_CHANNEL_X11_LISTENER:
1721                 case SSH_CHANNEL_PORT_LISTENER:
1722                 case SSH_CHANNEL_RPORT_LISTENER:
1723                 case SSH_CHANNEL_CLOSED:
1724                 case SSH_CHANNEL_AUTH_SOCKET:
1725                 case SSH_CHANNEL_DYNAMIC:
1726                 case SSH_CHANNEL_CONNECTING:
1727                 case SSH_CHANNEL_ZOMBIE:
1728                         continue;
1729                 case SSH_CHANNEL_LARVAL:
1730                         if (!compat20)
1731                                 fatal("cannot happen: SSH_CHANNEL_LARVAL");
1732                         continue;
1733                 case SSH_CHANNEL_OPENING:
1734                 case SSH_CHANNEL_OPEN:
1735                 case SSH_CHANNEL_X11_OPEN:
1736                         return 1;
1737                 case SSH_CHANNEL_INPUT_DRAINING:
1738                 case SSH_CHANNEL_OUTPUT_DRAINING:
1739                         if (!compat13)
1740                                 fatal("cannot happen: OUT_DRAIN");
1741                         return 1;
1742                 default:
1743                         fatal("channel_still_open: bad channel type %d", c->type);
1744                         /* NOTREACHED */
1745                 }
1746         }
1747         return 0;
1748 }
1749
1750 /* Returns the id of an open channel suitable for keepaliving */
1751
1752 int
1753 channel_find_open()
1754 {
1755         int i;
1756         Channel *c;
1757
1758         for (i = 0; i < channels_alloc; i++) {
1759                 c = channels[i];
1760                 if (c == NULL)
1761                         continue;
1762                 switch (c->type) {
1763                 case SSH_CHANNEL_CLOSED:
1764                 case SSH_CHANNEL_DYNAMIC:
1765                 case SSH_CHANNEL_X11_LISTENER:
1766                 case SSH_CHANNEL_PORT_LISTENER:
1767                 case SSH_CHANNEL_RPORT_LISTENER:
1768                 case SSH_CHANNEL_OPENING:
1769                 case SSH_CHANNEL_CONNECTING:
1770                 case SSH_CHANNEL_ZOMBIE:
1771                         continue;
1772                 case SSH_CHANNEL_LARVAL:
1773                 case SSH_CHANNEL_AUTH_SOCKET:
1774                 case SSH_CHANNEL_OPEN:
1775                 case SSH_CHANNEL_X11_OPEN:
1776                         return i;
1777                 case SSH_CHANNEL_INPUT_DRAINING:
1778                 case SSH_CHANNEL_OUTPUT_DRAINING:
1779                         if (!compat13)
1780                                 fatal("cannot happen: OUT_DRAIN");
1781                         return i;
1782                 default:
1783                         fatal("channel_find_open: bad channel type %d", c->type);
1784                         /* NOTREACHED */
1785                 }
1786         }
1787         return -1;
1788 }
1789
1790
1791 /*
1792  * Returns a message describing the currently open forwarded connections,
1793  * suitable for sending to the client.  The message contains crlf pairs for
1794  * newlines.
1795  */
1796
1797 char *
1798 channel_open_message()
1799 {
1800         Buffer buffer;
1801         Channel *c;
1802         char buf[1024], *cp;
1803         int i;
1804
1805         buffer_init(&buffer);
1806         snprintf(buf, sizeof buf, "The following connections are open:\r\n");
1807         buffer_append(&buffer, buf, strlen(buf));
1808         for (i = 0; i < channels_alloc; i++) {
1809                 c = channels[i];
1810                 if (c == NULL)
1811                         continue;
1812                 switch (c->type) {
1813                 case SSH_CHANNEL_X11_LISTENER:
1814                 case SSH_CHANNEL_PORT_LISTENER:
1815                 case SSH_CHANNEL_RPORT_LISTENER:
1816                 case SSH_CHANNEL_CLOSED:
1817                 case SSH_CHANNEL_AUTH_SOCKET:
1818                 case SSH_CHANNEL_ZOMBIE:
1819                         continue;
1820                 case SSH_CHANNEL_LARVAL:
1821                 case SSH_CHANNEL_OPENING:
1822                 case SSH_CHANNEL_CONNECTING:
1823                 case SSH_CHANNEL_DYNAMIC:
1824                 case SSH_CHANNEL_OPEN:
1825                 case SSH_CHANNEL_X11_OPEN:
1826                 case SSH_CHANNEL_INPUT_DRAINING:
1827                 case SSH_CHANNEL_OUTPUT_DRAINING:
1828                         snprintf(buf, sizeof buf, "  #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
1829                             c->self, c->remote_name,
1830                             c->type, c->remote_id,
1831                             c->istate, buffer_len(&c->input),
1832                             c->ostate, buffer_len(&c->output),
1833                             c->rfd, c->wfd);
1834                         buffer_append(&buffer, buf, strlen(buf));
1835                         continue;
1836                 default:
1837                         fatal("channel_open_message: bad channel type %d", c->type);
1838                         /* NOTREACHED */
1839                 }
1840         }
1841         buffer_append(&buffer, "\0", 1);
1842         cp = xstrdup(buffer_ptr(&buffer));
1843         buffer_free(&buffer);
1844         return cp;
1845 }
1846
1847 /*
1848  * Initiate forwarding of connections to local port "port" through the secure
1849  * channel to host:port from remote side.
1850  */
1851 int
1852 channel_request_local_forwarding(u_short listen_port, const char *host_to_connect,
1853     u_short port_to_connect, int gateway_ports)
1854 {
1855         return channel_request_forwarding(
1856             NULL, listen_port,
1857             host_to_connect, port_to_connect,
1858             gateway_ports, /*remote_fwd*/ 0);
1859 }
1860
1861 /*
1862  * If 'remote_fwd' is true we have a '-R style' listener for protocol 2
1863  * (SSH_CHANNEL_RPORT_LISTENER).
1864  */
1865 int
1866 channel_request_forwarding(
1867     const char *listen_address, u_short listen_port,
1868     const char *host_to_connect, u_short port_to_connect,
1869     int gateway_ports, int remote_fwd)
1870 {
1871         Channel *c;
1872         int success, sock, on = 1, ctype;
1873         struct addrinfo hints, *ai, *aitop;
1874         char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1875         const char *host;
1876         struct linger linger;
1877
1878         success = 0;
1879
1880         if (remote_fwd) {
1881                 host = listen_address;
1882                 ctype = SSH_CHANNEL_RPORT_LISTENER;
1883         } else {
1884                 host = host_to_connect;
1885                 ctype  =SSH_CHANNEL_PORT_LISTENER;
1886         }
1887
1888         if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
1889                 error("Forward host name too long.");
1890                 return success;
1891         }
1892
1893         /* XXX listen_address is currently ignored */
1894         /*
1895          * getaddrinfo returns a loopback address if the hostname is
1896          * set to NULL and hints.ai_flags is not AI_PASSIVE
1897          */
1898         memset(&hints, 0, sizeof(hints));
1899         hints.ai_family = IPv4or6;
1900         hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
1901         hints.ai_socktype = SOCK_STREAM;
1902         snprintf(strport, sizeof strport, "%d", listen_port);
1903         if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
1904                 packet_disconnect("getaddrinfo: fatal error");
1905
1906         for (ai = aitop; ai; ai = ai->ai_next) {
1907                 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1908                         continue;
1909                 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1910                     strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1911                         error("channel_request_forwarding: getnameinfo failed");
1912                         continue;
1913                 }
1914                 /* Create a port to listen for the host. */
1915                 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1916                 if (sock < 0) {
1917                         /* this is no error since kernel may not support ipv6 */
1918                         verbose("socket: %.100s", strerror(errno));
1919                         continue;
1920                 }
1921                 /*
1922                  * Set socket options.  We would like the socket to disappear
1923                  * as soon as it has been closed for whatever reason.
1924                  */
1925                 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
1926                 linger.l_onoff = 1;
1927                 linger.l_linger = 5;
1928                 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
1929                 debug("Local forwarding listening on %s port %s.", ntop, strport);
1930
1931                 /* Bind the socket to the address. */
1932                 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1933                         /* address can be in use ipv6 address is already bound */
1934                         if (!ai->ai_next)
1935                                 error("bind: %.100s", strerror(errno));
1936                         else
1937                                 verbose("bind: %.100s", strerror(errno));
1938
1939                         close(sock);
1940                         continue;
1941                 }
1942                 /* Start listening for connections on the socket. */
1943                 if (listen(sock, 5) < 0) {
1944                         error("listen: %.100s", strerror(errno));
1945                         close(sock);
1946                         continue;
1947                 }
1948                 /* Allocate a channel number for the socket. */
1949                 c = channel_new("port listener", ctype, sock, sock, -1,
1950                     CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1951                     0, xstrdup("port listener"), 1);
1952                 if (c == NULL) {
1953                         error("channel_request_forwarding: channel_new failed");
1954                         close(sock);
1955                         continue;
1956                 }
1957                 strlcpy(c->path, host, sizeof(c->path));
1958                 c->host_port = port_to_connect;
1959                 c->listening_port = listen_port;
1960                 success = 1;
1961         }
1962         if (success == 0)
1963                 error("channel_request_forwarding: cannot listen to port: %d",
1964                     listen_port);
1965         freeaddrinfo(aitop);
1966         return success;
1967 }
1968
1969 /*
1970  * Initiate forwarding of connections to port "port" on remote host through
1971  * the secure channel to host:port from local side.
1972  */
1973
1974 void
1975 channel_request_remote_forwarding(u_short listen_port,
1976     const char *host_to_connect, u_short port_to_connect)
1977 {
1978         int payload_len, type, success = 0;
1979
1980         /* Record locally that connection to this host/port is permitted. */
1981         if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
1982                 fatal("channel_request_remote_forwarding: too many forwards");
1983
1984         /* Send the forward request to the remote side. */
1985         if (compat20) {
1986                 const char *address_to_bind = "0.0.0.0";
1987                 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1988                 packet_put_cstring("tcpip-forward");
1989                 packet_put_char(0);                     /* boolean: want reply */
1990                 packet_put_cstring(address_to_bind);
1991                 packet_put_int(listen_port);
1992                 packet_send();
1993                 packet_write_wait();
1994                 /* Assume that server accepts the request */
1995                 success = 1;
1996         } else {
1997                 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1998                 packet_put_int(listen_port);
1999                 packet_put_cstring(host_to_connect);
2000                 packet_put_int(port_to_connect);
2001                 packet_send();
2002                 packet_write_wait();
2003
2004                 /* Wait for response from the remote side. */
2005                 type = packet_read(&payload_len);
2006                 switch (type) {
2007                 case SSH_SMSG_SUCCESS:
2008                         success = 1;
2009                         break;
2010                 case SSH_SMSG_FAILURE:
2011                         log("Warning: Server denied remote port forwarding.");
2012                         break;
2013                 default:
2014                         /* Unknown packet */
2015                         packet_disconnect("Protocol error for port forward request:"
2016                             "received packet type %d.", type);
2017                 }
2018         }
2019         if (success) {
2020                 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
2021                 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
2022                 permitted_opens[num_permitted_opens].listen_port = listen_port;
2023                 num_permitted_opens++;
2024         }
2025 }
2026
2027 /*
2028  * This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
2029  * listening for the port, and sends back a success reply (or disconnect
2030  * message if there was an error).  This never returns if there was an error.
2031  */
2032
2033 void
2034 channel_input_port_forward_request(int is_root, int gateway_ports)
2035 {
2036         u_short port, host_port;
2037         char *hostname;
2038
2039         /* Get arguments from the packet. */
2040         port = packet_get_int();
2041         hostname = packet_get_string(NULL);
2042         host_port = packet_get_int();
2043
2044 #ifndef HAVE_CYGWIN
2045         /*
2046          * Check that an unprivileged user is not trying to forward a
2047          * privileged port.
2048          */
2049         if (port < IPPORT_RESERVED && !is_root)
2050                 packet_disconnect("Requested forwarding of port %d but user is not root.",
2051                                   port);
2052 #endif
2053         /* Initiate forwarding */
2054         channel_request_local_forwarding(port, hostname, host_port, gateway_ports);
2055
2056         /* Free the argument string. */
2057         xfree(hostname);
2058 }
2059
2060 /*
2061  * Permits opening to any host/port if permitted_opens[] is empty.  This is
2062  * usually called by the server, because the user could connect to any port
2063  * anyway, and the server has no way to know but to trust the client anyway.
2064  */
2065 void
2066 channel_permit_all_opens()
2067 {
2068         if (num_permitted_opens == 0)
2069                 all_opens_permitted = 1;
2070 }
2071
2072 void
2073 channel_add_permitted_opens(char *host, int port)
2074 {
2075         if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2076                 fatal("channel_request_remote_forwarding: too many forwards");
2077         debug("allow port forwarding to host %s port %d", host, port);
2078
2079         permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
2080         permitted_opens[num_permitted_opens].port_to_connect = port;
2081         num_permitted_opens++;
2082
2083         all_opens_permitted = 0;
2084 }
2085
2086 void
2087 channel_clear_permitted_opens(void)
2088 {
2089         int i;
2090
2091         for (i = 0; i < num_permitted_opens; i++)
2092                 xfree(permitted_opens[i].host_to_connect);
2093         num_permitted_opens = 0;
2094
2095 }
2096
2097
2098 /* return socket to remote host, port */
2099 int
2100 connect_to(const char *host, u_short port)
2101 {
2102         struct addrinfo hints, *ai, *aitop;
2103         char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2104         int gaierr;
2105         int sock = -1;
2106
2107         memset(&hints, 0, sizeof(hints));
2108         hints.ai_family = IPv4or6;
2109         hints.ai_socktype = SOCK_STREAM;
2110         snprintf(strport, sizeof strport, "%d", port);
2111         if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
2112                 error("connect_to %.100s: unknown host (%s)", host,
2113                     gai_strerror(gaierr));
2114                 return -1;
2115         }
2116         for (ai = aitop; ai; ai = ai->ai_next) {
2117                 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2118                         continue;
2119                 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2120                     strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2121                         error("connect_to: getnameinfo failed");
2122                         continue;
2123                 }
2124                 sock = socket(ai->ai_family, SOCK_STREAM, 0);
2125                 if (sock < 0) {
2126                         error("socket: %.100s", strerror(errno));
2127                         continue;
2128                 }
2129                 if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0)
2130                         fatal("connect_to: F_SETFL: %s", strerror(errno));
2131                 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
2132                     errno != EINPROGRESS) {
2133                         error("connect_to %.100s port %s: %.100s", ntop, strport,
2134                             strerror(errno));
2135                         close(sock);
2136                         continue;       /* fail -- try next */
2137                 }
2138                 break; /* success */
2139
2140         }
2141         freeaddrinfo(aitop);
2142         if (!ai) {
2143                 error("connect_to %.100s port %d: failed.", host, port);
2144                 return -1;
2145         }
2146         /* success */
2147         return sock;
2148 }
2149
2150 int
2151 channel_connect_by_listen_adress(u_short listen_port)
2152 {
2153         int i;
2154
2155         for (i = 0; i < num_permitted_opens; i++)
2156                 if (permitted_opens[i].listen_port == listen_port)
2157                         return connect_to(
2158                             permitted_opens[i].host_to_connect,
2159                             permitted_opens[i].port_to_connect);
2160         error("WARNING: Server requests forwarding for unknown listen_port %d",
2161             listen_port);
2162         return -1;
2163 }
2164
2165 /* Check if connecting to that port is permitted and connect. */
2166 int
2167 channel_connect_to(const char *host, u_short port)
2168 {
2169         int i, permit;
2170
2171         permit = all_opens_permitted;
2172         if (!permit) {
2173                 for (i = 0; i < num_permitted_opens; i++)
2174                         if (permitted_opens[i].port_to_connect == port &&
2175                             strcmp(permitted_opens[i].host_to_connect, host) == 0)
2176                                 permit = 1;
2177
2178         }
2179         if (!permit) {
2180                 log("Received request to connect to host %.100s port %d, "
2181                     "but the request was denied.", host, port);
2182                 return -1;
2183         }
2184         return connect_to(host, port);
2185 }
2186
2187 /*
2188  * This is called after receiving PORT_OPEN message.  This attempts to
2189  * connect to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION
2190  * or CHANNEL_OPEN_FAILURE.
2191  */
2192
2193 void
2194 channel_input_port_open(int type, int plen, void *ctxt)
2195 {
2196         Channel *c = NULL;
2197         u_short host_port;
2198         char *host, *originator_string;
2199         int remote_id, sock = -1;
2200
2201         remote_id = packet_get_int();
2202         host = packet_get_string(NULL);
2203         host_port = packet_get_int();
2204
2205         if (have_hostname_in_open) {
2206                 originator_string = packet_get_string(NULL);
2207         } else {
2208                 originator_string = xstrdup("unknown (remote did not supply name)");
2209         }
2210         packet_done();
2211         sock = channel_connect_to(host, host_port);
2212         if (sock != -1) {
2213                 c = channel_new("connected socket",
2214                     SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
2215                     originator_string, 1);
2216                 if (c == NULL) {
2217                         error("channel_input_port_open: channel_new failed");
2218                         close(sock);
2219                 } else {
2220                         c->remote_id = remote_id;
2221                 }
2222         }
2223         if (c == NULL) {
2224                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2225                 packet_put_int(remote_id);
2226                 packet_send();
2227         }
2228         xfree(host);
2229 }
2230
2231 /*
2232  * Creates an internet domain socket for listening for X11 connections.
2233  * Returns a suitable value for the DISPLAY variable, or NULL if an error
2234  * occurs.
2235  */
2236
2237 #define NUM_SOCKS       10
2238
2239 char *
2240 x11_create_display_inet(int screen_number, int x11_display_offset)
2241 {
2242         int display_number, sock;
2243         u_short port;
2244         struct addrinfo hints, *ai, *aitop;
2245         char strport[NI_MAXSERV];
2246         int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
2247         char display[512];
2248         char hostname[MAXHOSTNAMELEN];
2249
2250         for (display_number = x11_display_offset;
2251              display_number < MAX_DISPLAYS;
2252              display_number++) {
2253                 port = 6000 + display_number;
2254                 memset(&hints, 0, sizeof(hints));
2255                 hints.ai_family = IPv4or6;
2256                 hints.ai_flags = AI_PASSIVE;            /* XXX loopback only ? */
2257                 hints.ai_socktype = SOCK_STREAM;
2258                 snprintf(strport, sizeof strport, "%d", port);
2259                 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
2260                         error("getaddrinfo: %.100s", gai_strerror(gaierr));
2261                         return NULL;
2262                 }
2263                 for (ai = aitop; ai; ai = ai->ai_next) {
2264                         if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2265                                 continue;
2266                         sock = socket(ai->ai_family, SOCK_STREAM, 0);
2267                         if (sock < 0) {
2268                                 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) {
2269                                         error("socket: %.100s", strerror(errno));
2270                                         return NULL;
2271                                 } else {
2272                                         debug("x11_create_display_inet: Socket family %d not supported",
2273                                                  ai->ai_family);
2274                                         continue;
2275                                 }
2276                         }
2277                         if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2278                                 debug("bind port %d: %.100s", port, strerror(errno));
2279                                 shutdown(sock, SHUT_RDWR);
2280                                 close(sock);
2281
2282                                 if (ai->ai_next)
2283                                         continue;
2284
2285                                 for (n = 0; n < num_socks; n++) {
2286                                         shutdown(socks[n], SHUT_RDWR);
2287                                         close(socks[n]);
2288                                 }
2289                                 num_socks = 0;
2290                                 break;
2291                         }
2292                         socks[num_socks++] = sock;
2293 #ifndef DONT_TRY_OTHER_AF
2294                         if (num_socks == NUM_SOCKS)
2295                                 break;
2296 #else
2297                         break;
2298 #endif
2299                 }
2300                 freeaddrinfo(aitop);
2301                 if (num_socks > 0)
2302                         break;
2303         }
2304         if (display_number >= MAX_DISPLAYS) {
2305                 error("Failed to allocate internet-domain X11 display socket.");
2306                 return NULL;
2307         }
2308         /* Start listening for connections on the socket. */
2309         for (n = 0; n < num_socks; n++) {
2310                 sock = socks[n];
2311                 if (listen(sock, 5) < 0) {
2312                         error("listen: %.100s", strerror(errno));
2313                         shutdown(sock, SHUT_RDWR);
2314                         close(sock);
2315                         return NULL;
2316                 }
2317         }
2318
2319         /* Set up a suitable value for the DISPLAY variable. */
2320         if (gethostname(hostname, sizeof(hostname)) < 0)
2321                 fatal("gethostname: %.100s", strerror(errno));
2322
2323 #ifdef IPADDR_IN_DISPLAY
2324         /*
2325          * HPUX detects the local hostname in the DISPLAY variable and tries
2326          * to set up a shared memory connection to the server, which it
2327          * incorrectly supposes to be local.
2328          *
2329          * The workaround - as used in later $$H and other programs - is
2330          * is to set display to the host's IP address.
2331          */
2332         {
2333                 struct hostent *he;
2334                 struct in_addr my_addr;
2335
2336                 he = gethostbyname(hostname);
2337                 if (he == NULL) {
2338                         error("[X11-broken-fwd-hostname-workaround] Could not get "
2339                                 "IP address for hostname %s.", hostname);
2340
2341                         packet_send_debug("[X11-broken-fwd-hostname-workaround]"
2342                                 "Could not get IP address for hostname %s.", hostname);
2343
2344                         shutdown(sock, SHUT_RDWR);
2345                         close(sock);
2346
2347                         return NULL;
2348                 }
2349
2350                 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2351
2352                 /* Set DISPLAY to <ip address>:screen.display */
2353                 snprintf(display, sizeof(display), "%.50s:%d.%d", inet_ntoa(my_addr),
2354                          display_number, screen_number);
2355         }
2356 #else /* IPADDR_IN_DISPLAY */
2357         /* Just set DISPLAY to hostname:screen.display */
2358         snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
2359                  display_number, screen_number);
2360 #endif /* IPADDR_IN_DISPLAY */
2361
2362         /* Allocate a channel for each socket. */
2363         for (n = 0; n < num_socks; n++) {
2364                 sock = socks[n];
2365                 (void) channel_new("x11 listener",
2366                     SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
2367                     CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2368                     0, xstrdup("X11 inet listener"), 1);
2369         }
2370
2371         /* Return a suitable value for the DISPLAY environment variable. */
2372         return xstrdup(display);
2373 }
2374
2375 #ifndef X_UNIX_PATH
2376 #define X_UNIX_PATH "/tmp/.X11-unix/X"
2377 #endif
2378
2379 static
2380 int
2381 connect_local_xsocket(u_int dnr)
2382 {
2383         static const char *const x_sockets[] = {
2384                 X_UNIX_PATH "%u",
2385                 "/var/X/.X11-unix/X" "%u",
2386                 "/usr/spool/sockets/X11/" "%u",
2387                 NULL
2388         };
2389         int sock;
2390         struct sockaddr_un addr;
2391         const char *const * path;
2392
2393         for (path = x_sockets; *path; ++path) {
2394                 sock = socket(AF_UNIX, SOCK_STREAM, 0);
2395                 if (sock < 0)
2396                         error("socket: %.100s", strerror(errno));
2397                 memset(&addr, 0, sizeof(addr));
2398                 addr.sun_family = AF_UNIX;
2399                 snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
2400                 if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
2401                         return sock;
2402                 close(sock);
2403         }
2404         error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
2405         return -1;
2406 }
2407
2408 int
2409 x11_connect_display(void)
2410 {
2411         int display_number, sock = 0;
2412         const char *display;
2413         char buf[1024], *cp;
2414         struct addrinfo hints, *ai, *aitop;
2415         char strport[NI_MAXSERV];
2416         int gaierr;
2417
2418         /* Try to open a socket for the local X server. */
2419         display = getenv("DISPLAY");
2420         if (!display) {
2421                 error("DISPLAY not set.");
2422                 return -1;
2423         }
2424         /*
2425          * Now we decode the value of the DISPLAY variable and make a
2426          * connection to the real X server.
2427          */
2428
2429         /*
2430          * Check if it is a unix domain socket.  Unix domain displays are in
2431          * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
2432          */
2433         if (strncmp(display, "unix:", 5) == 0 ||
2434             display[0] == ':') {
2435                 /* Connect to the unix domain socket. */
2436                 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
2437                         error("Could not parse display number from DISPLAY: %.100s",
2438                               display);
2439                         return -1;
2440                 }
2441                 /* Create a socket. */
2442                 sock = connect_local_xsocket(display_number);
2443                 if (sock < 0)
2444                         return -1;
2445
2446                 /* OK, we now have a connection to the display. */
2447                 return sock;
2448         }
2449         /*
2450          * Connect to an inet socket.  The DISPLAY value is supposedly
2451          * hostname:d[.s], where hostname may also be numeric IP address.
2452          */
2453         strncpy(buf, display, sizeof(buf));
2454         buf[sizeof(buf) - 1] = 0;
2455         cp = strchr(buf, ':');
2456         if (!cp) {
2457                 error("Could not find ':' in DISPLAY: %.100s", display);
2458                 return -1;
2459         }
2460         *cp = 0;
2461         /* buf now contains the host name.  But first we parse the display number. */
2462         if (sscanf(cp + 1, "%d", &display_number) != 1) {
2463                 error("Could not parse display number from DISPLAY: %.100s",
2464                       display);
2465                 return -1;
2466         }
2467
2468         /* Look up the host address */
2469         memset(&hints, 0, sizeof(hints));
2470         hints.ai_family = IPv4or6;
2471         hints.ai_socktype = SOCK_STREAM;
2472         snprintf(strport, sizeof strport, "%d", 6000 + display_number);
2473         if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
2474                 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
2475                 return -1;
2476         }
2477         for (ai = aitop; ai; ai = ai->ai_next) {
2478                 /* Create a socket. */
2479                 sock = socket(ai->ai_family, SOCK_STREAM, 0);
2480                 if (sock < 0) {
2481                         debug("socket: %.100s", strerror(errno));
2482                         continue;
2483                 }
2484                 /* Connect it to the display. */
2485                 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2486                         debug("connect %.100s port %d: %.100s", buf,
2487                             6000 + display_number, strerror(errno));
2488                         close(sock);
2489                         continue;
2490                 }
2491                 /* Success */
2492                 break;
2493         }
2494         freeaddrinfo(aitop);
2495         if (!ai) {
2496                 error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
2497                     strerror(errno));
2498                 return -1;
2499         }
2500         return sock;
2501 }
2502
2503 /*
2504  * This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
2505  * the remote channel number.  We should do whatever we want, and respond
2506  * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
2507  */
2508
2509 void
2510 x11_input_open(int type, int plen, void *ctxt)
2511 {
2512         Channel *c = NULL;
2513         int remote_id, sock = 0;
2514         char *remote_host;
2515
2516         debug("Received X11 open request.");
2517
2518         remote_id = packet_get_int();
2519         if (have_hostname_in_open) {
2520                 remote_host = packet_get_string(NULL);
2521         } else {
2522                 remote_host = xstrdup("unknown (remote did not supply name)");
2523         }
2524         packet_done();
2525
2526         /* Obtain a connection to the real X display. */
2527         sock = x11_connect_display();
2528         if (sock != -1) {
2529                 /* Allocate a channel for this connection. */
2530                 c = channel_new("connected x11 socket",
2531                     SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
2532                     remote_host, 1);
2533                 if (c == NULL) {
2534                         error("x11_input_open: channel_new failed");
2535                         close(sock);
2536                 } else {
2537                         c->remote_id = remote_id;
2538                 }
2539         }
2540         if (c == NULL) {
2541                 /* Send refusal to the remote host. */
2542                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2543                 packet_put_int(remote_id);
2544         } else {
2545                 /* Send a confirmation to the remote host. */
2546                 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2547                 packet_put_int(remote_id);
2548                 packet_put_int(c->self);
2549         }
2550         packet_send();
2551 }
2552
2553 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
2554 void
2555 deny_input_open(int type, int plen, void *ctxt)
2556 {
2557         int rchan = packet_get_int();
2558         switch(type){
2559         case SSH_SMSG_AGENT_OPEN:
2560                 error("Warning: ssh server tried agent forwarding.");
2561                 break;
2562         case SSH_SMSG_X11_OPEN:
2563                 error("Warning: ssh server tried X11 forwarding.");
2564                 break;
2565         default:
2566                 error("deny_input_open: type %d plen %d", type, plen);
2567                 break;
2568         }
2569         error("Warning: this is probably a break in attempt by a malicious server.");
2570         packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2571         packet_put_int(rchan);
2572         packet_send();
2573 }
2574
2575 /*
2576  * Requests forwarding of X11 connections, generates fake authentication
2577  * data, and enables authentication spoofing.
2578  */
2579
2580 void
2581 x11_request_forwarding_with_spoofing(int client_session_id,
2582     const char *proto, const char *data)
2583 {
2584         u_int data_len = (u_int) strlen(data) / 2;
2585         u_int i, value, len;
2586         char *new_data;
2587         int screen_number;
2588         const char *cp;
2589         u_int32_t rand = 0;
2590
2591         cp = getenv("DISPLAY");
2592         if (cp)
2593                 cp = strchr(cp, ':');
2594         if (cp)
2595                 cp = strchr(cp, '.');
2596         if (cp)
2597                 screen_number = atoi(cp + 1);
2598         else
2599                 screen_number = 0;
2600
2601         /* Save protocol name. */
2602         x11_saved_proto = xstrdup(proto);
2603
2604         /*
2605          * Extract real authentication data and generate fake data of the
2606          * same length.
2607          */
2608         x11_saved_data = xmalloc(data_len);
2609         x11_fake_data = xmalloc(data_len);
2610         for (i = 0; i < data_len; i++) {
2611                 if (sscanf(data + 2 * i, "%2x", &value) != 1)
2612                         fatal("x11_request_forwarding: bad authentication data: %.100s", data);
2613                 if (i % 4 == 0)
2614                         rand = arc4random();
2615                 x11_saved_data[i] = value;
2616                 x11_fake_data[i] = rand & 0xff;
2617                 rand >>= 8;
2618         }
2619         x11_saved_data_len = data_len;
2620         x11_fake_data_len = data_len;
2621
2622         /* Convert the fake data into hex. */
2623         len = 2 * data_len + 1;
2624         new_data = xmalloc(len);
2625         for (i = 0; i < data_len; i++)
2626                 snprintf(new_data + 2 * i, len - 2 * i,
2627                     "%02x", (u_char) x11_fake_data[i]);
2628
2629         /* Send the request packet. */
2630         if (compat20) {
2631                 channel_request_start(client_session_id, "x11-req", 0);
2632                 packet_put_char(0);     /* XXX bool single connection */
2633         } else {
2634                 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
2635         }
2636         packet_put_cstring(proto);
2637         packet_put_cstring(new_data);
2638         packet_put_int(screen_number);
2639         packet_send();
2640         packet_write_wait();
2641         xfree(new_data);
2642 }
2643
2644 /* Sends a message to the server to request authentication fd forwarding. */
2645
2646 void
2647 auth_request_forwarding()
2648 {
2649         packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
2650         packet_send();
2651         packet_write_wait();
2652 }
2653
2654 /*
2655  * Returns the name of the forwarded authentication socket.  Returns NULL if
2656  * there is no forwarded authentication socket.  The returned value points to
2657  * a static buffer.
2658  */
2659
2660 char *
2661 auth_get_socket_name()
2662 {
2663         return channel_forwarded_auth_socket_name;
2664 }
2665
2666 /* removes the agent forwarding socket */
2667
2668 void
2669 cleanup_socket(void)
2670 {
2671         unlink(channel_forwarded_auth_socket_name);
2672         rmdir(channel_forwarded_auth_socket_dir);
2673 }
2674
2675 /*
2676  * This is called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
2677  * This starts forwarding authentication requests.
2678  */
2679
2680 int
2681 auth_input_request_forwarding(struct passwd * pw)
2682 {
2683         Channel *nc;
2684         int sock;
2685         struct sockaddr_un sunaddr;
2686
2687         if (auth_get_socket_name() != NULL)
2688                 fatal("Protocol error: authentication forwarding requested twice.");
2689
2690         /* Temporarily drop privileged uid for mkdir/bind. */
2691         temporarily_use_uid(pw);
2692
2693         /* Allocate a buffer for the socket name, and format the name. */
2694         channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
2695         channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
2696         strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
2697
2698         /* Create private directory for socket */
2699         if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL) {
2700                 packet_send_debug("Agent forwarding disabled: mkdtemp() failed: %.100s",
2701                     strerror(errno));
2702                 restore_uid();
2703                 xfree(channel_forwarded_auth_socket_name);
2704                 xfree(channel_forwarded_auth_socket_dir);
2705                 channel_forwarded_auth_socket_name = NULL;
2706                 channel_forwarded_auth_socket_dir = NULL;
2707                 return 0;
2708         }
2709         snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME, "%s/agent.%d",
2710                  channel_forwarded_auth_socket_dir, (int) getpid());
2711
2712         if (atexit(cleanup_socket) < 0) {
2713                 int saved = errno;
2714                 cleanup_socket();
2715                 packet_disconnect("socket: %.100s", strerror(saved));
2716         }
2717         /* Create the socket. */
2718         sock = socket(AF_UNIX, SOCK_STREAM, 0);
2719         if (sock < 0)
2720                 packet_disconnect("socket: %.100s", strerror(errno));
2721
2722         /* Bind it to the name. */
2723         memset(&sunaddr, 0, sizeof(sunaddr));
2724         sunaddr.sun_family = AF_UNIX;
2725         strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
2726                 sizeof(sunaddr.sun_path));
2727
2728         if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
2729                 packet_disconnect("bind: %.100s", strerror(errno));
2730
2731         /* Restore the privileged uid. */
2732         restore_uid();
2733
2734         /* Start listening on the socket. */
2735         if (listen(sock, 5) < 0)
2736                 packet_disconnect("listen: %.100s", strerror(errno));
2737
2738         /* Allocate a channel for the authentication agent socket. */
2739         nc = channel_new("auth socket",
2740             SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
2741             CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2742             0, xstrdup("auth socket"), 1);
2743         if (nc == NULL) {
2744                 error("auth_input_request_forwarding: channel_new failed");
2745                 close(sock);
2746                 return 0;
2747         }
2748         strlcpy(nc->path, channel_forwarded_auth_socket_name, sizeof(nc->path));
2749         return 1;
2750 }
2751
2752 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
2753
2754 void
2755 auth_input_open_request(int type, int plen, void *ctxt)
2756 {
2757         Channel *c = NULL;
2758         int remote_id, sock;
2759         char *dummyname;
2760
2761         packet_integrity_check(plen, 4, type);
2762
2763         /* Read the remote channel number from the message. */
2764         remote_id = packet_get_int();
2765
2766         /*
2767          * Get a connection to the local authentication agent (this may again
2768          * get forwarded).
2769          */
2770         sock = ssh_get_authentication_socket();
2771
2772         /*
2773          * If we could not connect the agent, send an error message back to
2774          * the server. This should never happen unless the agent dies,
2775          * because authentication forwarding is only enabled if we have an
2776          * agent.
2777          */
2778         if (sock >= 0) {
2779                 dummyname = xstrdup("authentication agent connection");
2780                 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock, -1, 0, 0, 0, dummyname, 1);
2781                 if (c == NULL) {
2782                         error("auth_input_open_request: channel_new failed");
2783                         close(sock);
2784                 } else {
2785                         c->remote_id = remote_id;
2786                 }
2787         }
2788         if (c == NULL) {
2789                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2790                 packet_put_int(remote_id);
2791         } else {
2792                 /* Send a confirmation to the remote host. */
2793                 debug("Forwarding authentication connection.");
2794                 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2795                 packet_put_int(remote_id);
2796                 packet_put_int(c->self);
2797         }
2798         packet_send();
2799 }
2800
2801 void
2802 channel_start_open(int id)
2803 {
2804         Channel *c = channel_lookup(id);
2805         if (c == NULL) {
2806                 log("channel_open: %d: bad id", id);
2807                 return;
2808         }
2809         debug("send channel open %d", id);
2810         packet_start(SSH2_MSG_CHANNEL_OPEN);
2811         packet_put_cstring(c->ctype);
2812         packet_put_int(c->self);
2813         packet_put_int(c->local_window);
2814         packet_put_int(c->local_maxpacket);
2815 }
2816 void
2817 channel_open(int id)
2818 {
2819         /* XXX REMOVE ME */
2820         channel_start_open(id);
2821         packet_send();
2822 }
2823 void
2824 channel_request(int id, char *service, int wantconfirm)
2825 {
2826         channel_request_start(id, service, wantconfirm);
2827         packet_send();
2828         debug("channel request %d: %s", id, service) ;
2829 }
2830 void
2831 channel_request_start(int id, char *service, int wantconfirm)
2832 {
2833         Channel *c = channel_lookup(id);
2834         if (c == NULL) {
2835                 log("channel_request: %d: bad id", id);
2836                 return;
2837         }
2838         packet_start(SSH2_MSG_CHANNEL_REQUEST);
2839         packet_put_int(c->remote_id);
2840         packet_put_cstring(service);
2841         packet_put_char(wantconfirm);
2842 }
2843 void
2844 channel_register_callback(int id, int mtype, channel_callback_fn *fn, void *arg)
2845 {
2846         Channel *c = channel_lookup(id);
2847         if (c == NULL) {
2848                 log("channel_register_callback: %d: bad id", id);
2849                 return;
2850         }
2851         c->cb_event = mtype;
2852         c->cb_fn = fn;
2853         c->cb_arg = arg;
2854 }
2855 void
2856 channel_register_cleanup(int id, channel_callback_fn *fn)
2857 {
2858         Channel *c = channel_lookup(id);
2859         if (c == NULL) {
2860                 log("channel_register_cleanup: %d: bad id", id);
2861                 return;
2862         }
2863         c->dettach_user = fn;
2864 }
2865 void
2866 channel_cancel_cleanup(int id)
2867 {
2868         Channel *c = channel_lookup(id);
2869         if (c == NULL) {
2870                 log("channel_cancel_cleanup: %d: bad id", id);
2871                 return;
2872         }
2873         c->dettach_user = NULL;
2874 }
2875 void
2876 channel_register_filter(int id, channel_filter_fn *fn)
2877 {
2878         Channel *c = channel_lookup(id);
2879         if (c == NULL) {
2880                 log("channel_register_filter: %d: bad id", id);
2881                 return;
2882         }
2883         c->input_filter = fn;
2884 }
2885
2886 void
2887 channel_set_fds(int id, int rfd, int wfd, int efd,
2888     int extusage, int nonblock)
2889 {
2890         Channel *c = channel_lookup(id);
2891         if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
2892                 fatal("channel_activate for non-larval channel %d.", id);
2893         channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
2894         c->type = SSH_CHANNEL_OPEN;
2895         /* XXX window size? */
2896         c->local_window = c->local_window_max = c->local_maxpacket * 2;
2897         packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2898         packet_put_int(c->remote_id);
2899         packet_put_int(c->local_window);
2900         packet_send();
2901 }
This page took 0.337385 seconds and 5 git commands to generate.