[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.417

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