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