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