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