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

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