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