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

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