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

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