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