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