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

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