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