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