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

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