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