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

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