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

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