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