[BACK]Return to channels.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/channels.c, Revision 1.411

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