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

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