]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssh/channels.c
Merge llvm-project 13.0.0 release
[FreeBSD/FreeBSD.git] / crypto / openssh / channels.c
1 /* $OpenBSD: channels.c,v 1.407 2021/05/19 01:24:05 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * This file contains functions for generic socket connection forwarding.
7  * There is also code for initiating connection forwarding for X11 connections,
8  * arbitrary tcp/ip connections, and the authentication agent connection.
9  *
10  * As far as I am concerned, the code I have written for this software
11  * can be used freely for any purpose.  Any derived versions of this
12  * software must be clearly marked as such, and if the derived work is
13  * incompatible with the protocol description in the RFC file, it must be
14  * called by a name other than "ssh" or "Secure Shell".
15  *
16  * SSH2 support added by Markus Friedl.
17  * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl.  All rights reserved.
18  * Copyright (c) 1999 Dug Song.  All rights reserved.
19  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
20  *
21  * Redistribution and use in source and binary forms, with or without
22  * modification, are permitted provided that the following conditions
23  * are met:
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  */
41
42 #include "includes.h"
43
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #include <sys/ioctl.h>
47 #include <sys/un.h>
48 #include <sys/socket.h>
49 #ifdef HAVE_SYS_TIME_H
50 # include <sys/time.h>
51 #endif
52
53 #include <netinet/in.h>
54 #include <arpa/inet.h>
55
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <limits.h>
59 #include <netdb.h>
60 #include <stdarg.h>
61 #ifdef HAVE_STDINT_H
62 # include <stdint.h>
63 #endif
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <termios.h>
68 #include <unistd.h>
69
70 #include "openbsd-compat/sys-queue.h"
71 #include "xmalloc.h"
72 #include "ssh.h"
73 #include "ssh2.h"
74 #include "ssherr.h"
75 #include "sshbuf.h"
76 #include "packet.h"
77 #include "log.h"
78 #include "misc.h"
79 #include "channels.h"
80 #include "compat.h"
81 #include "canohost.h"
82 #include "sshkey.h"
83 #include "authfd.h"
84 #include "pathnames.h"
85 #include "match.h"
86
87 /* -- agent forwarding */
88 #define NUM_SOCKS       10
89
90 /* -- tcp forwarding */
91 /* special-case port number meaning allow any port */
92 #define FWD_PERMIT_ANY_PORT     0
93
94 /* special-case wildcard meaning allow any host */
95 #define FWD_PERMIT_ANY_HOST     "*"
96
97 /* -- X11 forwarding */
98 /* Maximum number of fake X11 displays to try. */
99 #define MAX_DISPLAYS  1000
100
101 /* Per-channel callback for pre/post select() actions */
102 typedef void chan_fn(struct ssh *, Channel *c,
103     fd_set *readset, fd_set *writeset);
104
105 /*
106  * Data structure for storing which hosts are permitted for forward requests.
107  * The local sides of any remote forwards are stored in this array to prevent
108  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
109  * network (which might be behind a firewall).
110  */
111 /* XXX: streamlocal wants a path instead of host:port */
112 /*      Overload host_to_connect; we could just make this match Forward */
113 /*      XXX - can we use listen_host instead of listen_path? */
114 struct permission {
115         char *host_to_connect;          /* Connect to 'host'. */
116         int port_to_connect;            /* Connect to 'port'. */
117         char *listen_host;              /* Remote side should listen address. */
118         char *listen_path;              /* Remote side should listen path. */
119         int listen_port;                /* Remote side should listen port. */
120         Channel *downstream;            /* Downstream mux*/
121 };
122
123 /*
124  * Stores the forwarding permission state for a single direction (local or
125  * remote).
126  */
127 struct permission_set {
128         /*
129          * List of all local permitted host/port pairs to allow for the
130          * user.
131          */
132         u_int num_permitted_user;
133         struct permission *permitted_user;
134
135         /*
136          * List of all permitted host/port pairs to allow for the admin.
137          */
138         u_int num_permitted_admin;
139         struct permission *permitted_admin;
140
141         /*
142          * If this is true, all opens/listens are permitted.  This is the
143          * case on the server on which we have to trust the client anyway,
144          * and the user could do anything after logging in.
145          */
146         int all_permitted;
147 };
148
149 /* Master structure for channels state */
150 struct ssh_channels {
151         /*
152          * Pointer to an array containing all allocated channels.  The array
153          * is dynamically extended as needed.
154          */
155         Channel **channels;
156
157         /*
158          * Size of the channel array.  All slots of the array must always be
159          * initialized (at least the type field); unused slots set to NULL
160          */
161         u_int channels_alloc;
162
163         /*
164          * Maximum file descriptor value used in any of the channels.  This is
165          * updated in channel_new.
166          */
167         int channel_max_fd;
168
169         /*
170          * 'channel_pre*' are called just before select() to add any bits
171          * relevant to channels in the select bitmasks.
172          *
173          * 'channel_post*': perform any appropriate operations for
174          * channels which have events pending.
175          */
176         chan_fn **channel_pre;
177         chan_fn **channel_post;
178
179         /* -- tcp forwarding */
180         struct permission_set local_perms;
181         struct permission_set remote_perms;
182
183         /* -- X11 forwarding */
184
185         /* Saved X11 local (client) display. */
186         char *x11_saved_display;
187
188         /* Saved X11 authentication protocol name. */
189         char *x11_saved_proto;
190
191         /* Saved X11 authentication data.  This is the real data. */
192         char *x11_saved_data;
193         u_int x11_saved_data_len;
194
195         /* Deadline after which all X11 connections are refused */
196         u_int x11_refuse_time;
197
198         /*
199          * Fake X11 authentication data.  This is what the server will be
200          * sending us; we should replace any occurrences of this by the
201          * real data.
202          */
203         u_char *x11_fake_data;
204         u_int x11_fake_data_len;
205
206         /* AF_UNSPEC or AF_INET or AF_INET6 */
207         int IPv4or6;
208 };
209
210 /* helper */
211 static void port_open_helper(struct ssh *ssh, Channel *c, char *rtype);
212 static const char *channel_rfwd_bind_host(const char *listen_host);
213
214 /* non-blocking connect helpers */
215 static int connect_next(struct channel_connect *);
216 static void channel_connect_ctx_free(struct channel_connect *);
217 static Channel *rdynamic_connect_prepare(struct ssh *, char *, char *);
218 static int rdynamic_connect_finish(struct ssh *, Channel *);
219
220 /* Setup helper */
221 static void channel_handler_init(struct ssh_channels *sc);
222
223 /* -- channel core */
224
225 void
226 channel_init_channels(struct ssh *ssh)
227 {
228         struct ssh_channels *sc;
229
230         if ((sc = calloc(1, sizeof(*sc))) == NULL)
231                 fatal_f("allocation failed");
232         sc->channels_alloc = 10;
233         sc->channels = xcalloc(sc->channels_alloc, sizeof(*sc->channels));
234         sc->IPv4or6 = AF_UNSPEC;
235         channel_handler_init(sc);
236
237         ssh->chanctxt = sc;
238 }
239
240 Channel *
241 channel_by_id(struct ssh *ssh, int id)
242 {
243         Channel *c;
244
245         if (id < 0 || (u_int)id >= ssh->chanctxt->channels_alloc) {
246                 logit_f("%d: bad id", id);
247                 return NULL;
248         }
249         c = ssh->chanctxt->channels[id];
250         if (c == NULL) {
251                 logit_f("%d: bad id: channel free", id);
252                 return NULL;
253         }
254         return c;
255 }
256
257 Channel *
258 channel_by_remote_id(struct ssh *ssh, u_int remote_id)
259 {
260         Channel *c;
261         u_int i;
262
263         for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
264                 c = ssh->chanctxt->channels[i];
265                 if (c != NULL && c->have_remote_id && c->remote_id == remote_id)
266                         return c;
267         }
268         return NULL;
269 }
270
271 /*
272  * Returns the channel if it is allowed to receive protocol messages.
273  * Private channels, like listening sockets, may not receive messages.
274  */
275 Channel *
276 channel_lookup(struct ssh *ssh, int id)
277 {
278         Channel *c;
279
280         if ((c = channel_by_id(ssh, id)) == NULL)
281                 return NULL;
282
283         switch (c->type) {
284         case SSH_CHANNEL_X11_OPEN:
285         case SSH_CHANNEL_LARVAL:
286         case SSH_CHANNEL_CONNECTING:
287         case SSH_CHANNEL_DYNAMIC:
288         case SSH_CHANNEL_RDYNAMIC_OPEN:
289         case SSH_CHANNEL_RDYNAMIC_FINISH:
290         case SSH_CHANNEL_OPENING:
291         case SSH_CHANNEL_OPEN:
292         case SSH_CHANNEL_ABANDONED:
293         case SSH_CHANNEL_MUX_PROXY:
294                 return c;
295         }
296         logit("Non-public channel %d, type %d.", id, c->type);
297         return NULL;
298 }
299
300 /*
301  * Register filedescriptors for a channel, used when allocating a channel or
302  * when the channel consumer/producer is ready, e.g. shell exec'd
303  */
304 static void
305 channel_register_fds(struct ssh *ssh, Channel *c, int rfd, int wfd, int efd,
306     int extusage, int nonblock, int is_tty)
307 {
308         struct ssh_channels *sc = ssh->chanctxt;
309
310         /* Update the maximum file descriptor value. */
311         sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, rfd);
312         sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, wfd);
313         sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, efd);
314
315         if (rfd != -1)
316                 fcntl(rfd, F_SETFD, FD_CLOEXEC);
317         if (wfd != -1 && wfd != rfd)
318                 fcntl(wfd, F_SETFD, FD_CLOEXEC);
319         if (efd != -1 && efd != rfd && efd != wfd)
320                 fcntl(efd, F_SETFD, FD_CLOEXEC);
321
322         c->rfd = rfd;
323         c->wfd = wfd;
324         c->sock = (rfd == wfd) ? rfd : -1;
325         c->efd = efd;
326         c->extended_usage = extusage;
327
328         if ((c->isatty = is_tty) != 0)
329                 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
330 #ifdef _AIX
331         /* XXX: Later AIX versions can't push as much data to tty */
332         c->wfd_isatty = is_tty || isatty(c->wfd);
333 #endif
334
335         /* enable nonblocking mode */
336         c->restore_block = 0;
337         if (nonblock == CHANNEL_NONBLOCK_STDIO) {
338                 /*
339                  * Special handling for stdio file descriptors: do not set
340                  * non-blocking mode if they are TTYs. Otherwise prepare to
341                  * restore their blocking state on exit to avoid interfering
342                  * with other programs that follow.
343                  */
344                 if (rfd != -1 && !isatty(rfd) && fcntl(rfd, F_GETFL) == 0) {
345                         c->restore_block |= CHANNEL_RESTORE_RFD;
346                         set_nonblock(rfd);
347                 }
348                 if (wfd != -1 && !isatty(wfd) && fcntl(wfd, F_GETFL) == 0) {
349                         c->restore_block |= CHANNEL_RESTORE_WFD;
350                         set_nonblock(wfd);
351                 }
352                 if (efd != -1 && !isatty(efd) && fcntl(efd, F_GETFL) == 0) {
353                         c->restore_block |= CHANNEL_RESTORE_EFD;
354                         set_nonblock(efd);
355                 }
356         } else if (nonblock) {
357                 if (rfd != -1)
358                         set_nonblock(rfd);
359                 if (wfd != -1)
360                         set_nonblock(wfd);
361                 if (efd != -1)
362                         set_nonblock(efd);
363         }
364 }
365
366 /*
367  * Allocate a new channel object and set its type and socket. This will cause
368  * remote_name to be freed.
369  */
370 Channel *
371 channel_new(struct ssh *ssh, char *ctype, int type, int rfd, int wfd, int efd,
372     u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
373 {
374         struct ssh_channels *sc = ssh->chanctxt;
375         u_int i, found;
376         Channel *c;
377         int r;
378
379         /* Try to find a free slot where to put the new channel. */
380         for (i = 0; i < sc->channels_alloc; i++) {
381                 if (sc->channels[i] == NULL) {
382                         /* Found a free slot. */
383                         found = i;
384                         break;
385                 }
386         }
387         if (i >= sc->channels_alloc) {
388                 /*
389                  * There are no free slots. Take last+1 slot and expand
390                  * the array.
391                  */
392                 found = sc->channels_alloc;
393                 if (sc->channels_alloc > CHANNELS_MAX_CHANNELS)
394                         fatal_f("internal error: channels_alloc %d too big",
395                             sc->channels_alloc);
396                 sc->channels = xrecallocarray(sc->channels, sc->channels_alloc,
397                     sc->channels_alloc + 10, sizeof(*sc->channels));
398                 sc->channels_alloc += 10;
399                 debug2("channel: expanding %d", sc->channels_alloc);
400         }
401         /* Initialize and return new channel. */
402         c = sc->channels[found] = xcalloc(1, sizeof(Channel));
403         if ((c->input = sshbuf_new()) == NULL ||
404             (c->output = sshbuf_new()) == NULL ||
405             (c->extended = sshbuf_new()) == NULL)
406                 fatal_f("sshbuf_new failed");
407         if ((r = sshbuf_set_max_size(c->input, CHAN_INPUT_MAX)) != 0)
408                 fatal_fr(r, "sshbuf_set_max_size");
409         c->ostate = CHAN_OUTPUT_OPEN;
410         c->istate = CHAN_INPUT_OPEN;
411         channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, 0);
412         c->self = found;
413         c->type = type;
414         c->ctype = ctype;
415         c->local_window = window;
416         c->local_window_max = window;
417         c->local_maxpacket = maxpack;
418         c->remote_name = xstrdup(remote_name);
419         c->ctl_chan = -1;
420         c->delayed = 1;         /* prevent call to channel_post handler */
421         TAILQ_INIT(&c->status_confirms);
422         debug("channel %d: new [%s]", found, remote_name);
423         return c;
424 }
425
426 static void
427 channel_find_maxfd(struct ssh_channels *sc)
428 {
429         u_int i;
430         int max = 0;
431         Channel *c;
432
433         for (i = 0; i < sc->channels_alloc; i++) {
434                 c = sc->channels[i];
435                 if (c != NULL) {
436                         max = MAXIMUM(max, c->rfd);
437                         max = MAXIMUM(max, c->wfd);
438                         max = MAXIMUM(max, c->efd);
439                 }
440         }
441         sc->channel_max_fd = max;
442 }
443
444 int
445 channel_close_fd(struct ssh *ssh, Channel *c, int *fdp)
446 {
447         struct ssh_channels *sc = ssh->chanctxt;
448         int ret, fd = *fdp;
449
450         if (fd == -1)
451                 return 0;
452
453         if ((*fdp == c->rfd && (c->restore_block & CHANNEL_RESTORE_RFD) != 0) ||
454            (*fdp == c->wfd && (c->restore_block & CHANNEL_RESTORE_WFD) != 0) ||
455            (*fdp == c->efd && (c->restore_block & CHANNEL_RESTORE_EFD) != 0))
456                 (void)fcntl(*fdp, F_SETFL, 0);  /* restore blocking */
457
458         ret = close(fd);
459         *fdp = -1;
460         if (fd == sc->channel_max_fd)
461                 channel_find_maxfd(sc);
462         return ret;
463 }
464
465 /* Close all channel fd/socket. */
466 static void
467 channel_close_fds(struct ssh *ssh, Channel *c)
468 {
469         int sock = c->sock, rfd = c->rfd, wfd = c->wfd, efd = c->efd;
470
471         channel_close_fd(ssh, c, &c->sock);
472         if (rfd != sock)
473                 channel_close_fd(ssh, c, &c->rfd);
474         if (wfd != sock && wfd != rfd)
475                 channel_close_fd(ssh, c, &c->wfd);
476         if (efd != sock && efd != rfd && efd != wfd)
477                 channel_close_fd(ssh, c, &c->efd);
478 }
479
480 static void
481 fwd_perm_clear(struct permission *perm)
482 {
483         free(perm->host_to_connect);
484         free(perm->listen_host);
485         free(perm->listen_path);
486         memset(perm, 0, sizeof(*perm));
487 }
488
489 /* Returns an printable name for the specified forwarding permission list */
490 static const char *
491 fwd_ident(int who, int where)
492 {
493         if (who == FORWARD_ADM) {
494                 if (where == FORWARD_LOCAL)
495                         return "admin local";
496                 else if (where == FORWARD_REMOTE)
497                         return "admin remote";
498         } else if (who == FORWARD_USER) {
499                 if (where == FORWARD_LOCAL)
500                         return "user local";
501                 else if (where == FORWARD_REMOTE)
502                         return "user remote";
503         }
504         fatal("Unknown forward permission list %d/%d", who, where);
505 }
506
507 /* Returns the forwarding permission list for the specified direction */
508 static struct permission_set *
509 permission_set_get(struct ssh *ssh, int where)
510 {
511         struct ssh_channels *sc = ssh->chanctxt;
512
513         switch (where) {
514         case FORWARD_LOCAL:
515                 return &sc->local_perms;
516                 break;
517         case FORWARD_REMOTE:
518                 return &sc->remote_perms;
519                 break;
520         default:
521                 fatal_f("invalid forwarding direction %d", where);
522         }
523 }
524
525 /* Returns pointers to the specified forwarding list and its element count */
526 static void
527 permission_set_get_array(struct ssh *ssh, int who, int where,
528     struct permission ***permpp, u_int **npermpp)
529 {
530         struct permission_set *pset = permission_set_get(ssh, where);
531
532         switch (who) {
533         case FORWARD_USER:
534                 *permpp = &pset->permitted_user;
535                 *npermpp = &pset->num_permitted_user;
536                 break;
537         case FORWARD_ADM:
538                 *permpp = &pset->permitted_admin;
539                 *npermpp = &pset->num_permitted_admin;
540                 break;
541         default:
542                 fatal_f("invalid forwarding client %d", who);
543         }
544 }
545
546 /* Adds an entry to the spcified forwarding list */
547 static int
548 permission_set_add(struct ssh *ssh, int who, int where,
549     const char *host_to_connect, int port_to_connect,
550     const char *listen_host, const char *listen_path, int listen_port,
551     Channel *downstream)
552 {
553         struct permission **permp;
554         u_int n, *npermp;
555
556         permission_set_get_array(ssh, who, where, &permp, &npermp);
557
558         if (*npermp >= INT_MAX)
559                 fatal_f("%s overflow", fwd_ident(who, where));
560
561         *permp = xrecallocarray(*permp, *npermp, *npermp + 1, sizeof(**permp));
562         n = (*npermp)++;
563 #define MAYBE_DUP(s) ((s == NULL) ? NULL : xstrdup(s))
564         (*permp)[n].host_to_connect = MAYBE_DUP(host_to_connect);
565         (*permp)[n].port_to_connect = port_to_connect;
566         (*permp)[n].listen_host = MAYBE_DUP(listen_host);
567         (*permp)[n].listen_path = MAYBE_DUP(listen_path);
568         (*permp)[n].listen_port = listen_port;
569         (*permp)[n].downstream = downstream;
570 #undef MAYBE_DUP
571         return (int)n;
572 }
573
574 static void
575 mux_remove_remote_forwardings(struct ssh *ssh, Channel *c)
576 {
577         struct ssh_channels *sc = ssh->chanctxt;
578         struct permission_set *pset = &sc->local_perms;
579         struct permission *perm;
580         int r;
581         u_int i;
582
583         for (i = 0; i < pset->num_permitted_user; i++) {
584                 perm = &pset->permitted_user[i];
585                 if (perm->downstream != c)
586                         continue;
587
588                 /* cancel on the server, since mux client is gone */
589                 debug("channel %d: cleanup remote forward for %s:%u",
590                     c->self, perm->listen_host, perm->listen_port);
591                 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
592                     (r = sshpkt_put_cstring(ssh,
593                     "cancel-tcpip-forward")) != 0 ||
594                     (r = sshpkt_put_u8(ssh, 0)) != 0 ||
595                     (r = sshpkt_put_cstring(ssh,
596                     channel_rfwd_bind_host(perm->listen_host))) != 0 ||
597                     (r = sshpkt_put_u32(ssh, perm->listen_port)) != 0 ||
598                     (r = sshpkt_send(ssh)) != 0) {
599                         fatal_fr(r, "channel %i", c->self);
600                 }
601                 fwd_perm_clear(perm); /* unregister */
602         }
603 }
604
605 /* Free the channel and close its fd/socket. */
606 void
607 channel_free(struct ssh *ssh, Channel *c)
608 {
609         struct ssh_channels *sc = ssh->chanctxt;
610         char *s;
611         u_int i, n;
612         Channel *other;
613         struct channel_confirm *cc;
614
615         for (n = 0, i = 0; i < sc->channels_alloc; i++) {
616                 if ((other = sc->channels[i]) == NULL)
617                         continue;
618                 n++;
619                 /* detach from mux client and prepare for closing */
620                 if (c->type == SSH_CHANNEL_MUX_CLIENT &&
621                     other->type == SSH_CHANNEL_MUX_PROXY &&
622                     other->mux_ctx == c) {
623                         other->mux_ctx = NULL;
624                         other->type = SSH_CHANNEL_OPEN;
625                         other->istate = CHAN_INPUT_CLOSED;
626                         other->ostate = CHAN_OUTPUT_CLOSED;
627                 }
628         }
629         debug("channel %d: free: %s, nchannels %u", c->self,
630             c->remote_name ? c->remote_name : "???", n);
631
632         if (c->type == SSH_CHANNEL_MUX_CLIENT)
633                 mux_remove_remote_forwardings(ssh, c);
634         else if (c->type == SSH_CHANNEL_MUX_LISTENER) {
635                 free(c->mux_ctx);
636                 c->mux_ctx = NULL;
637         }
638
639         if (log_level_get() >= SYSLOG_LEVEL_DEBUG3) {
640                 s = channel_open_message(ssh);
641                 debug3("channel %d: status: %s", c->self, s);
642                 free(s);
643         }
644
645         channel_close_fds(ssh, c);
646         sshbuf_free(c->input);
647         sshbuf_free(c->output);
648         sshbuf_free(c->extended);
649         c->input = c->output = c->extended = NULL;
650         free(c->remote_name);
651         c->remote_name = NULL;
652         free(c->path);
653         c->path = NULL;
654         free(c->listening_addr);
655         c->listening_addr = NULL;
656         while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
657                 if (cc->abandon_cb != NULL)
658                         cc->abandon_cb(ssh, c, cc->ctx);
659                 TAILQ_REMOVE(&c->status_confirms, cc, entry);
660                 freezero(cc, sizeof(*cc));
661         }
662         if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
663                 c->filter_cleanup(ssh, c->self, c->filter_ctx);
664         sc->channels[c->self] = NULL;
665         freezero(c, sizeof(*c));
666 }
667
668 void
669 channel_free_all(struct ssh *ssh)
670 {
671         u_int i;
672         struct ssh_channels *sc = ssh->chanctxt;
673
674         for (i = 0; i < sc->channels_alloc; i++)
675                 if (sc->channels[i] != NULL)
676                         channel_free(ssh, sc->channels[i]);
677
678         free(sc->channels);
679         sc->channels = NULL;
680         sc->channels_alloc = 0;
681         sc->channel_max_fd = 0;
682
683         free(sc->x11_saved_display);
684         sc->x11_saved_display = NULL;
685
686         free(sc->x11_saved_proto);
687         sc->x11_saved_proto = NULL;
688
689         free(sc->x11_saved_data);
690         sc->x11_saved_data = NULL;
691         sc->x11_saved_data_len = 0;
692
693         free(sc->x11_fake_data);
694         sc->x11_fake_data = NULL;
695         sc->x11_fake_data_len = 0;
696 }
697
698 /*
699  * Closes the sockets/fds of all channels.  This is used to close extra file
700  * descriptors after a fork.
701  */
702 void
703 channel_close_all(struct ssh *ssh)
704 {
705         u_int i;
706
707         for (i = 0; i < ssh->chanctxt->channels_alloc; i++)
708                 if (ssh->chanctxt->channels[i] != NULL)
709                         channel_close_fds(ssh, ssh->chanctxt->channels[i]);
710 }
711
712 /*
713  * Stop listening to channels.
714  */
715 void
716 channel_stop_listening(struct ssh *ssh)
717 {
718         u_int i;
719         Channel *c;
720
721         for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
722                 c = ssh->chanctxt->channels[i];
723                 if (c != NULL) {
724                         switch (c->type) {
725                         case SSH_CHANNEL_AUTH_SOCKET:
726                         case SSH_CHANNEL_PORT_LISTENER:
727                         case SSH_CHANNEL_RPORT_LISTENER:
728                         case SSH_CHANNEL_X11_LISTENER:
729                         case SSH_CHANNEL_UNIX_LISTENER:
730                         case SSH_CHANNEL_RUNIX_LISTENER:
731                                 channel_close_fd(ssh, c, &c->sock);
732                                 channel_free(ssh, c);
733                                 break;
734                         }
735                 }
736         }
737 }
738
739 /*
740  * Returns true if no channel has too much buffered data, and false if one or
741  * more channel is overfull.
742  */
743 int
744 channel_not_very_much_buffered_data(struct ssh *ssh)
745 {
746         u_int i;
747         u_int maxsize = ssh_packet_get_maxsize(ssh);
748         Channel *c;
749
750         for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
751                 c = ssh->chanctxt->channels[i];
752                 if (c == NULL || c->type != SSH_CHANNEL_OPEN)
753                         continue;
754                 if (sshbuf_len(c->output) > maxsize) {
755                         debug2("channel %d: big output buffer %zu > %u",
756                             c->self, sshbuf_len(c->output), maxsize);
757                         return 0;
758                 }
759         }
760         return 1;
761 }
762
763 /* Returns true if any channel is still open. */
764 int
765 channel_still_open(struct ssh *ssh)
766 {
767         u_int i;
768         Channel *c;
769
770         for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
771                 c = ssh->chanctxt->channels[i];
772                 if (c == NULL)
773                         continue;
774                 switch (c->type) {
775                 case SSH_CHANNEL_X11_LISTENER:
776                 case SSH_CHANNEL_PORT_LISTENER:
777                 case SSH_CHANNEL_RPORT_LISTENER:
778                 case SSH_CHANNEL_MUX_LISTENER:
779                 case SSH_CHANNEL_CLOSED:
780                 case SSH_CHANNEL_AUTH_SOCKET:
781                 case SSH_CHANNEL_DYNAMIC:
782                 case SSH_CHANNEL_RDYNAMIC_OPEN:
783                 case SSH_CHANNEL_CONNECTING:
784                 case SSH_CHANNEL_ZOMBIE:
785                 case SSH_CHANNEL_ABANDONED:
786                 case SSH_CHANNEL_UNIX_LISTENER:
787                 case SSH_CHANNEL_RUNIX_LISTENER:
788                         continue;
789                 case SSH_CHANNEL_LARVAL:
790                         continue;
791                 case SSH_CHANNEL_OPENING:
792                 case SSH_CHANNEL_OPEN:
793                 case SSH_CHANNEL_RDYNAMIC_FINISH:
794                 case SSH_CHANNEL_X11_OPEN:
795                 case SSH_CHANNEL_MUX_CLIENT:
796                 case SSH_CHANNEL_MUX_PROXY:
797                         return 1;
798                 default:
799                         fatal_f("bad channel type %d", c->type);
800                         /* NOTREACHED */
801                 }
802         }
803         return 0;
804 }
805
806 /* Returns the id of an open channel suitable for keepaliving */
807 int
808 channel_find_open(struct ssh *ssh)
809 {
810         u_int i;
811         Channel *c;
812
813         for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
814                 c = ssh->chanctxt->channels[i];
815                 if (c == NULL || !c->have_remote_id)
816                         continue;
817                 switch (c->type) {
818                 case SSH_CHANNEL_CLOSED:
819                 case SSH_CHANNEL_DYNAMIC:
820                 case SSH_CHANNEL_RDYNAMIC_OPEN:
821                 case SSH_CHANNEL_RDYNAMIC_FINISH:
822                 case SSH_CHANNEL_X11_LISTENER:
823                 case SSH_CHANNEL_PORT_LISTENER:
824                 case SSH_CHANNEL_RPORT_LISTENER:
825                 case SSH_CHANNEL_MUX_LISTENER:
826                 case SSH_CHANNEL_MUX_CLIENT:
827                 case SSH_CHANNEL_MUX_PROXY:
828                 case SSH_CHANNEL_OPENING:
829                 case SSH_CHANNEL_CONNECTING:
830                 case SSH_CHANNEL_ZOMBIE:
831                 case SSH_CHANNEL_ABANDONED:
832                 case SSH_CHANNEL_UNIX_LISTENER:
833                 case SSH_CHANNEL_RUNIX_LISTENER:
834                         continue;
835                 case SSH_CHANNEL_LARVAL:
836                 case SSH_CHANNEL_AUTH_SOCKET:
837                 case SSH_CHANNEL_OPEN:
838                 case SSH_CHANNEL_X11_OPEN:
839                         return i;
840                 default:
841                         fatal_f("bad channel type %d", c->type);
842                         /* NOTREACHED */
843                 }
844         }
845         return -1;
846 }
847
848 /* Returns the state of the channel's extended usage flag */
849 const char *
850 channel_format_extended_usage(const Channel *c)
851 {
852         if (c->efd == -1)
853                 return "closed";
854
855         switch (c->extended_usage) {
856         case CHAN_EXTENDED_WRITE:
857                 return "write";
858         case CHAN_EXTENDED_READ:
859                 return "read";
860         case CHAN_EXTENDED_IGNORE:
861                 return "ignore";
862         default:
863                 return "UNKNOWN";
864         }
865 }
866
867 static char *
868 channel_format_status(const Channel *c)
869 {
870         char *ret = NULL;
871
872         xasprintf(&ret, "t%d %s%u i%u/%zu o%u/%zu e[%s]/%zu "
873             "fd %d/%d/%d sock %d cc %d",
874             c->type,
875             c->have_remote_id ? "r" : "nr", c->remote_id,
876             c->istate, sshbuf_len(c->input),
877             c->ostate, sshbuf_len(c->output),
878             channel_format_extended_usage(c), sshbuf_len(c->extended),
879             c->rfd, c->wfd, c->efd, c->sock, c->ctl_chan);
880         return ret;
881 }
882
883 /*
884  * Returns a message describing the currently open forwarded connections,
885  * suitable for sending to the client.  The message contains crlf pairs for
886  * newlines.
887  */
888 char *
889 channel_open_message(struct ssh *ssh)
890 {
891         struct sshbuf *buf;
892         Channel *c;
893         u_int i;
894         int r;
895         char *cp, *ret;
896
897         if ((buf = sshbuf_new()) == NULL)
898                 fatal_f("sshbuf_new");
899         if ((r = sshbuf_putf(buf,
900             "The following connections are open:\r\n")) != 0)
901                 fatal_fr(r, "sshbuf_putf");
902         for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
903                 c = ssh->chanctxt->channels[i];
904                 if (c == NULL)
905                         continue;
906                 switch (c->type) {
907                 case SSH_CHANNEL_X11_LISTENER:
908                 case SSH_CHANNEL_PORT_LISTENER:
909                 case SSH_CHANNEL_RPORT_LISTENER:
910                 case SSH_CHANNEL_CLOSED:
911                 case SSH_CHANNEL_AUTH_SOCKET:
912                 case SSH_CHANNEL_ZOMBIE:
913                 case SSH_CHANNEL_ABANDONED:
914                 case SSH_CHANNEL_MUX_LISTENER:
915                 case SSH_CHANNEL_UNIX_LISTENER:
916                 case SSH_CHANNEL_RUNIX_LISTENER:
917                         continue;
918                 case SSH_CHANNEL_LARVAL:
919                 case SSH_CHANNEL_OPENING:
920                 case SSH_CHANNEL_CONNECTING:
921                 case SSH_CHANNEL_DYNAMIC:
922                 case SSH_CHANNEL_RDYNAMIC_OPEN:
923                 case SSH_CHANNEL_RDYNAMIC_FINISH:
924                 case SSH_CHANNEL_OPEN:
925                 case SSH_CHANNEL_X11_OPEN:
926                 case SSH_CHANNEL_MUX_PROXY:
927                 case SSH_CHANNEL_MUX_CLIENT:
928                         cp = channel_format_status(c);
929                         if ((r = sshbuf_putf(buf, "  #%d %.300s (%s)\r\n",
930                             c->self, c->remote_name, cp)) != 0) {
931                                 free(cp);
932                                 fatal_fr(r, "sshbuf_putf");
933                         }
934                         free(cp);
935                         continue;
936                 default:
937                         fatal_f("bad channel type %d", c->type);
938                         /* NOTREACHED */
939                 }
940         }
941         if ((ret = sshbuf_dup_string(buf)) == NULL)
942                 fatal_f("sshbuf_dup_string");
943         sshbuf_free(buf);
944         return ret;
945 }
946
947 static void
948 open_preamble(struct ssh *ssh, const char *where, Channel *c, const char *type)
949 {
950         int r;
951
952         if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
953             (r = sshpkt_put_cstring(ssh, type)) != 0 ||
954             (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
955             (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
956             (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0) {
957                 fatal_r(r, "%s: channel %i: open", where, c->self);
958         }
959 }
960
961 void
962 channel_send_open(struct ssh *ssh, int id)
963 {
964         Channel *c = channel_lookup(ssh, id);
965         int r;
966
967         if (c == NULL) {
968                 logit("channel_send_open: %d: bad id", id);
969                 return;
970         }
971         debug2("channel %d: send open", id);
972         open_preamble(ssh, __func__, c, c->ctype);
973         if ((r = sshpkt_send(ssh)) != 0)
974                 fatal_fr(r, "channel %i", c->self);
975 }
976
977 void
978 channel_request_start(struct ssh *ssh, int id, char *service, int wantconfirm)
979 {
980         Channel *c = channel_lookup(ssh, id);
981         int r;
982
983         if (c == NULL) {
984                 logit_f("%d: unknown channel id", id);
985                 return;
986         }
987         if (!c->have_remote_id)
988                 fatal_f("channel %d: no remote id", c->self);
989
990         debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
991         if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_REQUEST)) != 0 ||
992             (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
993             (r = sshpkt_put_cstring(ssh, service)) != 0 ||
994             (r = sshpkt_put_u8(ssh, wantconfirm)) != 0) {
995                 fatal_fr(r, "channel %i", c->self);
996         }
997 }
998
999 void
1000 channel_register_status_confirm(struct ssh *ssh, int id,
1001     channel_confirm_cb *cb, channel_confirm_abandon_cb *abandon_cb, void *ctx)
1002 {
1003         struct channel_confirm *cc;
1004         Channel *c;
1005
1006         if ((c = channel_lookup(ssh, id)) == NULL)
1007                 fatal_f("%d: bad id", id);
1008
1009         cc = xcalloc(1, sizeof(*cc));
1010         cc->cb = cb;
1011         cc->abandon_cb = abandon_cb;
1012         cc->ctx = ctx;
1013         TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
1014 }
1015
1016 void
1017 channel_register_open_confirm(struct ssh *ssh, int id,
1018     channel_open_fn *fn, void *ctx)
1019 {
1020         Channel *c = channel_lookup(ssh, id);
1021
1022         if (c == NULL) {
1023                 logit_f("%d: bad id", id);
1024                 return;
1025         }
1026         c->open_confirm = fn;
1027         c->open_confirm_ctx = ctx;
1028 }
1029
1030 void
1031 channel_register_cleanup(struct ssh *ssh, int id,
1032     channel_callback_fn *fn, int do_close)
1033 {
1034         Channel *c = channel_by_id(ssh, id);
1035
1036         if (c == NULL) {
1037                 logit_f("%d: bad id", id);
1038                 return;
1039         }
1040         c->detach_user = fn;
1041         c->detach_close = do_close;
1042 }
1043
1044 void
1045 channel_cancel_cleanup(struct ssh *ssh, int id)
1046 {
1047         Channel *c = channel_by_id(ssh, id);
1048
1049         if (c == NULL) {
1050                 logit_f("%d: bad id", id);
1051                 return;
1052         }
1053         c->detach_user = NULL;
1054         c->detach_close = 0;
1055 }
1056
1057 void
1058 channel_register_filter(struct ssh *ssh, int id, channel_infilter_fn *ifn,
1059     channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
1060 {
1061         Channel *c = channel_lookup(ssh, id);
1062
1063         if (c == NULL) {
1064                 logit_f("%d: bad id", id);
1065                 return;
1066         }
1067         c->input_filter = ifn;
1068         c->output_filter = ofn;
1069         c->filter_ctx = ctx;
1070         c->filter_cleanup = cfn;
1071 }
1072
1073 void
1074 channel_set_fds(struct ssh *ssh, int id, int rfd, int wfd, int efd,
1075     int extusage, int nonblock, int is_tty, u_int window_max)
1076 {
1077         Channel *c = channel_lookup(ssh, id);
1078         int r;
1079
1080         if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
1081                 fatal("channel_activate for non-larval channel %d.", id);
1082         if (!c->have_remote_id)
1083                 fatal_f("channel %d: no remote id", c->self);
1084
1085         channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, is_tty);
1086         c->type = SSH_CHANNEL_OPEN;
1087         c->local_window = c->local_window_max = window_max;
1088
1089         if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
1090             (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1091             (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1092             (r = sshpkt_send(ssh)) != 0)
1093                 fatal_fr(r, "channel %i", c->self);
1094 }
1095
1096 static void
1097 channel_pre_listener(struct ssh *ssh, Channel *c,
1098     fd_set *readset, fd_set *writeset)
1099 {
1100         FD_SET(c->sock, readset);
1101 }
1102
1103 static void
1104 channel_pre_connecting(struct ssh *ssh, Channel *c,
1105     fd_set *readset, fd_set *writeset)
1106 {
1107         debug3("channel %d: waiting for connection", c->self);
1108         FD_SET(c->sock, writeset);
1109 }
1110
1111 static void
1112 channel_pre_open(struct ssh *ssh, Channel *c,
1113     fd_set *readset, fd_set *writeset)
1114 {
1115         if (c->istate == CHAN_INPUT_OPEN &&
1116             c->remote_window > 0 &&
1117             sshbuf_len(c->input) < c->remote_window &&
1118             sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1119                 FD_SET(c->rfd, readset);
1120         if (c->ostate == CHAN_OUTPUT_OPEN ||
1121             c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1122                 if (sshbuf_len(c->output) > 0) {
1123                         FD_SET(c->wfd, writeset);
1124                 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1125                         if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
1126                                 debug2("channel %d: "
1127                                     "obuf_empty delayed efd %d/(%zu)", c->self,
1128                                     c->efd, sshbuf_len(c->extended));
1129                         else
1130                                 chan_obuf_empty(ssh, c);
1131                 }
1132         }
1133         /** XXX check close conditions, too */
1134         if (c->efd != -1 && !(c->istate == CHAN_INPUT_CLOSED &&
1135             c->ostate == CHAN_OUTPUT_CLOSED)) {
1136                 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1137                     sshbuf_len(c->extended) > 0)
1138                         FD_SET(c->efd, writeset);
1139                 else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
1140                     (c->extended_usage == CHAN_EXTENDED_READ ||
1141                     c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1142                     sshbuf_len(c->extended) < c->remote_window)
1143                         FD_SET(c->efd, readset);
1144         }
1145         /* XXX: What about efd? races? */
1146 }
1147
1148 /*
1149  * This is a special state for X11 authentication spoofing.  An opened X11
1150  * connection (when authentication spoofing is being done) remains in this
1151  * state until the first packet has been completely read.  The authentication
1152  * data in that packet is then substituted by the real data if it matches the
1153  * fake data, and the channel is put into normal mode.
1154  * XXX All this happens at the client side.
1155  * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
1156  */
1157 static int
1158 x11_open_helper(struct ssh *ssh, struct sshbuf *b)
1159 {
1160         struct ssh_channels *sc = ssh->chanctxt;
1161         u_char *ucp;
1162         u_int proto_len, data_len;
1163
1164         /* Is this being called after the refusal deadline? */
1165         if (sc->x11_refuse_time != 0 &&
1166             (u_int)monotime() >= sc->x11_refuse_time) {
1167                 verbose("Rejected X11 connection after ForwardX11Timeout "
1168                     "expired");
1169                 return -1;
1170         }
1171
1172         /* Check if the fixed size part of the packet is in buffer. */
1173         if (sshbuf_len(b) < 12)
1174                 return 0;
1175
1176         /* Parse the lengths of variable-length fields. */
1177         ucp = sshbuf_mutable_ptr(b);
1178         if (ucp[0] == 0x42) {   /* Byte order MSB first. */
1179                 proto_len = 256 * ucp[6] + ucp[7];
1180                 data_len = 256 * ucp[8] + ucp[9];
1181         } else if (ucp[0] == 0x6c) {    /* Byte order LSB first. */
1182                 proto_len = ucp[6] + 256 * ucp[7];
1183                 data_len = ucp[8] + 256 * ucp[9];
1184         } else {
1185                 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
1186                     ucp[0]);
1187                 return -1;
1188         }
1189
1190         /* Check if the whole packet is in buffer. */
1191         if (sshbuf_len(b) <
1192             12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
1193                 return 0;
1194
1195         /* Check if authentication protocol matches. */
1196         if (proto_len != strlen(sc->x11_saved_proto) ||
1197             memcmp(ucp + 12, sc->x11_saved_proto, proto_len) != 0) {
1198                 debug2("X11 connection uses different authentication protocol.");
1199                 return -1;
1200         }
1201         /* Check if authentication data matches our fake data. */
1202         if (data_len != sc->x11_fake_data_len ||
1203             timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
1204                 sc->x11_fake_data, sc->x11_fake_data_len) != 0) {
1205                 debug2("X11 auth data does not match fake data.");
1206                 return -1;
1207         }
1208         /* Check fake data length */
1209         if (sc->x11_fake_data_len != sc->x11_saved_data_len) {
1210                 error("X11 fake_data_len %d != saved_data_len %d",
1211                     sc->x11_fake_data_len, sc->x11_saved_data_len);
1212                 return -1;
1213         }
1214         /*
1215          * Received authentication protocol and data match
1216          * our fake data. Substitute the fake data with real
1217          * data.
1218          */
1219         memcpy(ucp + 12 + ((proto_len + 3) & ~3),
1220             sc->x11_saved_data, sc->x11_saved_data_len);
1221         return 1;
1222 }
1223
1224 static void
1225 channel_pre_x11_open(struct ssh *ssh, Channel *c,
1226     fd_set *readset, fd_set *writeset)
1227 {
1228         int ret = x11_open_helper(ssh, c->output);
1229
1230         /* c->force_drain = 1; */
1231
1232         if (ret == 1) {
1233                 c->type = SSH_CHANNEL_OPEN;
1234                 channel_pre_open(ssh, c, readset, writeset);
1235         } else if (ret == -1) {
1236                 logit("X11 connection rejected because of wrong authentication.");
1237                 debug2("X11 rejected %d i%d/o%d",
1238                     c->self, c->istate, c->ostate);
1239                 chan_read_failed(ssh, c);
1240                 sshbuf_reset(c->input);
1241                 chan_ibuf_empty(ssh, c);
1242                 sshbuf_reset(c->output);
1243                 chan_write_failed(ssh, c);
1244                 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
1245         }
1246 }
1247
1248 static void
1249 channel_pre_mux_client(struct ssh *ssh,
1250     Channel *c, fd_set *readset, fd_set *writeset)
1251 {
1252         if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
1253             sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1254                 FD_SET(c->rfd, readset);
1255         if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1256                 /* clear buffer immediately (discard any partial packet) */
1257                 sshbuf_reset(c->input);
1258                 chan_ibuf_empty(ssh, c);
1259                 /* Start output drain. XXX just kill chan? */
1260                 chan_rcvd_oclose(ssh, c);
1261         }
1262         if (c->ostate == CHAN_OUTPUT_OPEN ||
1263             c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1264                 if (sshbuf_len(c->output) > 0)
1265                         FD_SET(c->wfd, writeset);
1266                 else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
1267                         chan_obuf_empty(ssh, c);
1268         }
1269 }
1270
1271 /* try to decode a socks4 header */
1272 static int
1273 channel_decode_socks4(Channel *c, struct sshbuf *input, struct sshbuf *output)
1274 {
1275         const u_char *p;
1276         char *host;
1277         u_int len, have, i, found, need;
1278         char username[256];
1279         struct {
1280                 u_int8_t version;
1281                 u_int8_t command;
1282                 u_int16_t dest_port;
1283                 struct in_addr dest_addr;
1284         } s4_req, s4_rsp;
1285         int r;
1286
1287         debug2("channel %d: decode socks4", c->self);
1288
1289         have = sshbuf_len(input);
1290         len = sizeof(s4_req);
1291         if (have < len)
1292                 return 0;
1293         p = sshbuf_ptr(input);
1294
1295         need = 1;
1296         /* SOCKS4A uses an invalid IP address 0.0.0.x */
1297         if (p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] != 0) {
1298                 debug2("channel %d: socks4a request", c->self);
1299                 /* ... and needs an extra string (the hostname) */
1300                 need = 2;
1301         }
1302         /* Check for terminating NUL on the string(s) */
1303         for (found = 0, i = len; i < have; i++) {
1304                 if (p[i] == '\0') {
1305                         found++;
1306                         if (found == need)
1307                                 break;
1308                 }
1309                 if (i > 1024) {
1310                         /* the peer is probably sending garbage */
1311                         debug("channel %d: decode socks4: too long",
1312                             c->self);
1313                         return -1;
1314                 }
1315         }
1316         if (found < need)
1317                 return 0;
1318         if ((r = sshbuf_get(input, &s4_req.version, 1)) != 0 ||
1319             (r = sshbuf_get(input, &s4_req.command, 1)) != 0 ||
1320             (r = sshbuf_get(input, &s4_req.dest_port, 2)) != 0 ||
1321             (r = sshbuf_get(input, &s4_req.dest_addr, 4)) != 0) {
1322                 debug_r(r, "channels %d: decode socks4", c->self);
1323                 return -1;
1324         }
1325         have = sshbuf_len(input);
1326         p = sshbuf_ptr(input);
1327         if (memchr(p, '\0', have) == NULL) {
1328                 error("channel %d: decode socks4: unterminated user", c->self);
1329                 return -1;
1330         }
1331         len = strlen(p);
1332         debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1333         len++; /* trailing '\0' */
1334         strlcpy(username, p, sizeof(username));
1335         if ((r = sshbuf_consume(input, len)) != 0)
1336                 fatal_fr(r, "channel %d: consume", c->self);
1337         free(c->path);
1338         c->path = NULL;
1339         if (need == 1) {                        /* SOCKS4: one string */
1340                 host = inet_ntoa(s4_req.dest_addr);
1341                 c->path = xstrdup(host);
1342         } else {                                /* SOCKS4A: two strings */
1343                 have = sshbuf_len(input);
1344                 p = sshbuf_ptr(input);
1345                 if (memchr(p, '\0', have) == NULL) {
1346                         error("channel %d: decode socks4a: host not nul "
1347                             "terminated", c->self);
1348                         return -1;
1349                 }
1350                 len = strlen(p);
1351                 debug2("channel %d: decode socks4a: host %s/%d",
1352                     c->self, p, len);
1353                 len++;                          /* trailing '\0' */
1354                 if (len > NI_MAXHOST) {
1355                         error("channel %d: hostname \"%.100s\" too long",
1356                             c->self, p);
1357                         return -1;
1358                 }
1359                 c->path = xstrdup(p);
1360                 if ((r = sshbuf_consume(input, len)) != 0)
1361                         fatal_fr(r, "channel %d: consume", c->self);
1362         }
1363         c->host_port = ntohs(s4_req.dest_port);
1364
1365         debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1366             c->self, c->path, c->host_port, s4_req.command);
1367
1368         if (s4_req.command != 1) {
1369                 debug("channel %d: cannot handle: %s cn %d",
1370                     c->self, need == 1 ? "SOCKS4" : "SOCKS4A", s4_req.command);
1371                 return -1;
1372         }
1373         s4_rsp.version = 0;                     /* vn: 0 for reply */
1374         s4_rsp.command = 90;                    /* cd: req granted */
1375         s4_rsp.dest_port = 0;                   /* ignored */
1376         s4_rsp.dest_addr.s_addr = INADDR_ANY;   /* ignored */
1377         if ((r = sshbuf_put(output, &s4_rsp, sizeof(s4_rsp))) != 0)
1378                 fatal_fr(r, "channel %d: append reply", c->self);
1379         return 1;
1380 }
1381
1382 /* try to decode a socks5 header */
1383 #define SSH_SOCKS5_AUTHDONE     0x1000
1384 #define SSH_SOCKS5_NOAUTH       0x00
1385 #define SSH_SOCKS5_IPV4         0x01
1386 #define SSH_SOCKS5_DOMAIN       0x03
1387 #define SSH_SOCKS5_IPV6         0x04
1388 #define SSH_SOCKS5_CONNECT      0x01
1389 #define SSH_SOCKS5_SUCCESS      0x00
1390
1391 static int
1392 channel_decode_socks5(Channel *c, struct sshbuf *input, struct sshbuf *output)
1393 {
1394         /* XXX use get/put_u8 instead of trusting struct padding */
1395         struct {
1396                 u_int8_t version;
1397                 u_int8_t command;
1398                 u_int8_t reserved;
1399                 u_int8_t atyp;
1400         } s5_req, s5_rsp;
1401         u_int16_t dest_port;
1402         char dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
1403         const u_char *p;
1404         u_int have, need, i, found, nmethods, addrlen, af;
1405         int r;
1406
1407         debug2("channel %d: decode socks5", c->self);
1408         p = sshbuf_ptr(input);
1409         if (p[0] != 0x05)
1410                 return -1;
1411         have = sshbuf_len(input);
1412         if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1413                 /* format: ver | nmethods | methods */
1414                 if (have < 2)
1415                         return 0;
1416                 nmethods = p[1];
1417                 if (have < nmethods + 2)
1418                         return 0;
1419                 /* look for method: "NO AUTHENTICATION REQUIRED" */
1420                 for (found = 0, i = 2; i < nmethods + 2; i++) {
1421                         if (p[i] == SSH_SOCKS5_NOAUTH) {
1422                                 found = 1;
1423                                 break;
1424                         }
1425                 }
1426                 if (!found) {
1427                         debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1428                             c->self);
1429                         return -1;
1430                 }
1431                 if ((r = sshbuf_consume(input, nmethods + 2)) != 0)
1432                         fatal_fr(r, "channel %d: consume", c->self);
1433                 /* version, method */
1434                 if ((r = sshbuf_put_u8(output, 0x05)) != 0 ||
1435                     (r = sshbuf_put_u8(output, SSH_SOCKS5_NOAUTH)) != 0)
1436                         fatal_fr(r, "channel %d: append reply", c->self);
1437                 c->flags |= SSH_SOCKS5_AUTHDONE;
1438                 debug2("channel %d: socks5 auth done", c->self);
1439                 return 0;                               /* need more */
1440         }
1441         debug2("channel %d: socks5 post auth", c->self);
1442         if (have < sizeof(s5_req)+1)
1443                 return 0;                       /* need more */
1444         memcpy(&s5_req, p, sizeof(s5_req));
1445         if (s5_req.version != 0x05 ||
1446             s5_req.command != SSH_SOCKS5_CONNECT ||
1447             s5_req.reserved != 0x00) {
1448                 debug2("channel %d: only socks5 connect supported", c->self);
1449                 return -1;
1450         }
1451         switch (s5_req.atyp){
1452         case SSH_SOCKS5_IPV4:
1453                 addrlen = 4;
1454                 af = AF_INET;
1455                 break;
1456         case SSH_SOCKS5_DOMAIN:
1457                 addrlen = p[sizeof(s5_req)];
1458                 af = -1;
1459                 break;
1460         case SSH_SOCKS5_IPV6:
1461                 addrlen = 16;
1462                 af = AF_INET6;
1463                 break;
1464         default:
1465                 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1466                 return -1;
1467         }
1468         need = sizeof(s5_req) + addrlen + 2;
1469         if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1470                 need++;
1471         if (have < need)
1472                 return 0;
1473         if ((r = sshbuf_consume(input, sizeof(s5_req))) != 0)
1474                 fatal_fr(r, "channel %d: consume", c->self);
1475         if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1476                 /* host string length */
1477                 if ((r = sshbuf_consume(input, 1)) != 0)
1478                         fatal_fr(r, "channel %d: consume", c->self);
1479         }
1480         if ((r = sshbuf_get(input, &dest_addr, addrlen)) != 0 ||
1481             (r = sshbuf_get(input, &dest_port, 2)) != 0) {
1482                 debug_r(r, "channel %d: parse addr/port", c->self);
1483                 return -1;
1484         }
1485         dest_addr[addrlen] = '\0';
1486         free(c->path);
1487         c->path = NULL;
1488         if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1489                 if (addrlen >= NI_MAXHOST) {
1490                         error("channel %d: dynamic request: socks5 hostname "
1491                             "\"%.100s\" too long", c->self, dest_addr);
1492                         return -1;
1493                 }
1494                 c->path = xstrdup(dest_addr);
1495         } else {
1496                 if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
1497                         return -1;
1498                 c->path = xstrdup(ntop);
1499         }
1500         c->host_port = ntohs(dest_port);
1501
1502         debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1503             c->self, c->path, c->host_port, s5_req.command);
1504
1505         s5_rsp.version = 0x05;
1506         s5_rsp.command = SSH_SOCKS5_SUCCESS;
1507         s5_rsp.reserved = 0;                    /* ignored */
1508         s5_rsp.atyp = SSH_SOCKS5_IPV4;
1509         dest_port = 0;                          /* ignored */
1510
1511         if ((r = sshbuf_put(output, &s5_rsp, sizeof(s5_rsp))) != 0 ||
1512             (r = sshbuf_put_u32(output, ntohl(INADDR_ANY))) != 0 ||
1513             (r = sshbuf_put(output, &dest_port, sizeof(dest_port))) != 0)
1514                 fatal_fr(r, "channel %d: append reply", c->self);
1515         return 1;
1516 }
1517
1518 Channel *
1519 channel_connect_stdio_fwd(struct ssh *ssh,
1520     const char *host_to_connect, u_short port_to_connect,
1521     int in, int out, int nonblock)
1522 {
1523         Channel *c;
1524
1525         debug_f("%s:%d", host_to_connect, port_to_connect);
1526
1527         c = channel_new(ssh, "stdio-forward", SSH_CHANNEL_OPENING, in, out,
1528             -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1529             0, "stdio-forward", nonblock);
1530
1531         c->path = xstrdup(host_to_connect);
1532         c->host_port = port_to_connect;
1533         c->listening_port = 0;
1534         c->force_drain = 1;
1535
1536         channel_register_fds(ssh, c, in, out, -1, 0, 1, 0);
1537         port_open_helper(ssh, c, "direct-tcpip");
1538
1539         return c;
1540 }
1541
1542 /* dynamic port forwarding */
1543 static void
1544 channel_pre_dynamic(struct ssh *ssh, Channel *c,
1545     fd_set *readset, fd_set *writeset)
1546 {
1547         const u_char *p;
1548         u_int have;
1549         int ret;
1550
1551         have = sshbuf_len(c->input);
1552         debug2("channel %d: pre_dynamic: have %d", c->self, have);
1553         /* sshbuf_dump(c->input, stderr); */
1554         /* check if the fixed size part of the packet is in buffer. */
1555         if (have < 3) {
1556                 /* need more */
1557                 FD_SET(c->sock, readset);
1558                 return;
1559         }
1560         /* try to guess the protocol */
1561         p = sshbuf_ptr(c->input);
1562         /* XXX sshbuf_peek_u8? */
1563         switch (p[0]) {
1564         case 0x04:
1565                 ret = channel_decode_socks4(c, c->input, c->output);
1566                 break;
1567         case 0x05:
1568                 ret = channel_decode_socks5(c, c->input, c->output);
1569                 break;
1570         default:
1571                 ret = -1;
1572                 break;
1573         }
1574         if (ret < 0) {
1575                 chan_mark_dead(ssh, c);
1576         } else if (ret == 0) {
1577                 debug2("channel %d: pre_dynamic: need more", c->self);
1578                 /* need more */
1579                 FD_SET(c->sock, readset);
1580                 if (sshbuf_len(c->output))
1581                         FD_SET(c->sock, writeset);
1582         } else {
1583                 /* switch to the next state */
1584                 c->type = SSH_CHANNEL_OPENING;
1585                 port_open_helper(ssh, c, "direct-tcpip");
1586         }
1587 }
1588
1589 /* simulate read-error */
1590 static void
1591 rdynamic_close(struct ssh *ssh, Channel *c)
1592 {
1593         c->type = SSH_CHANNEL_OPEN;
1594         chan_read_failed(ssh, c);
1595         sshbuf_reset(c->input);
1596         chan_ibuf_empty(ssh, c);
1597         sshbuf_reset(c->output);
1598         chan_write_failed(ssh, c);
1599 }
1600
1601 /* reverse dynamic port forwarding */
1602 static void
1603 channel_before_prepare_select_rdynamic(struct ssh *ssh, Channel *c)
1604 {
1605         const u_char *p;
1606         u_int have, len;
1607         int r, ret;
1608
1609         have = sshbuf_len(c->output);
1610         debug2("channel %d: pre_rdynamic: have %d", c->self, have);
1611         /* sshbuf_dump(c->output, stderr); */
1612         /* EOF received */
1613         if (c->flags & CHAN_EOF_RCVD) {
1614                 if ((r = sshbuf_consume(c->output, have)) != 0)
1615                         fatal_fr(r, "channel %d: consume", c->self);
1616                 rdynamic_close(ssh, c);
1617                 return;
1618         }
1619         /* check if the fixed size part of the packet is in buffer. */
1620         if (have < 3)
1621                 return;
1622         /* try to guess the protocol */
1623         p = sshbuf_ptr(c->output);
1624         switch (p[0]) {
1625         case 0x04:
1626                 /* switch input/output for reverse forwarding */
1627                 ret = channel_decode_socks4(c, c->output, c->input);
1628                 break;
1629         case 0x05:
1630                 ret = channel_decode_socks5(c, c->output, c->input);
1631                 break;
1632         default:
1633                 ret = -1;
1634                 break;
1635         }
1636         if (ret < 0) {
1637                 rdynamic_close(ssh, c);
1638         } else if (ret == 0) {
1639                 debug2("channel %d: pre_rdynamic: need more", c->self);
1640                 /* send socks request to peer */
1641                 len = sshbuf_len(c->input);
1642                 if (len > 0 && len < c->remote_window) {
1643                         if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
1644                             (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1645                             (r = sshpkt_put_stringb(ssh, c->input)) != 0 ||
1646                             (r = sshpkt_send(ssh)) != 0) {
1647                                 fatal_fr(r, "channel %i: rdynamic", c->self);
1648                         }
1649                         if ((r = sshbuf_consume(c->input, len)) != 0)
1650                                 fatal_fr(r, "channel %d: consume", c->self);
1651                         c->remote_window -= len;
1652                 }
1653         } else if (rdynamic_connect_finish(ssh, c) < 0) {
1654                 /* the connect failed */
1655                 rdynamic_close(ssh, c);
1656         }
1657 }
1658
1659 /* This is our fake X11 server socket. */
1660 static void
1661 channel_post_x11_listener(struct ssh *ssh, Channel *c,
1662     fd_set *readset, fd_set *writeset)
1663 {
1664         Channel *nc;
1665         struct sockaddr_storage addr;
1666         int r, newsock, oerrno, remote_port;
1667         socklen_t addrlen;
1668         char buf[16384], *remote_ipaddr;
1669
1670         if (!FD_ISSET(c->sock, readset))
1671                 return;
1672
1673         debug("X11 connection requested.");
1674         addrlen = sizeof(addr);
1675         newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1676         if (c->single_connection) {
1677                 oerrno = errno;
1678                 debug2("single_connection: closing X11 listener.");
1679                 channel_close_fd(ssh, c, &c->sock);
1680                 chan_mark_dead(ssh, c);
1681                 errno = oerrno;
1682         }
1683         if (newsock == -1) {
1684                 if (errno != EINTR && errno != EWOULDBLOCK &&
1685                     errno != ECONNABORTED)
1686                         error("accept: %.100s", strerror(errno));
1687                 if (errno == EMFILE || errno == ENFILE)
1688                         c->notbefore = monotime() + 1;
1689                 return;
1690         }
1691         set_nodelay(newsock);
1692         remote_ipaddr = get_peer_ipaddr(newsock);
1693         remote_port = get_peer_port(newsock);
1694         snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1695             remote_ipaddr, remote_port);
1696
1697         nc = channel_new(ssh, "accepted x11 socket",
1698             SSH_CHANNEL_OPENING, newsock, newsock, -1,
1699             c->local_window_max, c->local_maxpacket, 0, buf, 1);
1700         open_preamble(ssh, __func__, nc, "x11");
1701         if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1702             (r = sshpkt_put_u32(ssh, remote_port)) != 0) {
1703                 fatal_fr(r, "channel %i: reply", c->self);
1704         }
1705         if ((r = sshpkt_send(ssh)) != 0)
1706                 fatal_fr(r, "channel %i: send", c->self);
1707         free(remote_ipaddr);
1708 }
1709
1710 static void
1711 port_open_helper(struct ssh *ssh, Channel *c, char *rtype)
1712 {
1713         char *local_ipaddr = get_local_ipaddr(c->sock);
1714         int local_port = c->sock == -1 ? 65536 : get_local_port(c->sock);
1715         char *remote_ipaddr = get_peer_ipaddr(c->sock);
1716         int remote_port = get_peer_port(c->sock);
1717         int r;
1718
1719         if (remote_port == -1) {
1720                 /* Fake addr/port to appease peers that validate it (Tectia) */
1721                 free(remote_ipaddr);
1722                 remote_ipaddr = xstrdup("127.0.0.1");
1723                 remote_port = 65535;
1724         }
1725
1726         free(c->remote_name);
1727         xasprintf(&c->remote_name,
1728             "%s: listening port %d for %.100s port %d, "
1729             "connect from %.200s port %d to %.100s port %d",
1730             rtype, c->listening_port, c->path, c->host_port,
1731             remote_ipaddr, remote_port, local_ipaddr, local_port);
1732
1733         open_preamble(ssh, __func__, c, rtype);
1734         if (strcmp(rtype, "direct-tcpip") == 0) {
1735                 /* target host, port */
1736                 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1737                     (r = sshpkt_put_u32(ssh, c->host_port)) != 0)
1738                         fatal_fr(r, "channel %i: reply", c->self);
1739         } else if (strcmp(rtype, "direct-streamlocal@openssh.com") == 0) {
1740                 /* target path */
1741                 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1742                         fatal_fr(r, "channel %i: reply", c->self);
1743         } else if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1744                 /* listen path */
1745                 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1746                         fatal_fr(r, "channel %i: reply", c->self);
1747         } else {
1748                 /* listen address, port */
1749                 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1750                     (r = sshpkt_put_u32(ssh, local_port)) != 0)
1751                         fatal_fr(r, "channel %i: reply", c->self);
1752         }
1753         if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1754                 /* reserved for future owner/mode info */
1755                 if ((r = sshpkt_put_cstring(ssh, "")) != 0)
1756                         fatal_fr(r, "channel %i: reply", c->self);
1757         } else {
1758                 /* originator host and port */
1759                 if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1760                     (r = sshpkt_put_u32(ssh, (u_int)remote_port)) != 0)
1761                         fatal_fr(r, "channel %i: reply", c->self);
1762         }
1763         if ((r = sshpkt_send(ssh)) != 0)
1764                 fatal_fr(r, "channel %i: send", c->self);
1765         free(remote_ipaddr);
1766         free(local_ipaddr);
1767 }
1768
1769 void
1770 channel_set_x11_refuse_time(struct ssh *ssh, u_int refuse_time)
1771 {
1772         ssh->chanctxt->x11_refuse_time = refuse_time;
1773 }
1774
1775 /*
1776  * This socket is listening for connections to a forwarded TCP/IP port.
1777  */
1778 static void
1779 channel_post_port_listener(struct ssh *ssh, Channel *c,
1780     fd_set *readset, fd_set *writeset)
1781 {
1782         Channel *nc;
1783         struct sockaddr_storage addr;
1784         int newsock, nextstate;
1785         socklen_t addrlen;
1786         char *rtype;
1787
1788         if (!FD_ISSET(c->sock, readset))
1789                 return;
1790
1791         debug("Connection to port %d forwarding to %.100s port %d requested.",
1792             c->listening_port, c->path, c->host_port);
1793
1794         if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1795                 nextstate = SSH_CHANNEL_OPENING;
1796                 rtype = "forwarded-tcpip";
1797         } else if (c->type == SSH_CHANNEL_RUNIX_LISTENER) {
1798                 nextstate = SSH_CHANNEL_OPENING;
1799                 rtype = "forwarded-streamlocal@openssh.com";
1800         } else if (c->host_port == PORT_STREAMLOCAL) {
1801                 nextstate = SSH_CHANNEL_OPENING;
1802                 rtype = "direct-streamlocal@openssh.com";
1803         } else if (c->host_port == 0) {
1804                 nextstate = SSH_CHANNEL_DYNAMIC;
1805                 rtype = "dynamic-tcpip";
1806         } else {
1807                 nextstate = SSH_CHANNEL_OPENING;
1808                 rtype = "direct-tcpip";
1809         }
1810
1811         addrlen = sizeof(addr);
1812         newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1813         if (newsock == -1) {
1814                 if (errno != EINTR && errno != EWOULDBLOCK &&
1815                     errno != ECONNABORTED)
1816                         error("accept: %.100s", strerror(errno));
1817                 if (errno == EMFILE || errno == ENFILE)
1818                         c->notbefore = monotime() + 1;
1819                 return;
1820         }
1821         if (c->host_port != PORT_STREAMLOCAL)
1822                 set_nodelay(newsock);
1823         nc = channel_new(ssh, rtype, nextstate, newsock, newsock, -1,
1824             c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1825         nc->listening_port = c->listening_port;
1826         nc->host_port = c->host_port;
1827         if (c->path != NULL)
1828                 nc->path = xstrdup(c->path);
1829
1830         if (nextstate != SSH_CHANNEL_DYNAMIC)
1831                 port_open_helper(ssh, nc, rtype);
1832 }
1833
1834 /*
1835  * This is the authentication agent socket listening for connections from
1836  * clients.
1837  */
1838 static void
1839 channel_post_auth_listener(struct ssh *ssh, Channel *c,
1840     fd_set *readset, fd_set *writeset)
1841 {
1842         Channel *nc;
1843         int r, newsock;
1844         struct sockaddr_storage addr;
1845         socklen_t addrlen;
1846
1847         if (!FD_ISSET(c->sock, readset))
1848                 return;
1849
1850         addrlen = sizeof(addr);
1851         newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1852         if (newsock == -1) {
1853                 error("accept from auth socket: %.100s", strerror(errno));
1854                 if (errno == EMFILE || errno == ENFILE)
1855                         c->notbefore = monotime() + 1;
1856                 return;
1857         }
1858         nc = channel_new(ssh, "accepted auth socket",
1859             SSH_CHANNEL_OPENING, newsock, newsock, -1,
1860             c->local_window_max, c->local_maxpacket,
1861             0, "accepted auth socket", 1);
1862         open_preamble(ssh, __func__, nc, "auth-agent@openssh.com");
1863         if ((r = sshpkt_send(ssh)) != 0)
1864                 fatal_fr(r, "channel %i", c->self);
1865 }
1866
1867 static void
1868 channel_post_connecting(struct ssh *ssh, Channel *c,
1869     fd_set *readset, fd_set *writeset)
1870 {
1871         int err = 0, sock, isopen, r;
1872         socklen_t sz = sizeof(err);
1873
1874         if (!FD_ISSET(c->sock, writeset))
1875                 return;
1876         if (!c->have_remote_id)
1877                 fatal_f("channel %d: no remote id", c->self);
1878         /* for rdynamic the OPEN_CONFIRMATION has been sent already */
1879         isopen = (c->type == SSH_CHANNEL_RDYNAMIC_FINISH);
1880         if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) == -1) {
1881                 err = errno;
1882                 error("getsockopt SO_ERROR failed");
1883         }
1884         if (err == 0) {
1885                 debug("channel %d: connected to %s port %d",
1886                     c->self, c->connect_ctx.host, c->connect_ctx.port);
1887                 channel_connect_ctx_free(&c->connect_ctx);
1888                 c->type = SSH_CHANNEL_OPEN;
1889                 if (isopen) {
1890                         /* no message necessary */
1891                 } else {
1892                         if ((r = sshpkt_start(ssh,
1893                             SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
1894                             (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1895                             (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1896                             (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1897                             (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
1898                             (r = sshpkt_send(ssh)) != 0)
1899                                 fatal_fr(r, "channel %i open confirm", c->self);
1900                 }
1901         } else {
1902                 debug("channel %d: connection failed: %s",
1903                     c->self, strerror(err));
1904                 /* Try next address, if any */
1905                 if ((sock = connect_next(&c->connect_ctx)) > 0) {
1906                         close(c->sock);
1907                         c->sock = c->rfd = c->wfd = sock;
1908                         channel_find_maxfd(ssh->chanctxt);
1909                         return;
1910                 }
1911                 /* Exhausted all addresses */
1912                 error("connect_to %.100s port %d: failed.",
1913                     c->connect_ctx.host, c->connect_ctx.port);
1914                 channel_connect_ctx_free(&c->connect_ctx);
1915                 if (isopen) {
1916                         rdynamic_close(ssh, c);
1917                 } else {
1918                         if ((r = sshpkt_start(ssh,
1919                             SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
1920                             (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1921                             (r = sshpkt_put_u32(ssh,
1922                             SSH2_OPEN_CONNECT_FAILED)) != 0 ||
1923                             (r = sshpkt_put_cstring(ssh, strerror(err))) != 0 ||
1924                             (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1925                             (r = sshpkt_send(ssh)) != 0)
1926                                 fatal_fr(r, "channel %i: failure", c->self);
1927                         chan_mark_dead(ssh, c);
1928                 }
1929         }
1930 }
1931
1932 static int
1933 channel_handle_rfd(struct ssh *ssh, Channel *c,
1934     fd_set *readset, fd_set *writeset)
1935 {
1936         char buf[CHAN_RBUF];
1937         ssize_t len;
1938         int r, force;
1939
1940         force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
1941
1942         if (c->rfd == -1 || (!force && !FD_ISSET(c->rfd, readset)))
1943                 return 1;
1944
1945         errno = 0;
1946         len = read(c->rfd, buf, sizeof(buf));
1947         if (len == -1 && (errno == EINTR ||
1948             ((errno == EAGAIN || errno == EWOULDBLOCK) && !force)))
1949                 return 1;
1950 #ifndef PTY_ZEROREAD
1951         if (len <= 0) {
1952 #else
1953         if ((!c->isatty && len <= 0) ||
1954             (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1955 #endif
1956                 debug2("channel %d: read<=0 rfd %d len %zd",
1957                     c->self, c->rfd, len);
1958                 if (c->type != SSH_CHANNEL_OPEN) {
1959                         debug2("channel %d: not open", c->self);
1960                         chan_mark_dead(ssh, c);
1961                         return -1;
1962                 } else {
1963                         chan_read_failed(ssh, c);
1964                 }
1965                 return -1;
1966         }
1967         if (c->input_filter != NULL) {
1968                 if (c->input_filter(ssh, c, buf, len) == -1) {
1969                         debug2("channel %d: filter stops", c->self);
1970                         chan_read_failed(ssh, c);
1971                 }
1972         } else if (c->datagram) {
1973                 if ((r = sshbuf_put_string(c->input, buf, len)) != 0)
1974                         fatal_fr(r, "channel %i: put datagram", c->self);
1975         } else if ((r = sshbuf_put(c->input, buf, len)) != 0)
1976                 fatal_fr(r, "channel %i: put data", c->self);
1977         return 1;
1978 }
1979
1980 static int
1981 channel_handle_wfd(struct ssh *ssh, Channel *c,
1982    fd_set *readset, fd_set *writeset)
1983 {
1984         struct termios tio;
1985         u_char *data = NULL, *buf; /* XXX const; need filter API change */
1986         size_t dlen, olen = 0;
1987         int r, len;
1988
1989         if (c->wfd == -1 || !FD_ISSET(c->wfd, writeset) ||
1990             sshbuf_len(c->output) == 0)
1991                 return 1;
1992
1993         /* Send buffered output data to the socket. */
1994         olen = sshbuf_len(c->output);
1995         if (c->output_filter != NULL) {
1996                 if ((buf = c->output_filter(ssh, c, &data, &dlen)) == NULL) {
1997                         debug2("channel %d: filter stops", c->self);
1998                         if (c->type != SSH_CHANNEL_OPEN)
1999                                 chan_mark_dead(ssh, c);
2000                         else
2001                                 chan_write_failed(ssh, c);
2002                         return -1;
2003                 }
2004         } else if (c->datagram) {
2005                 if ((r = sshbuf_get_string(c->output, &data, &dlen)) != 0)
2006                         fatal_fr(r, "channel %i: get datagram", c->self);
2007                 buf = data;
2008         } else {
2009                 buf = data = sshbuf_mutable_ptr(c->output);
2010                 dlen = sshbuf_len(c->output);
2011         }
2012
2013         if (c->datagram) {
2014                 /* ignore truncated writes, datagrams might get lost */
2015                 len = write(c->wfd, buf, dlen);
2016                 free(data);
2017                 if (len == -1 && (errno == EINTR || errno == EAGAIN ||
2018                     errno == EWOULDBLOCK))
2019                         return 1;
2020                 if (len <= 0)
2021                         goto write_fail;
2022                 goto out;
2023         }
2024
2025 #ifdef _AIX
2026         /* XXX: Later AIX versions can't push as much data to tty */
2027         if (c->wfd_isatty)
2028                 dlen = MIN(dlen, 8*1024);
2029 #endif
2030
2031         len = write(c->wfd, buf, dlen);
2032         if (len == -1 &&
2033             (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK))
2034                 return 1;
2035         if (len <= 0) {
2036  write_fail:
2037                 if (c->type != SSH_CHANNEL_OPEN) {
2038                         debug2("channel %d: not open", c->self);
2039                         chan_mark_dead(ssh, c);
2040                         return -1;
2041                 } else {
2042                         chan_write_failed(ssh, c);
2043                 }
2044                 return -1;
2045         }
2046 #ifndef BROKEN_TCGETATTR_ICANON
2047         if (c->isatty && dlen >= 1 && buf[0] != '\r') {
2048                 if (tcgetattr(c->wfd, &tio) == 0 &&
2049                     !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
2050                         /*
2051                          * Simulate echo to reduce the impact of
2052                          * traffic analysis. We need to match the
2053                          * size of a SSH2_MSG_CHANNEL_DATA message
2054                          * (4 byte channel id + buf)
2055                          */
2056                         if ((r = sshpkt_msg_ignore(ssh, 4+len)) != 0 ||
2057                             (r = sshpkt_send(ssh)) != 0)
2058                                 fatal_fr(r, "channel %i: ignore", c->self);
2059                 }
2060         }
2061 #endif /* BROKEN_TCGETATTR_ICANON */
2062         if ((r = sshbuf_consume(c->output, len)) != 0)
2063                 fatal_fr(r, "channel %i: consume", c->self);
2064  out:
2065         c->local_consumed += olen - sshbuf_len(c->output);
2066
2067         return 1;
2068 }
2069
2070 static int
2071 channel_handle_efd_write(struct ssh *ssh, Channel *c,
2072     fd_set *readset, fd_set *writeset)
2073 {
2074         int r;
2075         ssize_t len;
2076
2077         if (!FD_ISSET(c->efd, writeset) || sshbuf_len(c->extended) == 0)
2078                 return 1;
2079
2080         len = write(c->efd, sshbuf_ptr(c->extended),
2081             sshbuf_len(c->extended));
2082         debug2("channel %d: written %zd to efd %d", c->self, len, c->efd);
2083         if (len == -1 && (errno == EINTR || errno == EAGAIN ||
2084             errno == EWOULDBLOCK))
2085                 return 1;
2086         if (len <= 0) {
2087                 debug2("channel %d: closing write-efd %d", c->self, c->efd);
2088                 channel_close_fd(ssh, c, &c->efd);
2089         } else {
2090                 if ((r = sshbuf_consume(c->extended, len)) != 0)
2091                         fatal_fr(r, "channel %i: consume", c->self);
2092                 c->local_consumed += len;
2093         }
2094         return 1;
2095 }
2096
2097 static int
2098 channel_handle_efd_read(struct ssh *ssh, Channel *c,
2099     fd_set *readset, fd_set *writeset)
2100 {
2101         char buf[CHAN_RBUF];
2102         ssize_t len;
2103         int r, force;
2104
2105         force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
2106
2107         if (c->efd == -1 || (!force && !FD_ISSET(c->efd, readset)))
2108                 return 1;
2109
2110         len = read(c->efd, buf, sizeof(buf));
2111         debug2("channel %d: read %zd from efd %d", c->self, len, c->efd);
2112         if (len == -1 && (errno == EINTR || ((errno == EAGAIN ||
2113             errno == EWOULDBLOCK) && !force)))
2114                 return 1;
2115         if (len <= 0) {
2116                 debug2("channel %d: closing read-efd %d", c->self, c->efd);
2117                 channel_close_fd(ssh, c, &c->efd);
2118         } else if (c->extended_usage == CHAN_EXTENDED_IGNORE)
2119                 debug3("channel %d: discard efd", c->self);
2120         else if ((r = sshbuf_put(c->extended, buf, len)) != 0)
2121                 fatal_fr(r, "channel %i: append", c->self);
2122         return 1;
2123 }
2124
2125 static int
2126 channel_handle_efd(struct ssh *ssh, Channel *c,
2127     fd_set *readset, fd_set *writeset)
2128 {
2129         if (c->efd == -1)
2130                 return 1;
2131
2132         /** XXX handle drain efd, too */
2133
2134         if (c->extended_usage == CHAN_EXTENDED_WRITE)
2135                 return channel_handle_efd_write(ssh, c, readset, writeset);
2136         else if (c->extended_usage == CHAN_EXTENDED_READ ||
2137             c->extended_usage == CHAN_EXTENDED_IGNORE)
2138                 return channel_handle_efd_read(ssh, c, readset, writeset);
2139
2140         return 1;
2141 }
2142
2143 static int
2144 channel_check_window(struct ssh *ssh, Channel *c)
2145 {
2146         int r;
2147
2148         if (c->type == SSH_CHANNEL_OPEN &&
2149             !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
2150             ((c->local_window_max - c->local_window >
2151             c->local_maxpacket*3) ||
2152             c->local_window < c->local_window_max/2) &&
2153             c->local_consumed > 0) {
2154                 if (!c->have_remote_id)
2155                         fatal_f("channel %d: no remote id", c->self);
2156                 if ((r = sshpkt_start(ssh,
2157                     SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
2158                     (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2159                     (r = sshpkt_put_u32(ssh, c->local_consumed)) != 0 ||
2160                     (r = sshpkt_send(ssh)) != 0) {
2161                         fatal_fr(r, "channel %i", c->self);
2162                 }
2163                 debug2("channel %d: window %d sent adjust %d", c->self,
2164                     c->local_window, c->local_consumed);
2165                 c->local_window += c->local_consumed;
2166                 c->local_consumed = 0;
2167         }
2168         return 1;
2169 }
2170
2171 static void
2172 channel_post_open(struct ssh *ssh, Channel *c,
2173     fd_set *readset, fd_set *writeset)
2174 {
2175         channel_handle_rfd(ssh, c, readset, writeset);
2176         channel_handle_wfd(ssh, c, readset, writeset);
2177         channel_handle_efd(ssh, c, readset, writeset);
2178         channel_check_window(ssh, c);
2179 }
2180
2181 static u_int
2182 read_mux(struct ssh *ssh, Channel *c, u_int need)
2183 {
2184         char buf[CHAN_RBUF];
2185         ssize_t len;
2186         u_int rlen;
2187         int r;
2188
2189         if (sshbuf_len(c->input) < need) {
2190                 rlen = need - sshbuf_len(c->input);
2191                 len = read(c->rfd, buf, MINIMUM(rlen, CHAN_RBUF));
2192                 if (len == -1 && (errno == EINTR || errno == EAGAIN))
2193                         return sshbuf_len(c->input);
2194                 if (len <= 0) {
2195                         debug2("channel %d: ctl read<=0 rfd %d len %zd",
2196                             c->self, c->rfd, len);
2197                         chan_read_failed(ssh, c);
2198                         return 0;
2199                 } else if ((r = sshbuf_put(c->input, buf, len)) != 0)
2200                         fatal_fr(r, "channel %i: append", c->self);
2201         }
2202         return sshbuf_len(c->input);
2203 }
2204
2205 static void
2206 channel_post_mux_client_read(struct ssh *ssh, Channel *c,
2207     fd_set *readset, fd_set *writeset)
2208 {
2209         u_int need;
2210
2211         if (c->rfd == -1 || !FD_ISSET(c->rfd, readset))
2212                 return;
2213         if (c->istate != CHAN_INPUT_OPEN && c->istate != CHAN_INPUT_WAIT_DRAIN)
2214                 return;
2215         if (c->mux_pause)
2216                 return;
2217
2218         /*
2219          * Don't not read past the precise end of packets to
2220          * avoid disrupting fd passing.
2221          */
2222         if (read_mux(ssh, c, 4) < 4) /* read header */
2223                 return;
2224         /* XXX sshbuf_peek_u32 */
2225         need = PEEK_U32(sshbuf_ptr(c->input));
2226 #define CHANNEL_MUX_MAX_PACKET  (256 * 1024)
2227         if (need > CHANNEL_MUX_MAX_PACKET) {
2228                 debug2("channel %d: packet too big %u > %u",
2229                     c->self, CHANNEL_MUX_MAX_PACKET, need);
2230                 chan_rcvd_oclose(ssh, c);
2231                 return;
2232         }
2233         if (read_mux(ssh, c, need + 4) < need + 4) /* read body */
2234                 return;
2235         if (c->mux_rcb(ssh, c) != 0) {
2236                 debug("channel %d: mux_rcb failed", c->self);
2237                 chan_mark_dead(ssh, c);
2238                 return;
2239         }
2240 }
2241
2242 static void
2243 channel_post_mux_client_write(struct ssh *ssh, Channel *c,
2244     fd_set *readset, fd_set *writeset)
2245 {
2246         ssize_t len;
2247         int r;
2248
2249         if (c->wfd == -1 || !FD_ISSET(c->wfd, writeset) ||
2250             sshbuf_len(c->output) == 0)
2251                 return;
2252
2253         len = write(c->wfd, sshbuf_ptr(c->output), sshbuf_len(c->output));
2254         if (len == -1 && (errno == EINTR || errno == EAGAIN))
2255                 return;
2256         if (len <= 0) {
2257                 chan_mark_dead(ssh, c);
2258                 return;
2259         }
2260         if ((r = sshbuf_consume(c->output, len)) != 0)
2261                 fatal_fr(r, "channel %i: consume", c->self);
2262 }
2263
2264 static void
2265 channel_post_mux_client(struct ssh *ssh, Channel *c,
2266     fd_set *readset, fd_set *writeset)
2267 {
2268         channel_post_mux_client_read(ssh, c, readset, writeset);
2269         channel_post_mux_client_write(ssh, c, readset, writeset);
2270 }
2271
2272 static void
2273 channel_post_mux_listener(struct ssh *ssh, Channel *c,
2274     fd_set *readset, fd_set *writeset)
2275 {
2276         Channel *nc;
2277         struct sockaddr_storage addr;
2278         socklen_t addrlen;
2279         int newsock;
2280         uid_t euid;
2281         gid_t egid;
2282
2283         if (!FD_ISSET(c->sock, readset))
2284                 return;
2285
2286         debug("multiplexing control connection");
2287
2288         /*
2289          * Accept connection on control socket
2290          */
2291         memset(&addr, 0, sizeof(addr));
2292         addrlen = sizeof(addr);
2293         if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
2294             &addrlen)) == -1) {
2295                 error_f("accept: %s", strerror(errno));
2296                 if (errno == EMFILE || errno == ENFILE)
2297                         c->notbefore = monotime() + 1;
2298                 return;
2299         }
2300
2301         if (getpeereid(newsock, &euid, &egid) == -1) {
2302                 error_f("getpeereid failed: %s", strerror(errno));
2303                 close(newsock);
2304                 return;
2305         }
2306         if ((euid != 0) && (getuid() != euid)) {
2307                 error("multiplex uid mismatch: peer euid %u != uid %u",
2308                     (u_int)euid, (u_int)getuid());
2309                 close(newsock);
2310                 return;
2311         }
2312         nc = channel_new(ssh, "multiplex client", SSH_CHANNEL_MUX_CLIENT,
2313             newsock, newsock, -1, c->local_window_max,
2314             c->local_maxpacket, 0, "mux-control", 1);
2315         nc->mux_rcb = c->mux_rcb;
2316         debug3_f("new mux channel %d fd %d", nc->self, nc->sock);
2317         /* establish state */
2318         nc->mux_rcb(ssh, nc);
2319         /* mux state transitions must not elicit protocol messages */
2320         nc->flags |= CHAN_LOCAL;
2321 }
2322
2323 static void
2324 channel_handler_init(struct ssh_channels *sc)
2325 {
2326         chan_fn **pre, **post;
2327
2328         if ((pre = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*pre))) == NULL ||
2329             (post = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*post))) == NULL)
2330                 fatal_f("allocation failed");
2331
2332         pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open;
2333         pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
2334         pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
2335         pre[SSH_CHANNEL_RPORT_LISTENER] =       &channel_pre_listener;
2336         pre[SSH_CHANNEL_UNIX_LISTENER] =        &channel_pre_listener;
2337         pre[SSH_CHANNEL_RUNIX_LISTENER] =       &channel_pre_listener;
2338         pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
2339         pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
2340         pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
2341         pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
2342         pre[SSH_CHANNEL_RDYNAMIC_FINISH] =      &channel_pre_connecting;
2343         pre[SSH_CHANNEL_MUX_LISTENER] =         &channel_pre_listener;
2344         pre[SSH_CHANNEL_MUX_CLIENT] =           &channel_pre_mux_client;
2345
2346         post[SSH_CHANNEL_OPEN] =                &channel_post_open;
2347         post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
2348         post[SSH_CHANNEL_RPORT_LISTENER] =      &channel_post_port_listener;
2349         post[SSH_CHANNEL_UNIX_LISTENER] =       &channel_post_port_listener;
2350         post[SSH_CHANNEL_RUNIX_LISTENER] =      &channel_post_port_listener;
2351         post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
2352         post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
2353         post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
2354         post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
2355         post[SSH_CHANNEL_RDYNAMIC_FINISH] =     &channel_post_connecting;
2356         post[SSH_CHANNEL_MUX_LISTENER] =        &channel_post_mux_listener;
2357         post[SSH_CHANNEL_MUX_CLIENT] =          &channel_post_mux_client;
2358
2359         sc->channel_pre = pre;
2360         sc->channel_post = post;
2361 }
2362
2363 /* gc dead channels */
2364 static void
2365 channel_garbage_collect(struct ssh *ssh, Channel *c)
2366 {
2367         if (c == NULL)
2368                 return;
2369         if (c->detach_user != NULL) {
2370                 if (!chan_is_dead(ssh, c, c->detach_close))
2371                         return;
2372
2373                 debug2("channel %d: gc: notify user", c->self);
2374                 c->detach_user(ssh, c->self, NULL);
2375                 /* if we still have a callback */
2376                 if (c->detach_user != NULL)
2377                         return;
2378                 debug2("channel %d: gc: user detached", c->self);
2379         }
2380         if (!chan_is_dead(ssh, c, 1))
2381                 return;
2382         debug2("channel %d: garbage collecting", c->self);
2383         channel_free(ssh, c);
2384 }
2385
2386 enum channel_table { CHAN_PRE, CHAN_POST };
2387
2388 static void
2389 channel_handler(struct ssh *ssh, int table,
2390     fd_set *readset, fd_set *writeset, time_t *unpause_secs)
2391 {
2392         struct ssh_channels *sc = ssh->chanctxt;
2393         chan_fn **ftab = table == CHAN_PRE ? sc->channel_pre : sc->channel_post;
2394         u_int i, oalloc;
2395         Channel *c;
2396         time_t now;
2397
2398         now = monotime();
2399         if (unpause_secs != NULL)
2400                 *unpause_secs = 0;
2401         for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2402                 c = sc->channels[i];
2403                 if (c == NULL)
2404                         continue;
2405                 if (c->delayed) {
2406                         if (table == CHAN_PRE)
2407                                 c->delayed = 0;
2408                         else
2409                                 continue;
2410                 }
2411                 if (ftab[c->type] != NULL) {
2412                         /*
2413                          * Run handlers that are not paused.
2414                          */
2415                         if (c->notbefore <= now)
2416                                 (*ftab[c->type])(ssh, c, readset, writeset);
2417                         else if (unpause_secs != NULL) {
2418                                 /*
2419                                  * Collect the time that the earliest
2420                                  * channel comes off pause.
2421                                  */
2422                                 debug3_f("chan %d: skip for %d more "
2423                                     "seconds", c->self,
2424                                     (int)(c->notbefore - now));
2425                                 if (*unpause_secs == 0 ||
2426                                     (c->notbefore - now) < *unpause_secs)
2427                                         *unpause_secs = c->notbefore - now;
2428                         }
2429                 }
2430                 channel_garbage_collect(ssh, c);
2431         }
2432         if (unpause_secs != NULL && *unpause_secs != 0)
2433                 debug3_f("first channel unpauses in %d seconds",
2434                     (int)*unpause_secs);
2435 }
2436
2437 /*
2438  * Create sockets before allocating the select bitmasks.
2439  * This is necessary for things that need to happen after reading
2440  * the network-input but before channel_prepare_select().
2441  */
2442 static void
2443 channel_before_prepare_select(struct ssh *ssh)
2444 {
2445         struct ssh_channels *sc = ssh->chanctxt;
2446         Channel *c;
2447         u_int i, oalloc;
2448
2449         for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2450                 c = sc->channels[i];
2451                 if (c == NULL)
2452                         continue;
2453                 if (c->type == SSH_CHANNEL_RDYNAMIC_OPEN)
2454                         channel_before_prepare_select_rdynamic(ssh, c);
2455         }
2456 }
2457
2458 /*
2459  * Allocate/update select bitmasks and add any bits relevant to channels in
2460  * select bitmasks.
2461  */
2462 void
2463 channel_prepare_select(struct ssh *ssh, fd_set **readsetp, fd_set **writesetp,
2464     int *maxfdp, u_int *nallocp, time_t *minwait_secs)
2465 {
2466         u_int n, sz, nfdset;
2467
2468         channel_before_prepare_select(ssh); /* might update channel_max_fd */
2469
2470         n = MAXIMUM(*maxfdp, ssh->chanctxt->channel_max_fd);
2471
2472         nfdset = howmany(n+1, NFDBITS);
2473         /* Explicitly test here, because xrealloc isn't always called */
2474         if (nfdset && SIZE_MAX / nfdset < sizeof(fd_mask))
2475                 fatal("channel_prepare_select: max_fd (%d) is too large", n);
2476         sz = nfdset * sizeof(fd_mask);
2477
2478         /* perhaps check sz < nalloc/2 and shrink? */
2479         if (*readsetp == NULL || sz > *nallocp) {
2480                 *readsetp = xreallocarray(*readsetp, nfdset, sizeof(fd_mask));
2481                 *writesetp = xreallocarray(*writesetp, nfdset, sizeof(fd_mask));
2482                 *nallocp = sz;
2483         }
2484         *maxfdp = n;
2485         memset(*readsetp, 0, sz);
2486         memset(*writesetp, 0, sz);
2487
2488         if (!ssh_packet_is_rekeying(ssh))
2489                 channel_handler(ssh, CHAN_PRE, *readsetp, *writesetp,
2490                     minwait_secs);
2491 }
2492
2493 /*
2494  * After select, perform any appropriate operations for channels which have
2495  * events pending.
2496  */
2497 void
2498 channel_after_select(struct ssh *ssh, fd_set *readset, fd_set *writeset)
2499 {
2500         channel_handler(ssh, CHAN_POST, readset, writeset, NULL);
2501 }
2502
2503 /*
2504  * Enqueue data for channels with open or draining c->input.
2505  */
2506 static void
2507 channel_output_poll_input_open(struct ssh *ssh, Channel *c)
2508 {
2509         size_t len, plen;
2510         const u_char *pkt;
2511         int r;
2512
2513         if ((len = sshbuf_len(c->input)) == 0) {
2514                 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2515                         /*
2516                          * input-buffer is empty and read-socket shutdown:
2517                          * tell peer, that we will not send more data:
2518                          * send IEOF.
2519                          * hack for extended data: delay EOF if EFD still
2520                          * in use.
2521                          */
2522                         if (CHANNEL_EFD_INPUT_ACTIVE(c))
2523                                 debug2("channel %d: "
2524                                     "ibuf_empty delayed efd %d/(%zu)",
2525                                     c->self, c->efd, sshbuf_len(c->extended));
2526                         else
2527                                 chan_ibuf_empty(ssh, c);
2528                 }
2529                 return;
2530         }
2531
2532         if (!c->have_remote_id)
2533                 fatal_f("channel %d: no remote id", c->self);
2534
2535         if (c->datagram) {
2536                 /* Check datagram will fit; drop if not */
2537                 if ((r = sshbuf_get_string_direct(c->input, &pkt, &plen)) != 0)
2538                         fatal_fr(r, "channel %i: get datagram", c->self);
2539                 /*
2540                  * XXX this does tail-drop on the datagram queue which is
2541                  * usually suboptimal compared to head-drop. Better to have
2542                  * backpressure at read time? (i.e. read + discard)
2543                  */
2544                 if (plen > c->remote_window || plen > c->remote_maxpacket) {
2545                         debug("channel %d: datagram too big", c->self);
2546                         return;
2547                 }
2548                 /* Enqueue it */
2549                 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2550                     (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2551                     (r = sshpkt_put_string(ssh, pkt, plen)) != 0 ||
2552                     (r = sshpkt_send(ssh)) != 0)
2553                         fatal_fr(r, "channel %i: send datagram", c->self);
2554                 c->remote_window -= plen;
2555                 return;
2556         }
2557
2558         /* Enqueue packet for buffered data. */
2559         if (len > c->remote_window)
2560                 len = c->remote_window;
2561         if (len > c->remote_maxpacket)
2562                 len = c->remote_maxpacket;
2563         if (len == 0)
2564                 return;
2565         if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2566             (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2567             (r = sshpkt_put_string(ssh, sshbuf_ptr(c->input), len)) != 0 ||
2568             (r = sshpkt_send(ssh)) != 0)
2569                 fatal_fr(r, "channel %i: send data", c->self);
2570         if ((r = sshbuf_consume(c->input, len)) != 0)
2571                 fatal_fr(r, "channel %i: consume", c->self);
2572         c->remote_window -= len;
2573 }
2574
2575 /*
2576  * Enqueue data for channels with open c->extended in read mode.
2577  */
2578 static void
2579 channel_output_poll_extended_read(struct ssh *ssh, Channel *c)
2580 {
2581         size_t len;
2582         int r;
2583
2584         if ((len = sshbuf_len(c->extended)) == 0)
2585                 return;
2586
2587         debug2("channel %d: rwin %u elen %zu euse %d", c->self,
2588             c->remote_window, sshbuf_len(c->extended), c->extended_usage);
2589         if (len > c->remote_window)
2590                 len = c->remote_window;
2591         if (len > c->remote_maxpacket)
2592                 len = c->remote_maxpacket;
2593         if (len == 0)
2594                 return;
2595         if (!c->have_remote_id)
2596                 fatal_f("channel %d: no remote id", c->self);
2597         if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA)) != 0 ||
2598             (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2599             (r = sshpkt_put_u32(ssh, SSH2_EXTENDED_DATA_STDERR)) != 0 ||
2600             (r = sshpkt_put_string(ssh, sshbuf_ptr(c->extended), len)) != 0 ||
2601             (r = sshpkt_send(ssh)) != 0)
2602                 fatal_fr(r, "channel %i: data", c->self);
2603         if ((r = sshbuf_consume(c->extended, len)) != 0)
2604                 fatal_fr(r, "channel %i: consume", c->self);
2605         c->remote_window -= len;
2606         debug2("channel %d: sent ext data %zu", c->self, len);
2607 }
2608
2609 /* If there is data to send to the connection, enqueue some of it now. */
2610 void
2611 channel_output_poll(struct ssh *ssh)
2612 {
2613         struct ssh_channels *sc = ssh->chanctxt;
2614         Channel *c;
2615         u_int i;
2616
2617         for (i = 0; i < sc->channels_alloc; i++) {
2618                 c = sc->channels[i];
2619                 if (c == NULL)
2620                         continue;
2621
2622                 /*
2623                  * We are only interested in channels that can have buffered
2624                  * incoming data.
2625                  */
2626                 if (c->type != SSH_CHANNEL_OPEN)
2627                         continue;
2628                 if ((c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
2629                         /* XXX is this true? */
2630                         debug3("channel %d: will not send data after close",
2631                             c->self);
2632                         continue;
2633                 }
2634
2635                 /* Get the amount of buffered data for this channel. */
2636                 if (c->istate == CHAN_INPUT_OPEN ||
2637                     c->istate == CHAN_INPUT_WAIT_DRAIN)
2638                         channel_output_poll_input_open(ssh, c);
2639                 /* Send extended data, i.e. stderr */
2640                 if (!(c->flags & CHAN_EOF_SENT) &&
2641                     c->extended_usage == CHAN_EXTENDED_READ)
2642                         channel_output_poll_extended_read(ssh, c);
2643         }
2644 }
2645
2646 /* -- mux proxy support  */
2647
2648 /*
2649  * When multiplexing channel messages for mux clients we have to deal
2650  * with downstream messages from the mux client and upstream messages
2651  * from the ssh server:
2652  * 1) Handling downstream messages is straightforward and happens
2653  *    in channel_proxy_downstream():
2654  *    - We forward all messages (mostly) unmodified to the server.
2655  *    - However, in order to route messages from upstream to the correct
2656  *      downstream client, we have to replace the channel IDs used by the
2657  *      mux clients with a unique channel ID because the mux clients might
2658  *      use conflicting channel IDs.
2659  *    - so we inspect and change both SSH2_MSG_CHANNEL_OPEN and
2660  *      SSH2_MSG_CHANNEL_OPEN_CONFIRMATION messages, create a local
2661  *      SSH_CHANNEL_MUX_PROXY channel and replace the mux clients ID
2662  *      with the newly allocated channel ID.
2663  * 2) Upstream messages are received by matching SSH_CHANNEL_MUX_PROXY
2664  *    channels and processed by channel_proxy_upstream(). The local channel ID
2665  *    is then translated back to the original mux client ID.
2666  * 3) In both cases we need to keep track of matching SSH2_MSG_CHANNEL_CLOSE
2667  *    messages so we can clean up SSH_CHANNEL_MUX_PROXY channels.
2668  * 4) The SSH_CHANNEL_MUX_PROXY channels also need to closed when the
2669  *    downstream mux client are removed.
2670  * 5) Handling SSH2_MSG_CHANNEL_OPEN messages from the upstream server
2671  *    requires more work, because they are not addressed to a specific
2672  *    channel. E.g. client_request_forwarded_tcpip() needs to figure
2673  *    out whether the request is addressed to the local client or a
2674  *    specific downstream client based on the listen-address/port.
2675  * 6) Agent and X11-Forwarding have a similar problem and are currently
2676  *    not supported as the matching session/channel cannot be identified
2677  *    easily.
2678  */
2679
2680 /*
2681  * receive packets from downstream mux clients:
2682  * channel callback fired on read from mux client, creates
2683  * SSH_CHANNEL_MUX_PROXY channels and translates channel IDs
2684  * on channel creation.
2685  */
2686 int
2687 channel_proxy_downstream(struct ssh *ssh, Channel *downstream)
2688 {
2689         Channel *c = NULL;
2690         struct sshbuf *original = NULL, *modified = NULL;
2691         const u_char *cp;
2692         char *ctype = NULL, *listen_host = NULL;
2693         u_char type;
2694         size_t have;
2695         int ret = -1, r;
2696         u_int id, remote_id, listen_port;
2697
2698         /* sshbuf_dump(downstream->input, stderr); */
2699         if ((r = sshbuf_get_string_direct(downstream->input, &cp, &have))
2700             != 0) {
2701                 error_fr(r, "parse");
2702                 return -1;
2703         }
2704         if (have < 2) {
2705                 error_f("short message");
2706                 return -1;
2707         }
2708         type = cp[1];
2709         /* skip padlen + type */
2710         cp += 2;
2711         have -= 2;
2712         if (ssh_packet_log_type(type))
2713                 debug3_f("channel %u: down->up: type %u",
2714                     downstream->self, type);
2715
2716         switch (type) {
2717         case SSH2_MSG_CHANNEL_OPEN:
2718                 if ((original = sshbuf_from(cp, have)) == NULL ||
2719                     (modified = sshbuf_new()) == NULL) {
2720                         error_f("alloc");
2721                         goto out;
2722                 }
2723                 if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0 ||
2724                     (r = sshbuf_get_u32(original, &id)) != 0) {
2725                         error_fr(r, "parse");
2726                         goto out;
2727                 }
2728                 c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
2729                     -1, -1, -1, 0, 0, 0, ctype, 1);
2730                 c->mux_ctx = downstream;        /* point to mux client */
2731                 c->mux_downstream_id = id;      /* original downstream id */
2732                 if ((r = sshbuf_put_cstring(modified, ctype)) != 0 ||
2733                     (r = sshbuf_put_u32(modified, c->self)) != 0 ||
2734                     (r = sshbuf_putb(modified, original)) != 0) {
2735                         error_fr(r, "compose");
2736                         channel_free(ssh, c);
2737                         goto out;
2738                 }
2739                 break;
2740         case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2741                 /*
2742                  * Almost the same as SSH2_MSG_CHANNEL_OPEN, except then we
2743                  * need to parse 'remote_id' instead of 'ctype'.
2744                  */
2745                 if ((original = sshbuf_from(cp, have)) == NULL ||
2746                     (modified = sshbuf_new()) == NULL) {
2747                         error_f("alloc");
2748                         goto out;
2749                 }
2750                 if ((r = sshbuf_get_u32(original, &remote_id)) != 0 ||
2751                     (r = sshbuf_get_u32(original, &id)) != 0) {
2752                         error_fr(r, "parse");
2753                         goto out;
2754                 }
2755                 c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
2756                     -1, -1, -1, 0, 0, 0, "mux-down-connect", 1);
2757                 c->mux_ctx = downstream;        /* point to mux client */
2758                 c->mux_downstream_id = id;
2759                 c->remote_id = remote_id;
2760                 c->have_remote_id = 1;
2761                 if ((r = sshbuf_put_u32(modified, remote_id)) != 0 ||
2762                     (r = sshbuf_put_u32(modified, c->self)) != 0 ||
2763                     (r = sshbuf_putb(modified, original)) != 0) {
2764                         error_fr(r, "compose");
2765                         channel_free(ssh, c);
2766                         goto out;
2767                 }
2768                 break;
2769         case SSH2_MSG_GLOBAL_REQUEST:
2770                 if ((original = sshbuf_from(cp, have)) == NULL) {
2771                         error_f("alloc");
2772                         goto out;
2773                 }
2774                 if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0) {
2775                         error_fr(r, "parse");
2776                         goto out;
2777                 }
2778                 if (strcmp(ctype, "tcpip-forward") != 0) {
2779                         error_f("unsupported request %s", ctype);
2780                         goto out;
2781                 }
2782                 if ((r = sshbuf_get_u8(original, NULL)) != 0 ||
2783                     (r = sshbuf_get_cstring(original, &listen_host, NULL)) != 0 ||
2784                     (r = sshbuf_get_u32(original, &listen_port)) != 0) {
2785                         error_fr(r, "parse");
2786                         goto out;
2787                 }
2788                 if (listen_port > 65535) {
2789                         error_f("tcpip-forward for %s: bad port %u",
2790                             listen_host, listen_port);
2791                         goto out;
2792                 }
2793                 /* Record that connection to this host/port is permitted. */
2794                 permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL, "<mux>", -1,
2795                     listen_host, NULL, (int)listen_port, downstream);
2796                 listen_host = NULL;
2797                 break;
2798         case SSH2_MSG_CHANNEL_CLOSE:
2799                 if (have < 4)
2800                         break;
2801                 remote_id = PEEK_U32(cp);
2802                 if ((c = channel_by_remote_id(ssh, remote_id)) != NULL) {
2803                         if (c->flags & CHAN_CLOSE_RCVD)
2804                                 channel_free(ssh, c);
2805                         else
2806                                 c->flags |= CHAN_CLOSE_SENT;
2807                 }
2808                 break;
2809         }
2810         if (modified) {
2811                 if ((r = sshpkt_start(ssh, type)) != 0 ||
2812                     (r = sshpkt_putb(ssh, modified)) != 0 ||
2813                     (r = sshpkt_send(ssh)) != 0) {
2814                         error_fr(r, "send");
2815                         goto out;
2816                 }
2817         } else {
2818                 if ((r = sshpkt_start(ssh, type)) != 0 ||
2819                     (r = sshpkt_put(ssh, cp, have)) != 0 ||
2820                     (r = sshpkt_send(ssh)) != 0) {
2821                         error_fr(r, "send");
2822                         goto out;
2823                 }
2824         }
2825         ret = 0;
2826  out:
2827         free(ctype);
2828         free(listen_host);
2829         sshbuf_free(original);
2830         sshbuf_free(modified);
2831         return ret;
2832 }
2833
2834 /*
2835  * receive packets from upstream server and de-multiplex packets
2836  * to correct downstream:
2837  * implemented as a helper for channel input handlers,
2838  * replaces local (proxy) channel ID with downstream channel ID.
2839  */
2840 int
2841 channel_proxy_upstream(Channel *c, int type, u_int32_t seq, struct ssh *ssh)
2842 {
2843         struct sshbuf *b = NULL;
2844         Channel *downstream;
2845         const u_char *cp = NULL;
2846         size_t len;
2847         int r;
2848
2849         /*
2850          * When receiving packets from the peer we need to check whether we
2851          * need to forward the packets to the mux client. In this case we
2852          * restore the original channel id and keep track of CLOSE messages,
2853          * so we can cleanup the channel.
2854          */
2855         if (c == NULL || c->type != SSH_CHANNEL_MUX_PROXY)
2856                 return 0;
2857         if ((downstream = c->mux_ctx) == NULL)
2858                 return 0;
2859         switch (type) {
2860         case SSH2_MSG_CHANNEL_CLOSE:
2861         case SSH2_MSG_CHANNEL_DATA:
2862         case SSH2_MSG_CHANNEL_EOF:
2863         case SSH2_MSG_CHANNEL_EXTENDED_DATA:
2864         case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2865         case SSH2_MSG_CHANNEL_OPEN_FAILURE:
2866         case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
2867         case SSH2_MSG_CHANNEL_SUCCESS:
2868         case SSH2_MSG_CHANNEL_FAILURE:
2869         case SSH2_MSG_CHANNEL_REQUEST:
2870                 break;
2871         default:
2872                 debug2_f("channel %u: unsupported type %u", c->self, type);
2873                 return 0;
2874         }
2875         if ((b = sshbuf_new()) == NULL) {
2876                 error_f("alloc reply");
2877                 goto out;
2878         }
2879         /* get remaining payload (after id) */
2880         cp = sshpkt_ptr(ssh, &len);
2881         if (cp == NULL) {
2882                 error_f("no packet");
2883                 goto out;
2884         }
2885         /* translate id and send to muxclient */
2886         if ((r = sshbuf_put_u8(b, 0)) != 0 ||   /* padlen */
2887             (r = sshbuf_put_u8(b, type)) != 0 ||
2888             (r = sshbuf_put_u32(b, c->mux_downstream_id)) != 0 ||
2889             (r = sshbuf_put(b, cp, len)) != 0 ||
2890             (r = sshbuf_put_stringb(downstream->output, b)) != 0) {
2891                 error_fr(r, "compose muxclient");
2892                 goto out;
2893         }
2894         /* sshbuf_dump(b, stderr); */
2895         if (ssh_packet_log_type(type))
2896                 debug3_f("channel %u: up->down: type %u", c->self, type);
2897  out:
2898         /* update state */
2899         switch (type) {
2900         case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2901                 /* record remote_id for SSH2_MSG_CHANNEL_CLOSE */
2902                 if (cp && len > 4) {
2903                         c->remote_id = PEEK_U32(cp);
2904                         c->have_remote_id = 1;
2905                 }
2906                 break;
2907         case SSH2_MSG_CHANNEL_CLOSE:
2908                 if (c->flags & CHAN_CLOSE_SENT)
2909                         channel_free(ssh, c);
2910                 else
2911                         c->flags |= CHAN_CLOSE_RCVD;
2912                 break;
2913         }
2914         sshbuf_free(b);
2915         return 1;
2916 }
2917
2918 /* -- protocol input */
2919
2920 /* Parse a channel ID from the current packet */
2921 static int
2922 channel_parse_id(struct ssh *ssh, const char *where, const char *what)
2923 {
2924         u_int32_t id;
2925         int r;
2926
2927         if ((r = sshpkt_get_u32(ssh, &id)) != 0) {
2928                 error_r(r, "%s: parse id", where);
2929                 ssh_packet_disconnect(ssh, "Invalid %s message", what);
2930         }
2931         if (id > INT_MAX) {
2932                 error_r(r, "%s: bad channel id %u", where, id);
2933                 ssh_packet_disconnect(ssh, "Invalid %s channel id", what);
2934         }
2935         return (int)id;
2936 }
2937
2938 /* Lookup a channel from an ID in the current packet */
2939 static Channel *
2940 channel_from_packet_id(struct ssh *ssh, const char *where, const char *what)
2941 {
2942         int id = channel_parse_id(ssh, where, what);
2943         Channel *c;
2944
2945         if ((c = channel_lookup(ssh, id)) == NULL) {
2946                 ssh_packet_disconnect(ssh,
2947                     "%s packet referred to nonexistent channel %d", what, id);
2948         }
2949         return c;
2950 }
2951
2952 int
2953 channel_input_data(int type, u_int32_t seq, struct ssh *ssh)
2954 {
2955         const u_char *data;
2956         size_t data_len, win_len;
2957         Channel *c = channel_from_packet_id(ssh, __func__, "data");
2958         int r;
2959
2960         if (channel_proxy_upstream(c, type, seq, ssh))
2961                 return 0;
2962
2963         /* Ignore any data for non-open channels (might happen on close) */
2964         if (c->type != SSH_CHANNEL_OPEN &&
2965             c->type != SSH_CHANNEL_RDYNAMIC_OPEN &&
2966             c->type != SSH_CHANNEL_RDYNAMIC_FINISH &&
2967             c->type != SSH_CHANNEL_X11_OPEN)
2968                 return 0;
2969
2970         /* Get the data. */
2971         if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
2972             (r = sshpkt_get_end(ssh)) != 0)
2973                 fatal_fr(r, "channel %i: get data", c->self);
2974
2975         win_len = data_len;
2976         if (c->datagram)
2977                 win_len += 4;  /* string length header */
2978
2979         /*
2980          * The sending side reduces its window as it sends data, so we
2981          * must 'fake' consumption of the data in order to ensure that window
2982          * updates are sent back. Otherwise the connection might deadlock.
2983          */
2984         if (c->ostate != CHAN_OUTPUT_OPEN) {
2985                 c->local_window -= win_len;
2986                 c->local_consumed += win_len;
2987                 return 0;
2988         }
2989
2990         if (win_len > c->local_maxpacket) {
2991                 logit("channel %d: rcvd big packet %zu, maxpack %u",
2992                     c->self, win_len, c->local_maxpacket);
2993                 return 0;
2994         }
2995         if (win_len > c->local_window) {
2996                 logit("channel %d: rcvd too much data %zu, win %u",
2997                     c->self, win_len, c->local_window);
2998                 return 0;
2999         }
3000         c->local_window -= win_len;
3001
3002         if (c->datagram) {
3003                 if ((r = sshbuf_put_string(c->output, data, data_len)) != 0)
3004                         fatal_fr(r, "channel %i: append datagram", c->self);
3005         } else if ((r = sshbuf_put(c->output, data, data_len)) != 0)
3006                 fatal_fr(r, "channel %i: append data", c->self);
3007
3008         return 0;
3009 }
3010
3011 int
3012 channel_input_extended_data(int type, u_int32_t seq, struct ssh *ssh)
3013 {
3014         const u_char *data;
3015         size_t data_len;
3016         u_int32_t tcode;
3017         Channel *c = channel_from_packet_id(ssh, __func__, "extended data");
3018         int r;
3019
3020         if (channel_proxy_upstream(c, type, seq, ssh))
3021                 return 0;
3022         if (c->type != SSH_CHANNEL_OPEN) {
3023                 logit("channel %d: ext data for non open", c->self);
3024                 return 0;
3025         }
3026         if (c->flags & CHAN_EOF_RCVD) {
3027                 if (ssh->compat & SSH_BUG_EXTEOF)
3028                         debug("channel %d: accepting ext data after eof",
3029                             c->self);
3030                 else
3031                         ssh_packet_disconnect(ssh, "Received extended_data "
3032                             "after EOF on channel %d.", c->self);
3033         }
3034
3035         if ((r = sshpkt_get_u32(ssh, &tcode)) != 0) {
3036                 error_fr(r, "parse tcode");
3037                 ssh_packet_disconnect(ssh, "Invalid extended_data message");
3038         }
3039         if (c->efd == -1 ||
3040             c->extended_usage != CHAN_EXTENDED_WRITE ||
3041             tcode != SSH2_EXTENDED_DATA_STDERR) {
3042                 logit("channel %d: bad ext data", c->self);
3043                 return 0;
3044         }
3045         if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
3046             (r = sshpkt_get_end(ssh)) != 0) {
3047                 error_fr(r, "parse data");
3048                 ssh_packet_disconnect(ssh, "Invalid extended_data message");
3049         }
3050
3051         if (data_len > c->local_window) {
3052                 logit("channel %d: rcvd too much extended_data %zu, win %u",
3053                     c->self, data_len, c->local_window);
3054                 return 0;
3055         }
3056         debug2("channel %d: rcvd ext data %zu", c->self, data_len);
3057         /* XXX sshpkt_getb? */
3058         if ((r = sshbuf_put(c->extended, data, data_len)) != 0)
3059                 error_fr(r, "append");
3060         c->local_window -= data_len;
3061         return 0;
3062 }
3063
3064 int
3065 channel_input_ieof(int type, u_int32_t seq, struct ssh *ssh)
3066 {
3067         Channel *c = channel_from_packet_id(ssh, __func__, "ieof");
3068         int r;
3069
3070         if ((r = sshpkt_get_end(ssh)) != 0) {
3071                 error_fr(r, "parse data");
3072                 ssh_packet_disconnect(ssh, "Invalid ieof message");
3073         }
3074
3075         if (channel_proxy_upstream(c, type, seq, ssh))
3076                 return 0;
3077         chan_rcvd_ieof(ssh, c);
3078
3079         /* XXX force input close */
3080         if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
3081                 debug("channel %d: FORCE input drain", c->self);
3082                 c->istate = CHAN_INPUT_WAIT_DRAIN;
3083                 if (sshbuf_len(c->input) == 0)
3084                         chan_ibuf_empty(ssh, c);
3085         }
3086         return 0;
3087 }
3088
3089 int
3090 channel_input_oclose(int type, u_int32_t seq, struct ssh *ssh)
3091 {
3092         Channel *c = channel_from_packet_id(ssh, __func__, "oclose");
3093         int r;
3094
3095         if (channel_proxy_upstream(c, type, seq, ssh))
3096                 return 0;
3097         if ((r = sshpkt_get_end(ssh)) != 0) {
3098                 error_fr(r, "parse data");
3099                 ssh_packet_disconnect(ssh, "Invalid oclose message");
3100         }
3101         chan_rcvd_oclose(ssh, c);
3102         return 0;
3103 }
3104
3105 int
3106 channel_input_open_confirmation(int type, u_int32_t seq, struct ssh *ssh)
3107 {
3108         Channel *c = channel_from_packet_id(ssh, __func__, "open confirmation");
3109         u_int32_t remote_window, remote_maxpacket;
3110         int r;
3111
3112         if (channel_proxy_upstream(c, type, seq, ssh))
3113                 return 0;
3114         if (c->type != SSH_CHANNEL_OPENING)
3115                 ssh_packet_disconnect(ssh, "Received open confirmation for "
3116                     "non-opening channel %d.", c->self);
3117         /*
3118          * Record the remote channel number and mark that the channel
3119          * is now open.
3120          */
3121         if ((r = sshpkt_get_u32(ssh, &c->remote_id)) != 0 ||
3122             (r = sshpkt_get_u32(ssh, &remote_window)) != 0 ||
3123             (r = sshpkt_get_u32(ssh, &remote_maxpacket)) != 0 ||
3124             (r = sshpkt_get_end(ssh)) != 0) {
3125                 error_fr(r, "window/maxpacket");
3126                 ssh_packet_disconnect(ssh, "Invalid open confirmation message");
3127         }
3128
3129         c->have_remote_id = 1;
3130         c->remote_window = remote_window;
3131         c->remote_maxpacket = remote_maxpacket;
3132         c->type = SSH_CHANNEL_OPEN;
3133         if (c->open_confirm) {
3134                 debug2_f("channel %d: callback start", c->self);
3135                 c->open_confirm(ssh, c->self, 1, c->open_confirm_ctx);
3136                 debug2_f("channel %d: callback done", c->self);
3137         }
3138         debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
3139             c->remote_window, c->remote_maxpacket);
3140         return 0;
3141 }
3142
3143 static char *
3144 reason2txt(int reason)
3145 {
3146         switch (reason) {
3147         case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
3148                 return "administratively prohibited";
3149         case SSH2_OPEN_CONNECT_FAILED:
3150                 return "connect failed";
3151         case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
3152                 return "unknown channel type";
3153         case SSH2_OPEN_RESOURCE_SHORTAGE:
3154                 return "resource shortage";
3155         }
3156         return "unknown reason";
3157 }
3158
3159 int
3160 channel_input_open_failure(int type, u_int32_t seq, struct ssh *ssh)
3161 {
3162         Channel *c = channel_from_packet_id(ssh, __func__, "open failure");
3163         u_int32_t reason;
3164         char *msg = NULL;
3165         int r;
3166
3167         if (channel_proxy_upstream(c, type, seq, ssh))
3168                 return 0;
3169         if (c->type != SSH_CHANNEL_OPENING)
3170                 ssh_packet_disconnect(ssh, "Received open failure for "
3171                     "non-opening channel %d.", c->self);
3172         if ((r = sshpkt_get_u32(ssh, &reason)) != 0) {
3173                 error_fr(r, "parse reason");
3174                 ssh_packet_disconnect(ssh, "Invalid open failure message");
3175         }
3176         /* skip language */
3177         if ((r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
3178             (r = sshpkt_get_string_direct(ssh, NULL, NULL)) != 0 ||
3179             (r = sshpkt_get_end(ssh)) != 0) {
3180                 error_fr(r, "parse msg/lang");
3181                 ssh_packet_disconnect(ssh, "Invalid open failure message");
3182         }
3183         logit("channel %d: open failed: %s%s%s", c->self,
3184             reason2txt(reason), msg ? ": ": "", msg ? msg : "");
3185         free(msg);
3186         if (c->open_confirm) {
3187                 debug2_f("channel %d: callback start", c->self);
3188                 c->open_confirm(ssh, c->self, 0, c->open_confirm_ctx);
3189                 debug2_f("channel %d: callback done", c->self);
3190         }
3191         /* Schedule the channel for cleanup/deletion. */
3192         chan_mark_dead(ssh, c);
3193         return 0;
3194 }
3195
3196 int
3197 channel_input_window_adjust(int type, u_int32_t seq, struct ssh *ssh)
3198 {
3199         int id = channel_parse_id(ssh, __func__, "window adjust");
3200         Channel *c;
3201         u_int32_t adjust;
3202         u_int new_rwin;
3203         int r;
3204
3205         if ((c = channel_lookup(ssh, id)) == NULL) {
3206                 logit("Received window adjust for non-open channel %d.", id);
3207                 return 0;
3208         }
3209
3210         if (channel_proxy_upstream(c, type, seq, ssh))
3211                 return 0;
3212         if ((r = sshpkt_get_u32(ssh, &adjust)) != 0 ||
3213             (r = sshpkt_get_end(ssh)) != 0) {
3214                 error_fr(r, "parse adjust");
3215                 ssh_packet_disconnect(ssh, "Invalid window adjust message");
3216         }
3217         debug2("channel %d: rcvd adjust %u", c->self, adjust);
3218         if ((new_rwin = c->remote_window + adjust) < c->remote_window) {
3219                 fatal("channel %d: adjust %u overflows remote window %u",
3220                     c->self, adjust, c->remote_window);
3221         }
3222         c->remote_window = new_rwin;
3223         return 0;
3224 }
3225
3226 int
3227 channel_input_status_confirm(int type, u_int32_t seq, struct ssh *ssh)
3228 {
3229         int id = channel_parse_id(ssh, __func__, "status confirm");
3230         Channel *c;
3231         struct channel_confirm *cc;
3232
3233         /* Reset keepalive timeout */
3234         ssh_packet_set_alive_timeouts(ssh, 0);
3235
3236         debug2_f("type %d id %d", type, id);
3237
3238         if ((c = channel_lookup(ssh, id)) == NULL) {
3239                 logit_f("%d: unknown", id);
3240                 return 0;
3241         }
3242         if (channel_proxy_upstream(c, type, seq, ssh))
3243                 return 0;
3244         if (sshpkt_get_end(ssh) != 0)
3245                 ssh_packet_disconnect(ssh, "Invalid status confirm message");
3246         if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
3247                 return 0;
3248         cc->cb(ssh, type, c, cc->ctx);
3249         TAILQ_REMOVE(&c->status_confirms, cc, entry);
3250         freezero(cc, sizeof(*cc));
3251         return 0;
3252 }
3253
3254 /* -- tcp forwarding */
3255
3256 void
3257 channel_set_af(struct ssh *ssh, int af)
3258 {
3259         ssh->chanctxt->IPv4or6 = af;
3260 }
3261
3262
3263 /*
3264  * Determine whether or not a port forward listens to loopback, the
3265  * specified address or wildcard. On the client, a specified bind
3266  * address will always override gateway_ports. On the server, a
3267  * gateway_ports of 1 (``yes'') will override the client's specification
3268  * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
3269  * will bind to whatever address the client asked for.
3270  *
3271  * Special-case listen_addrs are:
3272  *
3273  * "0.0.0.0"               -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
3274  * "" (empty string), "*"  -> wildcard v4/v6
3275  * "localhost"             -> loopback v4/v6
3276  * "127.0.0.1" / "::1"     -> accepted even if gateway_ports isn't set
3277  */
3278 static const char *
3279 channel_fwd_bind_addr(struct ssh *ssh, const char *listen_addr, int *wildcardp,
3280     int is_client, struct ForwardOptions *fwd_opts)
3281 {
3282         const char *addr = NULL;
3283         int wildcard = 0;
3284
3285         if (listen_addr == NULL) {
3286                 /* No address specified: default to gateway_ports setting */
3287                 if (fwd_opts->gateway_ports)
3288                         wildcard = 1;
3289         } else if (fwd_opts->gateway_ports || is_client) {
3290                 if (((ssh->compat & SSH_OLD_FORWARD_ADDR) &&
3291                     strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
3292                     *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
3293                     (!is_client && fwd_opts->gateway_ports == 1)) {
3294                         wildcard = 1;
3295                         /*
3296                          * Notify client if they requested a specific listen
3297                          * address and it was overridden.
3298                          */
3299                         if (*listen_addr != '\0' &&
3300                             strcmp(listen_addr, "0.0.0.0") != 0 &&
3301                             strcmp(listen_addr, "*") != 0) {
3302                                 ssh_packet_send_debug(ssh,
3303                                     "Forwarding listen address "
3304                                     "\"%s\" overridden by server "
3305                                     "GatewayPorts", listen_addr);
3306                         }
3307                 } else if (strcmp(listen_addr, "localhost") != 0 ||
3308                     strcmp(listen_addr, "127.0.0.1") == 0 ||
3309                     strcmp(listen_addr, "::1") == 0) {
3310                         /*
3311                          * Accept explicit localhost address when
3312                          * GatewayPorts=yes. The "localhost" hostname is
3313                          * deliberately skipped here so it will listen on all
3314                          * available local address families.
3315                          */
3316                         addr = listen_addr;
3317                 }
3318         } else if (strcmp(listen_addr, "127.0.0.1") == 0 ||
3319             strcmp(listen_addr, "::1") == 0) {
3320                 /*
3321                  * If a specific IPv4/IPv6 localhost address has been
3322                  * requested then accept it even if gateway_ports is in
3323                  * effect. This allows the client to prefer IPv4 or IPv6.
3324                  */
3325                 addr = listen_addr;
3326         }
3327         if (wildcardp != NULL)
3328                 *wildcardp = wildcard;
3329         return addr;
3330 }
3331
3332 static int
3333 channel_setup_fwd_listener_tcpip(struct ssh *ssh, int type,
3334     struct Forward *fwd, int *allocated_listen_port,
3335     struct ForwardOptions *fwd_opts)
3336 {
3337         Channel *c;
3338         int sock, r, success = 0, wildcard = 0, is_client;
3339         struct addrinfo hints, *ai, *aitop;
3340         const char *host, *addr;
3341         char ntop[NI_MAXHOST], strport[NI_MAXSERV];
3342         in_port_t *lport_p;
3343
3344         is_client = (type == SSH_CHANNEL_PORT_LISTENER);
3345
3346         if (is_client && fwd->connect_path != NULL) {
3347                 host = fwd->connect_path;
3348         } else {
3349                 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
3350                     fwd->listen_host : fwd->connect_host;
3351                 if (host == NULL) {
3352                         error("No forward host name.");
3353                         return 0;
3354                 }
3355                 if (strlen(host) >= NI_MAXHOST) {
3356                         error("Forward host name too long.");
3357                         return 0;
3358                 }
3359         }
3360
3361         /* Determine the bind address, cf. channel_fwd_bind_addr() comment */
3362         addr = channel_fwd_bind_addr(ssh, fwd->listen_host, &wildcard,
3363             is_client, fwd_opts);
3364         debug3_f("type %d wildcard %d addr %s", type, wildcard,
3365             (addr == NULL) ? "NULL" : addr);
3366
3367         /*
3368          * getaddrinfo returns a loopback address if the hostname is
3369          * set to NULL and hints.ai_flags is not AI_PASSIVE
3370          */
3371         memset(&hints, 0, sizeof(hints));
3372         hints.ai_family = ssh->chanctxt->IPv4or6;
3373         hints.ai_flags = wildcard ? AI_PASSIVE : 0;
3374         hints.ai_socktype = SOCK_STREAM;
3375         snprintf(strport, sizeof strport, "%d", fwd->listen_port);
3376         if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
3377                 if (addr == NULL) {
3378                         /* This really shouldn't happen */
3379                         ssh_packet_disconnect(ssh, "getaddrinfo: fatal error: %s",
3380                             ssh_gai_strerror(r));
3381                 } else {
3382                         error_f("getaddrinfo(%.64s): %s", addr,
3383                             ssh_gai_strerror(r));
3384                 }
3385                 return 0;
3386         }
3387         if (allocated_listen_port != NULL)
3388                 *allocated_listen_port = 0;
3389         for (ai = aitop; ai; ai = ai->ai_next) {
3390                 switch (ai->ai_family) {
3391                 case AF_INET:
3392                         lport_p = &((struct sockaddr_in *)ai->ai_addr)->
3393                             sin_port;
3394                         break;
3395                 case AF_INET6:
3396                         lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
3397                             sin6_port;
3398                         break;
3399                 default:
3400                         continue;
3401                 }
3402                 /*
3403                  * If allocating a port for -R forwards, then use the
3404                  * same port for all address families.
3405                  */
3406                 if (type == SSH_CHANNEL_RPORT_LISTENER &&
3407                     fwd->listen_port == 0 && allocated_listen_port != NULL &&
3408                     *allocated_listen_port > 0)
3409                         *lport_p = htons(*allocated_listen_port);
3410
3411                 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
3412                     strport, sizeof(strport),
3413                     NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
3414                         error_f("getnameinfo failed");
3415                         continue;
3416                 }
3417                 /* Create a port to listen for the host. */
3418                 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3419                 if (sock == -1) {
3420                         /* this is no error since kernel may not support ipv6 */
3421                         verbose("socket [%s]:%s: %.100s", ntop, strport,
3422                             strerror(errno));
3423                         continue;
3424                 }
3425
3426                 set_reuseaddr(sock);
3427                 if (ai->ai_family == AF_INET6)
3428                         sock_set_v6only(sock);
3429
3430                 debug("Local forwarding listening on %s port %s.",
3431                     ntop, strport);
3432
3433                 /* Bind the socket to the address. */
3434                 if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
3435                         /*
3436                          * address can be in if use ipv6 address is
3437                          * already bound
3438                          */
3439                         if (!ai->ai_next)
3440                                 error("bind [%s]:%s: %.100s",
3441                                     ntop, strport, strerror(errno));
3442                         else
3443                                 verbose("bind [%s]:%s: %.100s",
3444                                     ntop, strport, strerror(errno));
3445
3446                         close(sock);
3447                         continue;
3448                 }
3449                 /* Start listening for connections on the socket. */
3450                 if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
3451                         error("listen [%s]:%s: %.100s", ntop, strport,
3452                             strerror(errno));
3453                         close(sock);
3454                         continue;
3455                 }
3456
3457                 /*
3458                  * fwd->listen_port == 0 requests a dynamically allocated port -
3459                  * record what we got.
3460                  */
3461                 if (type == SSH_CHANNEL_RPORT_LISTENER &&
3462                     fwd->listen_port == 0 &&
3463                     allocated_listen_port != NULL &&
3464                     *allocated_listen_port == 0) {
3465                         *allocated_listen_port = get_local_port(sock);
3466                         debug("Allocated listen port %d",
3467                             *allocated_listen_port);
3468                 }
3469
3470                 /* Allocate a channel number for the socket. */
3471                 c = channel_new(ssh, "port listener", type, sock, sock, -1,
3472                     CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3473                     0, "port listener", 1);
3474                 c->path = xstrdup(host);
3475                 c->host_port = fwd->connect_port;
3476                 c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
3477                 if (fwd->listen_port == 0 && allocated_listen_port != NULL &&
3478                     !(ssh->compat & SSH_BUG_DYNAMIC_RPORT))
3479                         c->listening_port = *allocated_listen_port;
3480                 else
3481                         c->listening_port = fwd->listen_port;
3482                 success = 1;
3483         }
3484         if (success == 0)
3485                 error_f("cannot listen to port: %d", fwd->listen_port);
3486         freeaddrinfo(aitop);
3487         return success;
3488 }
3489
3490 static int
3491 channel_setup_fwd_listener_streamlocal(struct ssh *ssh, int type,
3492     struct Forward *fwd, struct ForwardOptions *fwd_opts)
3493 {
3494         struct sockaddr_un sunaddr;
3495         const char *path;
3496         Channel *c;
3497         int port, sock;
3498         mode_t omask;
3499
3500         switch (type) {
3501         case SSH_CHANNEL_UNIX_LISTENER:
3502                 if (fwd->connect_path != NULL) {
3503                         if (strlen(fwd->connect_path) > sizeof(sunaddr.sun_path)) {
3504                                 error("Local connecting path too long: %s",
3505                                     fwd->connect_path);
3506                                 return 0;
3507                         }
3508                         path = fwd->connect_path;
3509                         port = PORT_STREAMLOCAL;
3510                 } else {
3511                         if (fwd->connect_host == NULL) {
3512                                 error("No forward host name.");
3513                                 return 0;
3514                         }
3515                         if (strlen(fwd->connect_host) >= NI_MAXHOST) {
3516                                 error("Forward host name too long.");
3517                                 return 0;
3518                         }
3519                         path = fwd->connect_host;
3520                         port = fwd->connect_port;
3521                 }
3522                 break;
3523         case SSH_CHANNEL_RUNIX_LISTENER:
3524                 path = fwd->listen_path;
3525                 port = PORT_STREAMLOCAL;
3526                 break;
3527         default:
3528                 error_f("unexpected channel type %d", type);
3529                 return 0;
3530         }
3531
3532         if (fwd->listen_path == NULL) {
3533                 error("No forward path name.");
3534                 return 0;
3535         }
3536         if (strlen(fwd->listen_path) > sizeof(sunaddr.sun_path)) {
3537                 error("Local listening path too long: %s", fwd->listen_path);
3538                 return 0;
3539         }
3540
3541         debug3_f("type %d path %s", type, fwd->listen_path);
3542
3543         /* Start a Unix domain listener. */
3544         omask = umask(fwd_opts->streamlocal_bind_mask);
3545         sock = unix_listener(fwd->listen_path, SSH_LISTEN_BACKLOG,
3546             fwd_opts->streamlocal_bind_unlink);
3547         umask(omask);
3548         if (sock < 0)
3549                 return 0;
3550
3551         debug("Local forwarding listening on path %s.", fwd->listen_path);
3552
3553         /* Allocate a channel number for the socket. */
3554         c = channel_new(ssh, "unix listener", type, sock, sock, -1,
3555             CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3556             0, "unix listener", 1);
3557         c->path = xstrdup(path);
3558         c->host_port = port;
3559         c->listening_port = PORT_STREAMLOCAL;
3560         c->listening_addr = xstrdup(fwd->listen_path);
3561         return 1;
3562 }
3563
3564 static int
3565 channel_cancel_rport_listener_tcpip(struct ssh *ssh,
3566     const char *host, u_short port)
3567 {
3568         u_int i;
3569         int found = 0;
3570
3571         for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3572                 Channel *c = ssh->chanctxt->channels[i];
3573                 if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
3574                         continue;
3575                 if (strcmp(c->path, host) == 0 && c->listening_port == port) {
3576                         debug2_f("close channel %d", i);
3577                         channel_free(ssh, c);
3578                         found = 1;
3579                 }
3580         }
3581
3582         return found;
3583 }
3584
3585 static int
3586 channel_cancel_rport_listener_streamlocal(struct ssh *ssh, const char *path)
3587 {
3588         u_int i;
3589         int found = 0;
3590
3591         for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3592                 Channel *c = ssh->chanctxt->channels[i];
3593                 if (c == NULL || c->type != SSH_CHANNEL_RUNIX_LISTENER)
3594                         continue;
3595                 if (c->path == NULL)
3596                         continue;
3597                 if (strcmp(c->path, path) == 0) {
3598                         debug2_f("close channel %d", i);
3599                         channel_free(ssh, c);
3600                         found = 1;
3601                 }
3602         }
3603
3604         return found;
3605 }
3606
3607 int
3608 channel_cancel_rport_listener(struct ssh *ssh, struct Forward *fwd)
3609 {
3610         if (fwd->listen_path != NULL) {
3611                 return channel_cancel_rport_listener_streamlocal(ssh,
3612                     fwd->listen_path);
3613         } else {
3614                 return channel_cancel_rport_listener_tcpip(ssh,
3615                     fwd->listen_host, fwd->listen_port);
3616         }
3617 }
3618
3619 static int
3620 channel_cancel_lport_listener_tcpip(struct ssh *ssh,
3621     const char *lhost, u_short lport, int cport,
3622     struct ForwardOptions *fwd_opts)
3623 {
3624         u_int i;
3625         int found = 0;
3626         const char *addr = channel_fwd_bind_addr(ssh, lhost, NULL, 1, fwd_opts);
3627
3628         for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3629                 Channel *c = ssh->chanctxt->channels[i];
3630                 if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
3631                         continue;
3632                 if (c->listening_port != lport)
3633                         continue;
3634                 if (cport == CHANNEL_CANCEL_PORT_STATIC) {
3635                         /* skip dynamic forwardings */
3636                         if (c->host_port == 0)
3637                                 continue;
3638                 } else {
3639                         if (c->host_port != cport)
3640                                 continue;
3641                 }
3642                 if ((c->listening_addr == NULL && addr != NULL) ||
3643                     (c->listening_addr != NULL && addr == NULL))
3644                         continue;
3645                 if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
3646                         debug2_f("close channel %d", i);
3647                         channel_free(ssh, c);
3648                         found = 1;
3649                 }
3650         }
3651
3652         return found;
3653 }
3654
3655 static int
3656 channel_cancel_lport_listener_streamlocal(struct ssh *ssh, const char *path)
3657 {
3658         u_int i;
3659         int found = 0;
3660
3661         if (path == NULL) {
3662                 error_f("no path specified.");
3663                 return 0;
3664         }
3665
3666         for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3667                 Channel *c = ssh->chanctxt->channels[i];
3668                 if (c == NULL || c->type != SSH_CHANNEL_UNIX_LISTENER)
3669                         continue;
3670                 if (c->listening_addr == NULL)
3671                         continue;
3672                 if (strcmp(c->listening_addr, path) == 0) {
3673                         debug2_f("close channel %d", i);
3674                         channel_free(ssh, c);
3675                         found = 1;
3676                 }
3677         }
3678
3679         return found;
3680 }
3681
3682 int
3683 channel_cancel_lport_listener(struct ssh *ssh,
3684     struct Forward *fwd, int cport, struct ForwardOptions *fwd_opts)
3685 {
3686         if (fwd->listen_path != NULL) {
3687                 return channel_cancel_lport_listener_streamlocal(ssh,
3688                     fwd->listen_path);
3689         } else {
3690                 return channel_cancel_lport_listener_tcpip(ssh,
3691                     fwd->listen_host, fwd->listen_port, cport, fwd_opts);
3692         }
3693 }
3694
3695 /* protocol local port fwd, used by ssh */
3696 int
3697 channel_setup_local_fwd_listener(struct ssh *ssh,
3698     struct Forward *fwd, struct ForwardOptions *fwd_opts)
3699 {
3700         if (fwd->listen_path != NULL) {
3701                 return channel_setup_fwd_listener_streamlocal(ssh,
3702                     SSH_CHANNEL_UNIX_LISTENER, fwd, fwd_opts);
3703         } else {
3704                 return channel_setup_fwd_listener_tcpip(ssh,
3705                     SSH_CHANNEL_PORT_LISTENER, fwd, NULL, fwd_opts);
3706         }
3707 }
3708
3709 /* Matches a remote forwarding permission against a requested forwarding */
3710 static int
3711 remote_open_match(struct permission *allowed_open, struct Forward *fwd)
3712 {
3713         int ret;
3714         char *lhost;
3715
3716         /* XXX add ACLs for streamlocal */
3717         if (fwd->listen_path != NULL)
3718                 return 1;
3719
3720         if (fwd->listen_host == NULL || allowed_open->listen_host == NULL)
3721                 return 0;
3722
3723         if (allowed_open->listen_port != FWD_PERMIT_ANY_PORT &&
3724             allowed_open->listen_port != fwd->listen_port)
3725                 return 0;
3726
3727         /* Match hostnames case-insensitively */
3728         lhost = xstrdup(fwd->listen_host);
3729         lowercase(lhost);
3730         ret = match_pattern(lhost, allowed_open->listen_host);
3731         free(lhost);
3732
3733         return ret;
3734 }
3735
3736 /* Checks whether a requested remote forwarding is permitted */
3737 static int
3738 check_rfwd_permission(struct ssh *ssh, struct Forward *fwd)
3739 {
3740         struct ssh_channels *sc = ssh->chanctxt;
3741         struct permission_set *pset = &sc->remote_perms;
3742         u_int i, permit, permit_adm = 1;
3743         struct permission *perm;
3744
3745         /* XXX apply GatewayPorts override before checking? */
3746
3747         permit = pset->all_permitted;
3748         if (!permit) {
3749                 for (i = 0; i < pset->num_permitted_user; i++) {
3750                         perm = &pset->permitted_user[i];
3751                         if (remote_open_match(perm, fwd)) {
3752                                 permit = 1;
3753                                 break;
3754                         }
3755                 }
3756         }
3757
3758         if (pset->num_permitted_admin > 0) {
3759                 permit_adm = 0;
3760                 for (i = 0; i < pset->num_permitted_admin; i++) {
3761                         perm = &pset->permitted_admin[i];
3762                         if (remote_open_match(perm, fwd)) {
3763                                 permit_adm = 1;
3764                                 break;
3765                         }
3766                 }
3767         }
3768
3769         return permit && permit_adm;
3770 }
3771
3772 /* protocol v2 remote port fwd, used by sshd */
3773 int
3774 channel_setup_remote_fwd_listener(struct ssh *ssh, struct Forward *fwd,
3775     int *allocated_listen_port, struct ForwardOptions *fwd_opts)
3776 {
3777         if (!check_rfwd_permission(ssh, fwd)) {
3778                 ssh_packet_send_debug(ssh, "port forwarding refused");
3779                 if (fwd->listen_path != NULL)
3780                         /* XXX always allowed, see remote_open_match() */
3781                         logit("Received request from %.100s port %d to "
3782                             "remote forward to path \"%.100s\", "
3783                             "but the request was denied.",
3784                             ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
3785                             fwd->listen_path);
3786                 else if(fwd->listen_host != NULL)
3787                         logit("Received request from %.100s port %d to "
3788                             "remote forward to host %.100s port %d, "
3789                             "but the request was denied.",
3790                             ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
3791                             fwd->listen_host, fwd->listen_port );
3792                 else
3793                         logit("Received request from %.100s port %d to remote "
3794                             "forward, but the request was denied.",
3795                             ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
3796                 return 0;
3797         }
3798         if (fwd->listen_path != NULL) {
3799                 return channel_setup_fwd_listener_streamlocal(ssh,
3800                     SSH_CHANNEL_RUNIX_LISTENER, fwd, fwd_opts);
3801         } else {
3802                 return channel_setup_fwd_listener_tcpip(ssh,
3803                     SSH_CHANNEL_RPORT_LISTENER, fwd, allocated_listen_port,
3804                     fwd_opts);
3805         }
3806 }
3807
3808 /*
3809  * Translate the requested rfwd listen host to something usable for
3810  * this server.
3811  */
3812 static const char *
3813 channel_rfwd_bind_host(const char *listen_host)
3814 {
3815         if (listen_host == NULL) {
3816                 return "localhost";
3817         } else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
3818                 return "";
3819         } else
3820                 return listen_host;
3821 }
3822
3823 /*
3824  * Initiate forwarding of connections to port "port" on remote host through
3825  * the secure channel to host:port from local side.
3826  * Returns handle (index) for updating the dynamic listen port with
3827  * channel_update_permission().
3828  */
3829 int
3830 channel_request_remote_forwarding(struct ssh *ssh, struct Forward *fwd)
3831 {
3832         int r, success = 0, idx = -1;
3833         char *host_to_connect, *listen_host, *listen_path;
3834         int port_to_connect, listen_port;
3835
3836         /* Send the forward request to the remote side. */
3837         if (fwd->listen_path != NULL) {
3838                 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
3839                     (r = sshpkt_put_cstring(ssh,
3840                     "streamlocal-forward@openssh.com")) != 0 ||
3841                     (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
3842                     (r = sshpkt_put_cstring(ssh, fwd->listen_path)) != 0 ||
3843                     (r = sshpkt_send(ssh)) != 0 ||
3844                     (r = ssh_packet_write_wait(ssh)) != 0)
3845                         fatal_fr(r, "request streamlocal");
3846         } else {
3847                 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
3848                     (r = sshpkt_put_cstring(ssh, "tcpip-forward")) != 0 ||
3849                     (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
3850                     (r = sshpkt_put_cstring(ssh,
3851                     channel_rfwd_bind_host(fwd->listen_host))) != 0 ||
3852                     (r = sshpkt_put_u32(ssh, fwd->listen_port)) != 0 ||
3853                     (r = sshpkt_send(ssh)) != 0 ||
3854                     (r = ssh_packet_write_wait(ssh)) != 0)
3855                         fatal_fr(r, "request tcpip-forward");
3856         }
3857         /* Assume that server accepts the request */
3858         success = 1;
3859         if (success) {
3860                 /* Record that connection to this host/port is permitted. */
3861                 host_to_connect = listen_host = listen_path = NULL;
3862                 port_to_connect = listen_port = 0;
3863                 if (fwd->connect_path != NULL) {
3864                         host_to_connect = xstrdup(fwd->connect_path);
3865                         port_to_connect = PORT_STREAMLOCAL;
3866                 } else {
3867                         host_to_connect = xstrdup(fwd->connect_host);
3868                         port_to_connect = fwd->connect_port;
3869                 }
3870                 if (fwd->listen_path != NULL) {
3871                         listen_path = xstrdup(fwd->listen_path);
3872                         listen_port = PORT_STREAMLOCAL;
3873                 } else {
3874                         if (fwd->listen_host != NULL)
3875                                 listen_host = xstrdup(fwd->listen_host);
3876                         listen_port = fwd->listen_port;
3877                 }
3878                 idx = permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL,
3879                     host_to_connect, port_to_connect,
3880                     listen_host, listen_path, listen_port, NULL);
3881         }
3882         return idx;
3883 }
3884
3885 static int
3886 open_match(struct permission *allowed_open, const char *requestedhost,
3887     int requestedport)
3888 {
3889         if (allowed_open->host_to_connect == NULL)
3890                 return 0;
3891         if (allowed_open->port_to_connect != FWD_PERMIT_ANY_PORT &&
3892             allowed_open->port_to_connect != requestedport)
3893                 return 0;
3894         if (strcmp(allowed_open->host_to_connect, FWD_PERMIT_ANY_HOST) != 0 &&
3895             strcmp(allowed_open->host_to_connect, requestedhost) != 0)
3896                 return 0;
3897         return 1;
3898 }
3899
3900 /*
3901  * Note that in the listen host/port case
3902  * we don't support FWD_PERMIT_ANY_PORT and
3903  * need to translate between the configured-host (listen_host)
3904  * and what we've sent to the remote server (channel_rfwd_bind_host)
3905  */
3906 static int
3907 open_listen_match_tcpip(struct permission *allowed_open,
3908     const char *requestedhost, u_short requestedport, int translate)
3909 {
3910         const char *allowed_host;
3911
3912         if (allowed_open->host_to_connect == NULL)
3913                 return 0;
3914         if (allowed_open->listen_port != requestedport)
3915                 return 0;
3916         if (!translate && allowed_open->listen_host == NULL &&
3917             requestedhost == NULL)
3918                 return 1;
3919         allowed_host = translate ?
3920             channel_rfwd_bind_host(allowed_open->listen_host) :
3921             allowed_open->listen_host;
3922         if (allowed_host == NULL || requestedhost == NULL ||
3923             strcmp(allowed_host, requestedhost) != 0)
3924                 return 0;
3925         return 1;
3926 }
3927
3928 static int
3929 open_listen_match_streamlocal(struct permission *allowed_open,
3930     const char *requestedpath)
3931 {
3932         if (allowed_open->host_to_connect == NULL)
3933                 return 0;
3934         if (allowed_open->listen_port != PORT_STREAMLOCAL)
3935                 return 0;
3936         if (allowed_open->listen_path == NULL ||
3937             strcmp(allowed_open->listen_path, requestedpath) != 0)
3938                 return 0;
3939         return 1;
3940 }
3941
3942 /*
3943  * Request cancellation of remote forwarding of connection host:port from
3944  * local side.
3945  */
3946 static int
3947 channel_request_rforward_cancel_tcpip(struct ssh *ssh,
3948     const char *host, u_short port)
3949 {
3950         struct ssh_channels *sc = ssh->chanctxt;
3951         struct permission_set *pset = &sc->local_perms;
3952         int r;
3953         u_int i;
3954         struct permission *perm = NULL;
3955
3956         for (i = 0; i < pset->num_permitted_user; i++) {
3957                 perm = &pset->permitted_user[i];
3958                 if (open_listen_match_tcpip(perm, host, port, 0))
3959                         break;
3960                 perm = NULL;
3961         }
3962         if (perm == NULL) {
3963                 debug_f("requested forward not found");
3964                 return -1;
3965         }
3966         if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
3967             (r = sshpkt_put_cstring(ssh, "cancel-tcpip-forward")) != 0 ||
3968             (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
3969             (r = sshpkt_put_cstring(ssh, channel_rfwd_bind_host(host))) != 0 ||
3970             (r = sshpkt_put_u32(ssh, port)) != 0 ||
3971             (r = sshpkt_send(ssh)) != 0)
3972                 fatal_fr(r, "send cancel");
3973
3974         fwd_perm_clear(perm); /* unregister */
3975
3976         return 0;
3977 }
3978
3979 /*
3980  * Request cancellation of remote forwarding of Unix domain socket
3981  * path from local side.
3982  */
3983 static int
3984 channel_request_rforward_cancel_streamlocal(struct ssh *ssh, const char *path)
3985 {
3986         struct ssh_channels *sc = ssh->chanctxt;
3987         struct permission_set *pset = &sc->local_perms;
3988         int r;
3989         u_int i;
3990         struct permission *perm = NULL;
3991
3992         for (i = 0; i < pset->num_permitted_user; i++) {
3993                 perm = &pset->permitted_user[i];
3994                 if (open_listen_match_streamlocal(perm, path))
3995                         break;
3996                 perm = NULL;
3997         }
3998         if (perm == NULL) {
3999                 debug_f("requested forward not found");
4000                 return -1;
4001         }
4002         if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4003             (r = sshpkt_put_cstring(ssh,
4004             "cancel-streamlocal-forward@openssh.com")) != 0 ||
4005             (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
4006             (r = sshpkt_put_cstring(ssh, path)) != 0 ||
4007             (r = sshpkt_send(ssh)) != 0)
4008                 fatal_fr(r, "send cancel");
4009
4010         fwd_perm_clear(perm); /* unregister */
4011
4012         return 0;
4013 }
4014
4015 /*
4016  * Request cancellation of remote forwarding of a connection from local side.
4017  */
4018 int
4019 channel_request_rforward_cancel(struct ssh *ssh, struct Forward *fwd)
4020 {
4021         if (fwd->listen_path != NULL) {
4022                 return channel_request_rforward_cancel_streamlocal(ssh,
4023                     fwd->listen_path);
4024         } else {
4025                 return channel_request_rforward_cancel_tcpip(ssh,
4026                     fwd->listen_host,
4027                     fwd->listen_port ? fwd->listen_port : fwd->allocated_port);
4028         }
4029 }
4030
4031 /*
4032  * Permits opening to any host/port if permitted_user[] is empty.  This is
4033  * usually called by the server, because the user could connect to any port
4034  * anyway, and the server has no way to know but to trust the client anyway.
4035  */
4036 void
4037 channel_permit_all(struct ssh *ssh, int where)
4038 {
4039         struct permission_set *pset = permission_set_get(ssh, where);
4040
4041         if (pset->num_permitted_user == 0)
4042                 pset->all_permitted = 1;
4043 }
4044
4045 /*
4046  * Permit the specified host/port for forwarding.
4047  */
4048 void
4049 channel_add_permission(struct ssh *ssh, int who, int where,
4050     char *host, int port)
4051 {
4052         int local = where == FORWARD_LOCAL;
4053         struct permission_set *pset = permission_set_get(ssh, where);
4054
4055         debug("allow %s forwarding to host %s port %d",
4056             fwd_ident(who, where), host, port);
4057         /*
4058          * Remote forwards set listen_host/port, local forwards set
4059          * host/port_to_connect.
4060          */
4061         permission_set_add(ssh, who, where,
4062             local ? host : 0, local ? port : 0,
4063             local ? NULL : host, NULL, local ? 0 : port, NULL);
4064         pset->all_permitted = 0;
4065 }
4066
4067 /*
4068  * Administratively disable forwarding.
4069  */
4070 void
4071 channel_disable_admin(struct ssh *ssh, int where)
4072 {
4073         channel_clear_permission(ssh, FORWARD_ADM, where);
4074         permission_set_add(ssh, FORWARD_ADM, where,
4075             NULL, 0, NULL, NULL, 0, NULL);
4076 }
4077
4078 /*
4079  * Clear a list of permitted opens.
4080  */
4081 void
4082 channel_clear_permission(struct ssh *ssh, int who, int where)
4083 {
4084         struct permission **permp;
4085         u_int *npermp;
4086
4087         permission_set_get_array(ssh, who, where, &permp, &npermp);
4088         *permp = xrecallocarray(*permp, *npermp, 0, sizeof(**permp));
4089         *npermp = 0;
4090 }
4091
4092 /*
4093  * Update the listen port for a dynamic remote forward, after
4094  * the actual 'newport' has been allocated. If 'newport' < 0 is
4095  * passed then they entry will be invalidated.
4096  */
4097 void
4098 channel_update_permission(struct ssh *ssh, int idx, int newport)
4099 {
4100         struct permission_set *pset = &ssh->chanctxt->local_perms;
4101
4102         if (idx < 0 || (u_int)idx >= pset->num_permitted_user) {
4103                 debug_f("index out of range: %d num_permitted_user %d",
4104                     idx, pset->num_permitted_user);
4105                 return;
4106         }
4107         debug("%s allowed port %d for forwarding to host %s port %d",
4108             newport > 0 ? "Updating" : "Removing",
4109             newport,
4110             pset->permitted_user[idx].host_to_connect,
4111             pset->permitted_user[idx].port_to_connect);
4112         if (newport <= 0)
4113                 fwd_perm_clear(&pset->permitted_user[idx]);
4114         else {
4115                 pset->permitted_user[idx].listen_port =
4116                     (ssh->compat & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
4117         }
4118 }
4119
4120 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
4121 int
4122 permitopen_port(const char *p)
4123 {
4124         int port;
4125
4126         if (strcmp(p, "*") == 0)
4127                 return FWD_PERMIT_ANY_PORT;
4128         if ((port = a2port(p)) > 0)
4129                 return port;
4130         return -1;
4131 }
4132
4133 /* Try to start non-blocking connect to next host in cctx list */
4134 static int
4135 connect_next(struct channel_connect *cctx)
4136 {
4137         int sock, saved_errno;
4138         struct sockaddr_un *sunaddr;
4139         char ntop[NI_MAXHOST];
4140         char strport[MAXIMUM(NI_MAXSERV, sizeof(sunaddr->sun_path))];
4141
4142         for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
4143                 switch (cctx->ai->ai_family) {
4144                 case AF_UNIX:
4145                         /* unix:pathname instead of host:port */
4146                         sunaddr = (struct sockaddr_un *)cctx->ai->ai_addr;
4147                         strlcpy(ntop, "unix", sizeof(ntop));
4148                         strlcpy(strport, sunaddr->sun_path, sizeof(strport));
4149                         break;
4150                 case AF_INET:
4151                 case AF_INET6:
4152                         if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
4153                             ntop, sizeof(ntop), strport, sizeof(strport),
4154                             NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
4155                                 error("connect_next: getnameinfo failed");
4156                                 continue;
4157                         }
4158                         break;
4159                 default:
4160                         continue;
4161                 }
4162                 if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
4163                     cctx->ai->ai_protocol)) == -1) {
4164                         if (cctx->ai->ai_next == NULL)
4165                                 error("socket: %.100s", strerror(errno));
4166                         else
4167                                 verbose("socket: %.100s", strerror(errno));
4168                         continue;
4169                 }
4170                 if (set_nonblock(sock) == -1)
4171                         fatal_f("set_nonblock(%d)", sock);
4172                 if (connect(sock, cctx->ai->ai_addr,
4173                     cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
4174                         debug("connect_next: host %.100s ([%.100s]:%s): "
4175                             "%.100s", cctx->host, ntop, strport,
4176                             strerror(errno));
4177                         saved_errno = errno;
4178                         close(sock);
4179                         errno = saved_errno;
4180                         continue;       /* fail -- try next */
4181                 }
4182                 if (cctx->ai->ai_family != AF_UNIX)
4183                         set_nodelay(sock);
4184                 debug("connect_next: host %.100s ([%.100s]:%s) "
4185                     "in progress, fd=%d", cctx->host, ntop, strport, sock);
4186                 cctx->ai = cctx->ai->ai_next;
4187                 return sock;
4188         }
4189         return -1;
4190 }
4191
4192 static void
4193 channel_connect_ctx_free(struct channel_connect *cctx)
4194 {
4195         free(cctx->host);
4196         if (cctx->aitop) {
4197                 if (cctx->aitop->ai_family == AF_UNIX)
4198                         free(cctx->aitop);
4199                 else
4200                         freeaddrinfo(cctx->aitop);
4201         }
4202         memset(cctx, 0, sizeof(*cctx));
4203 }
4204
4205 /*
4206  * Return connecting socket to remote host:port or local socket path,
4207  * passing back the failure reason if appropriate.
4208  */
4209 static int
4210 connect_to_helper(struct ssh *ssh, const char *name, int port, int socktype,
4211     char *ctype, char *rname, struct channel_connect *cctx,
4212     int *reason, const char **errmsg)
4213 {
4214         struct addrinfo hints;
4215         int gaierr;
4216         int sock = -1;
4217         char strport[NI_MAXSERV];
4218
4219         if (port == PORT_STREAMLOCAL) {
4220                 struct sockaddr_un *sunaddr;
4221                 struct addrinfo *ai;
4222
4223                 if (strlen(name) > sizeof(sunaddr->sun_path)) {
4224                         error("%.100s: %.100s", name, strerror(ENAMETOOLONG));
4225                         return -1;
4226                 }
4227
4228                 /*
4229                  * Fake up a struct addrinfo for AF_UNIX connections.
4230                  * channel_connect_ctx_free() must check ai_family
4231                  * and use free() not freeaddirinfo() for AF_UNIX.
4232                  */
4233                 ai = xmalloc(sizeof(*ai) + sizeof(*sunaddr));
4234                 memset(ai, 0, sizeof(*ai) + sizeof(*sunaddr));
4235                 ai->ai_addr = (struct sockaddr *)(ai + 1);
4236                 ai->ai_addrlen = sizeof(*sunaddr);
4237                 ai->ai_family = AF_UNIX;
4238                 ai->ai_socktype = socktype;
4239                 ai->ai_protocol = PF_UNSPEC;
4240                 sunaddr = (struct sockaddr_un *)ai->ai_addr;
4241                 sunaddr->sun_family = AF_UNIX;
4242                 strlcpy(sunaddr->sun_path, name, sizeof(sunaddr->sun_path));
4243                 cctx->aitop = ai;
4244         } else {
4245                 memset(&hints, 0, sizeof(hints));
4246                 hints.ai_family = ssh->chanctxt->IPv4or6;
4247                 hints.ai_socktype = socktype;
4248                 snprintf(strport, sizeof strport, "%d", port);
4249                 if ((gaierr = getaddrinfo(name, strport, &hints, &cctx->aitop))
4250                     != 0) {
4251                         if (errmsg != NULL)
4252                                 *errmsg = ssh_gai_strerror(gaierr);
4253                         if (reason != NULL)
4254                                 *reason = SSH2_OPEN_CONNECT_FAILED;
4255                         error("connect_to %.100s: unknown host (%s)", name,
4256                             ssh_gai_strerror(gaierr));
4257                         return -1;
4258                 }
4259         }
4260
4261         cctx->host = xstrdup(name);
4262         cctx->port = port;
4263         cctx->ai = cctx->aitop;
4264
4265         if ((sock = connect_next(cctx)) == -1) {
4266                 error("connect to %.100s port %d failed: %s",
4267                     name, port, strerror(errno));
4268                 return -1;
4269         }
4270
4271         return sock;
4272 }
4273
4274 /* Return CONNECTING channel to remote host:port or local socket path */
4275 static Channel *
4276 connect_to(struct ssh *ssh, const char *host, int port,
4277     char *ctype, char *rname)
4278 {
4279         struct channel_connect cctx;
4280         Channel *c;
4281         int sock;
4282
4283         memset(&cctx, 0, sizeof(cctx));
4284         sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4285             &cctx, NULL, NULL);
4286         if (sock == -1) {
4287                 channel_connect_ctx_free(&cctx);
4288                 return NULL;
4289         }
4290         c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4291             CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4292         c->host_port = port;
4293         c->path = xstrdup(host);
4294         c->connect_ctx = cctx;
4295
4296         return c;
4297 }
4298
4299 /*
4300  * returns either the newly connected channel or the downstream channel
4301  * that needs to deal with this connection.
4302  */
4303 Channel *
4304 channel_connect_by_listen_address(struct ssh *ssh, const char *listen_host,
4305     u_short listen_port, char *ctype, char *rname)
4306 {
4307         struct ssh_channels *sc = ssh->chanctxt;
4308         struct permission_set *pset = &sc->local_perms;
4309         u_int i;
4310         struct permission *perm;
4311
4312         for (i = 0; i < pset->num_permitted_user; i++) {
4313                 perm = &pset->permitted_user[i];
4314                 if (open_listen_match_tcpip(perm,
4315                     listen_host, listen_port, 1)) {
4316                         if (perm->downstream)
4317                                 return perm->downstream;
4318                         if (perm->port_to_connect == 0)
4319                                 return rdynamic_connect_prepare(ssh,
4320                                     ctype, rname);
4321                         return connect_to(ssh,
4322                             perm->host_to_connect, perm->port_to_connect,
4323                             ctype, rname);
4324                 }
4325         }
4326         error("WARNING: Server requests forwarding for unknown listen_port %d",
4327             listen_port);
4328         return NULL;
4329 }
4330
4331 Channel *
4332 channel_connect_by_listen_path(struct ssh *ssh, const char *path,
4333     char *ctype, char *rname)
4334 {
4335         struct ssh_channels *sc = ssh->chanctxt;
4336         struct permission_set *pset = &sc->local_perms;
4337         u_int i;
4338         struct permission *perm;
4339
4340         for (i = 0; i < pset->num_permitted_user; i++) {
4341                 perm = &pset->permitted_user[i];
4342                 if (open_listen_match_streamlocal(perm, path)) {
4343                         return connect_to(ssh,
4344                             perm->host_to_connect, perm->port_to_connect,
4345                             ctype, rname);
4346                 }
4347         }
4348         error("WARNING: Server requests forwarding for unknown path %.100s",
4349             path);
4350         return NULL;
4351 }
4352
4353 /* Check if connecting to that port is permitted and connect. */
4354 Channel *
4355 channel_connect_to_port(struct ssh *ssh, const char *host, u_short port,
4356     char *ctype, char *rname, int *reason, const char **errmsg)
4357 {
4358         struct ssh_channels *sc = ssh->chanctxt;
4359         struct permission_set *pset = &sc->local_perms;
4360         struct channel_connect cctx;
4361         Channel *c;
4362         u_int i, permit, permit_adm = 1;
4363         int sock;
4364         struct permission *perm;
4365
4366         permit = pset->all_permitted;
4367         if (!permit) {
4368                 for (i = 0; i < pset->num_permitted_user; i++) {
4369                         perm = &pset->permitted_user[i];
4370                         if (open_match(perm, host, port)) {
4371                                 permit = 1;
4372                                 break;
4373                         }
4374                 }
4375         }
4376
4377         if (pset->num_permitted_admin > 0) {
4378                 permit_adm = 0;
4379                 for (i = 0; i < pset->num_permitted_admin; i++) {
4380                         perm = &pset->permitted_admin[i];
4381                         if (open_match(perm, host, port)) {
4382                                 permit_adm = 1;
4383                                 break;
4384                         }
4385                 }
4386         }
4387
4388         if (!permit || !permit_adm) {
4389                 logit("Received request from %.100s port %d to connect to "
4390                     "host %.100s port %d, but the request was denied.",
4391                     ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), host, port);
4392                 if (reason != NULL)
4393                         *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
4394                 return NULL;
4395         }
4396
4397         memset(&cctx, 0, sizeof(cctx));
4398         sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4399             &cctx, reason, errmsg);
4400         if (sock == -1) {
4401                 channel_connect_ctx_free(&cctx);
4402                 return NULL;
4403         }
4404
4405         c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4406             CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4407         c->host_port = port;
4408         c->path = xstrdup(host);
4409         c->connect_ctx = cctx;
4410
4411         return c;
4412 }
4413
4414 /* Check if connecting to that path is permitted and connect. */
4415 Channel *
4416 channel_connect_to_path(struct ssh *ssh, const char *path,
4417     char *ctype, char *rname)
4418 {
4419         struct ssh_channels *sc = ssh->chanctxt;
4420         struct permission_set *pset = &sc->local_perms;
4421         u_int i, permit, permit_adm = 1;
4422         struct permission *perm;
4423
4424         permit = pset->all_permitted;
4425         if (!permit) {
4426                 for (i = 0; i < pset->num_permitted_user; i++) {
4427                         perm = &pset->permitted_user[i];
4428                         if (open_match(perm, path, PORT_STREAMLOCAL)) {
4429                                 permit = 1;
4430                                 break;
4431                         }
4432                 }
4433         }
4434
4435         if (pset->num_permitted_admin > 0) {
4436                 permit_adm = 0;
4437                 for (i = 0; i < pset->num_permitted_admin; i++) {
4438                         perm = &pset->permitted_admin[i];
4439                         if (open_match(perm, path, PORT_STREAMLOCAL)) {
4440                                 permit_adm = 1;
4441                                 break;
4442                         }
4443                 }
4444         }
4445
4446         if (!permit || !permit_adm) {
4447                 logit("Received request to connect to path %.100s, "
4448                     "but the request was denied.", path);
4449                 return NULL;
4450         }
4451         return connect_to(ssh, path, PORT_STREAMLOCAL, ctype, rname);
4452 }
4453
4454 void
4455 channel_send_window_changes(struct ssh *ssh)
4456 {
4457         struct ssh_channels *sc = ssh->chanctxt;
4458         struct winsize ws;
4459         int r;
4460         u_int i;
4461
4462         for (i = 0; i < sc->channels_alloc; i++) {
4463                 if (sc->channels[i] == NULL || !sc->channels[i]->client_tty ||
4464                     sc->channels[i]->type != SSH_CHANNEL_OPEN)
4465                         continue;
4466                 if (ioctl(sc->channels[i]->rfd, TIOCGWINSZ, &ws) == -1)
4467                         continue;
4468                 channel_request_start(ssh, i, "window-change", 0);
4469                 if ((r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
4470                     (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
4471                     (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
4472                     (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0 ||
4473                     (r = sshpkt_send(ssh)) != 0)
4474                         fatal_fr(r, "channel %u; send window-change", i);
4475         }
4476 }
4477
4478 /* Return RDYNAMIC_OPEN channel: channel allows SOCKS, but is not connected */
4479 static Channel *
4480 rdynamic_connect_prepare(struct ssh *ssh, char *ctype, char *rname)
4481 {
4482         Channel *c;
4483         int r;
4484
4485         c = channel_new(ssh, ctype, SSH_CHANNEL_RDYNAMIC_OPEN, -1, -1, -1,
4486             CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4487         c->host_port = 0;
4488         c->path = NULL;
4489
4490         /*
4491          * We need to open the channel before we have a FD,
4492          * so that we can get SOCKS header from peer.
4493          */
4494         if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
4495             (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
4496             (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
4497             (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
4498             (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0)
4499                 fatal_fr(r, "channel %i; confirm", c->self);
4500         return c;
4501 }
4502
4503 /* Return CONNECTING socket to remote host:port or local socket path */
4504 static int
4505 rdynamic_connect_finish(struct ssh *ssh, Channel *c)
4506 {
4507         struct ssh_channels *sc = ssh->chanctxt;
4508         struct permission_set *pset = &sc->local_perms;
4509         struct permission *perm;
4510         struct channel_connect cctx;
4511         u_int i, permit_adm = 1;
4512         int sock;
4513
4514         if (pset->num_permitted_admin > 0) {
4515                 permit_adm = 0;
4516                 for (i = 0; i < pset->num_permitted_admin; i++) {
4517                         perm = &pset->permitted_admin[i];
4518                         if (open_match(perm, c->path, c->host_port)) {
4519                                 permit_adm = 1;
4520                                 break;
4521                         }
4522                 }
4523         }
4524         if (!permit_adm) {
4525                 debug_f("requested forward not permitted");
4526                 return -1;
4527         }
4528
4529         memset(&cctx, 0, sizeof(cctx));
4530         sock = connect_to_helper(ssh, c->path, c->host_port, SOCK_STREAM, NULL,
4531             NULL, &cctx, NULL, NULL);
4532         if (sock == -1)
4533                 channel_connect_ctx_free(&cctx);
4534         else {
4535                 /* similar to SSH_CHANNEL_CONNECTING but we've already sent the open */
4536                 c->type = SSH_CHANNEL_RDYNAMIC_FINISH;
4537                 c->connect_ctx = cctx;
4538                 channel_register_fds(ssh, c, sock, sock, -1, 0, 1, 0);
4539         }
4540         return sock;
4541 }
4542
4543 /* -- X11 forwarding */
4544
4545 /*
4546  * Creates an internet domain socket for listening for X11 connections.
4547  * Returns 0 and a suitable display number for the DISPLAY variable
4548  * stored in display_numberp , or -1 if an error occurs.
4549  */
4550 int
4551 x11_create_display_inet(struct ssh *ssh, int x11_display_offset,
4552     int x11_use_localhost, int single_connection,
4553     u_int *display_numberp, int **chanids)
4554 {
4555         Channel *nc = NULL;
4556         int display_number, sock;
4557         u_short port;
4558         struct addrinfo hints, *ai, *aitop;
4559         char strport[NI_MAXSERV];
4560         int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
4561
4562         if (chanids == NULL)
4563                 return -1;
4564
4565         for (display_number = x11_display_offset;
4566             display_number < MAX_DISPLAYS;
4567             display_number++) {
4568                 port = 6000 + display_number;
4569                 memset(&hints, 0, sizeof(hints));
4570                 hints.ai_family = ssh->chanctxt->IPv4or6;
4571                 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
4572                 hints.ai_socktype = SOCK_STREAM;
4573                 snprintf(strport, sizeof strport, "%d", port);
4574                 if ((gaierr = getaddrinfo(NULL, strport,
4575                     &hints, &aitop)) != 0) {
4576                         error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
4577                         return -1;
4578                 }
4579                 for (ai = aitop; ai; ai = ai->ai_next) {
4580                         if (ai->ai_family != AF_INET &&
4581                             ai->ai_family != AF_INET6)
4582                                 continue;
4583                         sock = socket(ai->ai_family, ai->ai_socktype,
4584                             ai->ai_protocol);
4585                         if (sock == -1) {
4586                                 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)
4587 #ifdef EPFNOSUPPORT
4588                                     && (errno != EPFNOSUPPORT)
4589 #endif 
4590                                     ) {
4591                                         error("socket: %.100s", strerror(errno));
4592                                         freeaddrinfo(aitop);
4593                                         return -1;
4594                                 } else {
4595                                         debug("x11_create_display_inet: Socket family %d not supported",
4596                                                  ai->ai_family);
4597                                         continue;
4598                                 }
4599                         }
4600                         if (ai->ai_family == AF_INET6)
4601                                 sock_set_v6only(sock);
4602                         if (x11_use_localhost)
4603                                 set_reuseaddr(sock);
4604                         if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
4605                                 debug2_f("bind port %d: %.100s", port,
4606                                     strerror(errno));
4607                                 close(sock);
4608                                 for (n = 0; n < num_socks; n++)
4609                                         close(socks[n]);
4610                                 num_socks = 0;
4611                                 break;
4612                         }
4613                         socks[num_socks++] = sock;
4614                         if (num_socks == NUM_SOCKS)
4615                                 break;
4616                 }
4617                 freeaddrinfo(aitop);
4618                 if (num_socks > 0)
4619                         break;
4620         }
4621         if (display_number >= MAX_DISPLAYS) {
4622                 error("Failed to allocate internet-domain X11 display socket.");
4623                 return -1;
4624         }
4625         /* Start listening for connections on the socket. */
4626         for (n = 0; n < num_socks; n++) {
4627                 sock = socks[n];
4628                 if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
4629                         error("listen: %.100s", strerror(errno));
4630                         close(sock);
4631                         return -1;
4632                 }
4633         }
4634
4635         /* Allocate a channel for each socket. */
4636         *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
4637         for (n = 0; n < num_socks; n++) {
4638                 sock = socks[n];
4639                 nc = channel_new(ssh, "x11 listener",
4640                     SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
4641                     CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
4642                     0, "X11 inet listener", 1);
4643                 nc->single_connection = single_connection;
4644                 (*chanids)[n] = nc->self;
4645         }
4646         (*chanids)[n] = -1;
4647
4648         /* Return the display number for the DISPLAY environment variable. */
4649         *display_numberp = display_number;
4650         return 0;
4651 }
4652
4653 static int
4654 connect_local_xsocket_path(const char *pathname)
4655 {
4656         int sock;
4657         struct sockaddr_un addr;
4658
4659         sock = socket(AF_UNIX, SOCK_STREAM, 0);
4660         if (sock == -1)
4661                 error("socket: %.100s", strerror(errno));
4662         memset(&addr, 0, sizeof(addr));
4663         addr.sun_family = AF_UNIX;
4664         strlcpy(addr.sun_path, pathname, sizeof addr.sun_path);
4665         if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
4666                 return sock;
4667         close(sock);
4668         error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
4669         return -1;
4670 }
4671
4672 static int
4673 connect_local_xsocket(u_int dnr)
4674 {
4675         char buf[1024];
4676         snprintf(buf, sizeof buf, _PATH_UNIX_X, dnr);
4677         return connect_local_xsocket_path(buf);
4678 }
4679
4680 #ifdef __APPLE__
4681 static int
4682 is_path_to_xsocket(const char *display, char *path, size_t pathlen)
4683 {
4684         struct stat sbuf;
4685
4686         if (strlcpy(path, display, pathlen) >= pathlen) {
4687                 error("%s: display path too long", __func__);
4688                 return 0;
4689         }
4690         if (display[0] != '/')
4691                 return 0;
4692         if (stat(path, &sbuf) == 0) {
4693                 return 1;
4694         } else {
4695                 char *dot = strrchr(path, '.');
4696                 if (dot != NULL) {
4697                         *dot = '\0';
4698                         if (stat(path, &sbuf) == 0) {
4699                                 return 1;
4700                         }
4701                 }
4702         }
4703         return 0;
4704 }
4705 #endif
4706
4707 int
4708 x11_connect_display(struct ssh *ssh)
4709 {
4710         u_int display_number;
4711         const char *display;
4712         char buf[1024], *cp;
4713         struct addrinfo hints, *ai, *aitop;
4714         char strport[NI_MAXSERV];
4715         int gaierr, sock = 0;
4716
4717         /* Try to open a socket for the local X server. */
4718         display = getenv("DISPLAY");
4719         if (!display) {
4720                 error("DISPLAY not set.");
4721                 return -1;
4722         }
4723         /*
4724          * Now we decode the value of the DISPLAY variable and make a
4725          * connection to the real X server.
4726          */
4727
4728 #ifdef __APPLE__
4729         /* Check if display is a path to a socket (as set by launchd). */
4730         {
4731                 char path[PATH_MAX];
4732
4733                 if (is_path_to_xsocket(display, path, sizeof(path))) {
4734                         debug("x11_connect_display: $DISPLAY is launchd");
4735
4736                         /* Create a socket. */
4737                         sock = connect_local_xsocket_path(path);
4738                         if (sock < 0)
4739                                 return -1;
4740
4741                         /* OK, we now have a connection to the display. */
4742                         return sock;
4743                 }
4744         }
4745 #endif
4746         /*
4747          * Check if it is a unix domain socket.  Unix domain displays are in
4748          * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
4749          */
4750         if (strncmp(display, "unix:", 5) == 0 ||
4751             display[0] == ':') {
4752                 /* Connect to the unix domain socket. */
4753                 if (sscanf(strrchr(display, ':') + 1, "%u",
4754                     &display_number) != 1) {
4755                         error("Could not parse display number from DISPLAY: "
4756                             "%.100s", display);
4757                         return -1;
4758                 }
4759                 /* Create a socket. */
4760                 sock = connect_local_xsocket(display_number);
4761                 if (sock < 0)
4762                         return -1;
4763
4764                 /* OK, we now have a connection to the display. */
4765                 return sock;
4766         }
4767         /*
4768          * Connect to an inet socket.  The DISPLAY value is supposedly
4769          * hostname:d[.s], where hostname may also be numeric IP address.
4770          */
4771         strlcpy(buf, display, sizeof(buf));
4772         cp = strchr(buf, ':');
4773         if (!cp) {
4774                 error("Could not find ':' in DISPLAY: %.100s", display);
4775                 return -1;
4776         }
4777         *cp = 0;
4778         /*
4779          * buf now contains the host name.  But first we parse the
4780          * display number.
4781          */
4782         if (sscanf(cp + 1, "%u", &display_number) != 1) {
4783                 error("Could not parse display number from DISPLAY: %.100s",
4784                     display);
4785                 return -1;
4786         }
4787
4788         /* Look up the host address */
4789         memset(&hints, 0, sizeof(hints));
4790         hints.ai_family = ssh->chanctxt->IPv4or6;
4791         hints.ai_socktype = SOCK_STREAM;
4792         snprintf(strport, sizeof strport, "%u", 6000 + display_number);
4793         if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
4794                 error("%.100s: unknown host. (%s)", buf,
4795                 ssh_gai_strerror(gaierr));
4796                 return -1;
4797         }
4798         for (ai = aitop; ai; ai = ai->ai_next) {
4799                 /* Create a socket. */
4800                 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
4801                 if (sock == -1) {
4802                         debug2("socket: %.100s", strerror(errno));
4803                         continue;
4804                 }
4805                 /* Connect it to the display. */
4806                 if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
4807                         debug2("connect %.100s port %u: %.100s", buf,
4808                             6000 + display_number, strerror(errno));
4809                         close(sock);
4810                         continue;
4811                 }
4812                 /* Success */
4813                 break;
4814         }
4815         freeaddrinfo(aitop);
4816         if (!ai) {
4817                 error("connect %.100s port %u: %.100s", buf,
4818                     6000 + display_number, strerror(errno));
4819                 return -1;
4820         }
4821         set_nodelay(sock);
4822         return sock;
4823 }
4824
4825 /*
4826  * Requests forwarding of X11 connections, generates fake authentication
4827  * data, and enables authentication spoofing.
4828  * This should be called in the client only.
4829  */
4830 void
4831 x11_request_forwarding_with_spoofing(struct ssh *ssh, int client_session_id,
4832     const char *disp, const char *proto, const char *data, int want_reply)
4833 {
4834         struct ssh_channels *sc = ssh->chanctxt;
4835         u_int data_len = (u_int) strlen(data) / 2;
4836         u_int i, value;
4837         const char *cp;
4838         char *new_data;
4839         int r, screen_number;
4840
4841         if (sc->x11_saved_display == NULL)
4842                 sc->x11_saved_display = xstrdup(disp);
4843         else if (strcmp(disp, sc->x11_saved_display) != 0) {
4844                 error("x11_request_forwarding_with_spoofing: different "
4845                     "$DISPLAY already forwarded");
4846                 return;
4847         }
4848
4849         cp = strchr(disp, ':');
4850         if (cp)
4851                 cp = strchr(cp, '.');
4852         if (cp)
4853                 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
4854         else
4855                 screen_number = 0;
4856
4857         if (sc->x11_saved_proto == NULL) {
4858                 /* Save protocol name. */
4859                 sc->x11_saved_proto = xstrdup(proto);
4860
4861                 /* Extract real authentication data. */
4862                 sc->x11_saved_data = xmalloc(data_len);
4863                 for (i = 0; i < data_len; i++) {
4864                         if (sscanf(data + 2 * i, "%2x", &value) != 1) {
4865                                 fatal("x11_request_forwarding: bad "
4866                                     "authentication data: %.100s", data);
4867                         }
4868                         sc->x11_saved_data[i] = value;
4869                 }
4870                 sc->x11_saved_data_len = data_len;
4871
4872                 /* Generate fake data of the same length. */
4873                 sc->x11_fake_data = xmalloc(data_len);
4874                 arc4random_buf(sc->x11_fake_data, data_len);
4875                 sc->x11_fake_data_len = data_len;
4876         }
4877
4878         /* Convert the fake data into hex. */
4879         new_data = tohex(sc->x11_fake_data, data_len);
4880
4881         /* Send the request packet. */
4882         channel_request_start(ssh, client_session_id, "x11-req", want_reply);
4883         if ((r = sshpkt_put_u8(ssh, 0)) != 0 || /* bool: single connection */
4884             (r = sshpkt_put_cstring(ssh, proto)) != 0 ||
4885             (r = sshpkt_put_cstring(ssh, new_data)) != 0 ||
4886             (r = sshpkt_put_u32(ssh, screen_number)) != 0 ||
4887             (r = sshpkt_send(ssh)) != 0 ||
4888             (r = ssh_packet_write_wait(ssh)) != 0)
4889                 fatal_fr(r, "send x11-req");
4890         free(new_data);
4891 }