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

1.1       deraadt     1: /*
1.26      deraadt     2:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      3:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      4:  *                    All rights reserved
                      5:  * This file contains functions for generic socket connection forwarding.
                      6:  * There is also code for initiating connection forwarding for X11 connections,
                      7:  * arbitrary tcp/ip connections, and the authentication agent connection.
1.49      markus      8:  *
1.67      deraadt     9:  * As far as I am concerned, the code I have written for this software
                     10:  * can be used freely for any purpose.  Any derived versions of this
                     11:  * software must be clearly marked as such, and if the derived work is
                     12:  * incompatible with the protocol description in the RFC file, it must be
                     13:  * called by a name other than "ssh" or "Secure Shell".
                     14:  *
1.44      markus     15:  * SSH2 support added by Markus Friedl.
1.156     markus     16:  * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl.  All rights reserved.
1.67      deraadt    17:  * Copyright (c) 1999 Dug Song.  All rights reserved.
                     18:  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
                     19:  *
                     20:  * Redistribution and use in source and binary forms, with or without
                     21:  * modification, are permitted provided that the following conditions
                     22:  * are met:
                     23:  * 1. Redistributions of source code must retain the above copyright
                     24:  *    notice, this list of conditions and the following disclaimer.
                     25:  * 2. Redistributions in binary form must reproduce the above copyright
                     26:  *    notice, this list of conditions and the following disclaimer in the
                     27:  *    documentation and/or other materials provided with the distribution.
                     28:  *
                     29:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     30:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     31:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     32:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     33:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     34:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     35:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     36:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     37:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     38:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.26      deraadt    39:  */
1.1       deraadt    40:
                     41: #include "includes.h"
1.235   ! stevesk    42: RCSID("$OpenBSD: channels.c,v 1.234 2006/02/10 00:27:13 stevesk Exp $");
1.234     stevesk    43:
                     44: #include <sys/ioctl.h>
1.235   ! stevesk    45: #include <sys/types.h>
        !            46: #include <sys/un.h>
1.233     stevesk    47:
                     48: #include <termios.h>
1.1       deraadt    49:
                     50: #include "ssh.h"
1.82      markus     51: #include "ssh1.h"
                     52: #include "ssh2.h"
1.1       deraadt    53: #include "packet.h"
                     54: #include "xmalloc.h"
1.82      markus     55: #include "log.h"
                     56: #include "misc.h"
1.14      markus     57: #include "channels.h"
                     58: #include "compat.h"
1.82      markus     59: #include "canohost.h"
1.64      markus     60: #include "key.h"
                     61: #include "authfd.h"
1.147     stevesk    62: #include "pathnames.h"
1.193     markus     63: #include "bufaux.h"
1.1       deraadt    64:
1.121     markus     65: /* -- channel core */
1.12      markus     66:
1.27      markus     67: /*
                     68:  * Pointer to an array containing all allocated channels.  The array is
                     69:  * dynamically extended as needed.
                     70:  */
1.113     markus     71: static Channel **channels = NULL;
1.1       deraadt    72:
1.27      markus     73: /*
                     74:  * Size of the channel array.  All slots of the array must always be
1.113     markus     75:  * initialized (at least the type field); unused slots set to NULL
1.27      markus     76:  */
1.209     avsm       77: static u_int channels_alloc = 0;
1.1       deraadt    78:
1.27      markus     79: /*
                     80:  * Maximum file descriptor value used in any of the channels.  This is
1.113     markus     81:  * updated in channel_new.
1.27      markus     82:  */
1.84      markus     83: static int channel_max_fd = 0;
1.1       deraadt    84:
                     85:
1.121     markus     86: /* -- tcp forwarding */
1.1       deraadt    87:
1.27      markus     88: /*
                     89:  * Data structure for storing which hosts are permitted for forward requests.
                     90:  * The local sides of any remote forwards are stored in this array to prevent
                     91:  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
                     92:  * network (which might be behind a firewall).
                     93:  */
1.25      markus     94: typedef struct {
1.41      markus     95:        char *host_to_connect;          /* Connect to 'host'. */
                     96:        u_short port_to_connect;        /* Connect to 'port'. */
                     97:        u_short listen_port;            /* Remote side should listen port number. */
1.1       deraadt    98: } ForwardPermission;
                     99:
                    100: /* List of all permitted host/port pairs to connect. */
                    101: static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
1.121     markus    102:
1.1       deraadt   103: /* Number of permitted host/port pairs in the array. */
                    104: static int num_permitted_opens = 0;
1.27      markus    105: /*
                    106:  * If this is true, all opens are permitted.  This is the case on the server
                    107:  * on which we have to trust the client anyway, and the user could do
                    108:  * anything after logging in anyway.
                    109:  */
1.1       deraadt   110: static int all_opens_permitted = 0;
                    111:
1.121     markus    112:
                    113: /* -- X11 forwarding */
                    114:
                    115: /* Maximum number of fake X11 displays to try. */
                    116: #define MAX_DISPLAYS  1000
                    117:
1.219     djm       118: /* Saved X11 local (client) display. */
                    119: static char *x11_saved_display = NULL;
                    120:
1.121     markus    121: /* Saved X11 authentication protocol name. */
                    122: static char *x11_saved_proto = NULL;
                    123:
                    124: /* Saved X11 authentication data.  This is the real data. */
                    125: static char *x11_saved_data = NULL;
                    126: static u_int x11_saved_data_len = 0;
                    127:
                    128: /*
                    129:  * Fake X11 authentication data.  This is what the server will be sending us;
                    130:  * we should replace any occurrences of this by the real data.
                    131:  */
                    132: static char *x11_fake_data = NULL;
                    133: static u_int x11_fake_data_len;
                    134:
                    135:
                    136: /* -- agent forwarding */
                    137:
                    138: #define        NUM_SOCKS       10
                    139:
1.82      markus    140: /* AF_UNSPEC or AF_INET or AF_INET6 */
1.135     markus    141: static int IPv4or6 = AF_UNSPEC;
1.1       deraadt   142:
1.121     markus    143: /* helper */
1.127     itojun    144: static void port_open_helper(Channel *c, char *rtype);
1.103     markus    145:
1.121     markus    146: /* -- channel core */
1.41      markus    147:
                    148: Channel *
1.229     markus    149: channel_by_id(int id)
1.41      markus    150: {
                    151:        Channel *c;
1.113     markus    152:
1.209     avsm      153:        if (id < 0 || (u_int)id >= channels_alloc) {
1.229     markus    154:                logit("channel_by_id: %d: bad id", id);
1.41      markus    155:                return NULL;
                    156:        }
1.113     markus    157:        c = channels[id];
                    158:        if (c == NULL) {
1.229     markus    159:                logit("channel_by_id: %d: bad id: channel free", id);
1.41      markus    160:                return NULL;
                    161:        }
                    162:        return c;
1.55      markus    163: }
                    164:
1.27      markus    165: /*
1.229     markus    166:  * Returns the channel if it is allowed to receive protocol messages.
                    167:  * Private channels, like listening sockets, may not receive messages.
                    168:  */
                    169: Channel *
                    170: channel_lookup(int id)
                    171: {
                    172:        Channel *c;
                    173:
                    174:        if ((c = channel_by_id(id)) == NULL)
                    175:                return (NULL);
                    176:
                    177:        switch(c->type) {
                    178:        case SSH_CHANNEL_X11_OPEN:
                    179:        case SSH_CHANNEL_LARVAL:
                    180:        case SSH_CHANNEL_CONNECTING:
                    181:        case SSH_CHANNEL_DYNAMIC:
                    182:        case SSH_CHANNEL_OPENING:
                    183:        case SSH_CHANNEL_OPEN:
                    184:        case SSH_CHANNEL_INPUT_DRAINING:
                    185:        case SSH_CHANNEL_OUTPUT_DRAINING:
                    186:                return (c);
                    187:                break;
                    188:        }
                    189:        logit("Non-public channel %d, type %d.", id, c->type);
                    190:        return (NULL);
                    191: }
                    192:
                    193: /*
1.55      markus    194:  * Register filedescriptors for a channel, used when allocating a channel or
1.52      markus    195:  * when the channel consumer/producer is ready, e.g. shell exec'd
1.27      markus    196:  */
1.1       deraadt   197:
1.127     itojun    198: static void
1.71      markus    199: channel_register_fds(Channel *c, int rfd, int wfd, int efd,
                    200:     int extusage, int nonblock)
1.1       deraadt   201: {
1.25      markus    202:        /* Update the maximum file descriptor value. */
1.84      markus    203:        channel_max_fd = MAX(channel_max_fd, rfd);
                    204:        channel_max_fd = MAX(channel_max_fd, wfd);
                    205:        channel_max_fd = MAX(channel_max_fd, efd);
                    206:
1.27      markus    207:        /* XXX set close-on-exec -markus */
1.55      markus    208:
1.52      markus    209:        c->rfd = rfd;
                    210:        c->wfd = wfd;
                    211:        c->sock = (rfd == wfd) ? rfd : -1;
1.204     djm       212:        c->ctl_fd = -1; /* XXX: set elsewhere */
1.52      markus    213:        c->efd = efd;
                    214:        c->extended_usage = extusage;
1.71      markus    215:
1.91      markus    216:        /* XXX ugly hack: nonblock is only set by the server */
                    217:        if (nonblock && isatty(c->rfd)) {
1.194     markus    218:                debug2("channel %d: rfd %d isatty", c->self, c->rfd);
1.91      markus    219:                c->isatty = 1;
                    220:                if (!isatty(c->wfd)) {
1.94      markus    221:                        error("channel %d: wfd %d is not a tty?",
1.91      markus    222:                            c->self, c->wfd);
                    223:                }
                    224:        } else {
                    225:                c->isatty = 0;
                    226:        }
                    227:
1.71      markus    228:        /* enable nonblocking mode */
                    229:        if (nonblock) {
                    230:                if (rfd != -1)
                    231:                        set_nonblock(rfd);
                    232:                if (wfd != -1)
                    233:                        set_nonblock(wfd);
                    234:                if (efd != -1)
                    235:                        set_nonblock(efd);
                    236:        }
1.52      markus    237: }
                    238:
                    239: /*
                    240:  * Allocate a new channel object and set its type and socket. This will cause
                    241:  * remote_name to be freed.
                    242:  */
                    243:
1.113     markus    244: Channel *
1.52      markus    245: channel_new(char *ctype, int type, int rfd, int wfd, int efd,
1.178     markus    246:     u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
1.52      markus    247: {
1.209     avsm      248:        int found;
                    249:        u_int i;
1.52      markus    250:        Channel *c;
1.25      markus    251:
                    252:        /* Do initial allocation if this is the first call. */
                    253:        if (channels_alloc == 0) {
                    254:                channels_alloc = 10;
1.113     markus    255:                channels = xmalloc(channels_alloc * sizeof(Channel *));
1.25      markus    256:                for (i = 0; i < channels_alloc; i++)
1.113     markus    257:                        channels[i] = NULL;
1.25      markus    258:        }
                    259:        /* Try to find a free slot where to put the new channel. */
                    260:        for (found = -1, i = 0; i < channels_alloc; i++)
1.113     markus    261:                if (channels[i] == NULL) {
1.25      markus    262:                        /* Found a free slot. */
1.209     avsm      263:                        found = (int)i;
1.25      markus    264:                        break;
                    265:                }
1.209     avsm      266:        if (found < 0) {
1.27      markus    267:                /* There are no free slots.  Take last+1 slot and expand the array.  */
1.25      markus    268:                found = channels_alloc;
1.179     markus    269:                if (channels_alloc > 10000)
                    270:                        fatal("channel_new: internal error: channels_alloc %d "
                    271:                            "too big.", channels_alloc);
1.195     markus    272:                channels = xrealloc(channels,
                    273:                    (channels_alloc + 10) * sizeof(Channel *));
                    274:                channels_alloc += 10;
1.70      markus    275:                debug2("channel: expanding %d", channels_alloc);
1.25      markus    276:                for (i = found; i < channels_alloc; i++)
1.113     markus    277:                        channels[i] = NULL;
1.25      markus    278:        }
1.113     markus    279:        /* Initialize and return new channel. */
                    280:        c = channels[found] = xmalloc(sizeof(Channel));
1.137     markus    281:        memset(c, 0, sizeof(Channel));
1.25      markus    282:        buffer_init(&c->input);
                    283:        buffer_init(&c->output);
1.41      markus    284:        buffer_init(&c->extended);
1.159     markus    285:        c->ostate = CHAN_OUTPUT_OPEN;
                    286:        c->istate = CHAN_INPUT_OPEN;
                    287:        c->flags = 0;
1.71      markus    288:        channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
1.25      markus    289:        c->self = found;
                    290:        c->type = type;
1.41      markus    291:        c->ctype = ctype;
1.51      markus    292:        c->local_window = window;
                    293:        c->local_window_max = window;
                    294:        c->local_consumed = 0;
                    295:        c->local_maxpacket = maxpack;
1.25      markus    296:        c->remote_id = -1;
1.190     markus    297:        c->remote_name = xstrdup(remote_name);
1.41      markus    298:        c->remote_window = 0;
                    299:        c->remote_maxpacket = 0;
1.133     markus    300:        c->force_drain = 0;
1.149     markus    301:        c->single_connection = 0;
1.131     markus    302:        c->detach_user = NULL;
1.225     djm       303:        c->detach_close = 0;
1.165     markus    304:        c->confirm = NULL;
1.204     djm       305:        c->confirm_ctx = NULL;
1.65      markus    306:        c->input_filter = NULL;
1.231     reyk      307:        c->output_filter = NULL;
1.25      markus    308:        debug("channel %d: new [%s]", found, remote_name);
1.113     markus    309:        return c;
1.1       deraadt   310: }
1.52      markus    311:
1.132     markus    312: static int
                    313: channel_find_maxfd(void)
                    314: {
1.209     avsm      315:        u_int i;
                    316:        int max = 0;
1.132     markus    317:        Channel *c;
                    318:
                    319:        for (i = 0; i < channels_alloc; i++) {
                    320:                c = channels[i];
                    321:                if (c != NULL) {
                    322:                        max = MAX(max, c->rfd);
                    323:                        max = MAX(max, c->wfd);
                    324:                        max = MAX(max, c->efd);
                    325:                }
                    326:        }
                    327:        return max;
                    328: }
                    329:
                    330: int
                    331: channel_close_fd(int *fdp)
                    332: {
                    333:        int ret = 0, fd = *fdp;
                    334:
                    335:        if (fd != -1) {
                    336:                ret = close(fd);
                    337:                *fdp = -1;
                    338:                if (fd == channel_max_fd)
                    339:                        channel_max_fd = channel_find_maxfd();
                    340:        }
                    341:        return ret;
                    342: }
                    343:
1.52      markus    344: /* Close all channel fd/socket. */
                    345:
1.127     itojun    346: static void
1.52      markus    347: channel_close_fds(Channel *c)
                    348: {
1.204     djm       349:        debug3("channel %d: close_fds r %d w %d e %d c %d",
                    350:            c->self, c->rfd, c->wfd, c->efd, c->ctl_fd);
1.118     markus    351:
1.132     markus    352:        channel_close_fd(&c->sock);
1.204     djm       353:        channel_close_fd(&c->ctl_fd);
1.132     markus    354:        channel_close_fd(&c->rfd);
                    355:        channel_close_fd(&c->wfd);
                    356:        channel_close_fd(&c->efd);
1.121     markus    357: }
                    358:
                    359: /* Free the channel and close its fd/socket. */
                    360:
                    361: void
                    362: channel_free(Channel *c)
                    363: {
                    364:        char *s;
1.209     avsm      365:        u_int i, n;
1.121     markus    366:
                    367:        for (n = 0, i = 0; i < channels_alloc; i++)
                    368:                if (channels[i])
                    369:                        n++;
1.209     avsm      370:        debug("channel %d: free: %s, nchannels %u", c->self,
1.121     markus    371:            c->remote_name ? c->remote_name : "???", n);
                    372:
                    373:        s = channel_open_message();
1.194     markus    374:        debug3("channel %d: status: %s", c->self, s);
1.121     markus    375:        xfree(s);
                    376:
                    377:        if (c->sock != -1)
                    378:                shutdown(c->sock, SHUT_RDWR);
1.204     djm       379:        if (c->ctl_fd != -1)
                    380:                shutdown(c->ctl_fd, SHUT_RDWR);
1.121     markus    381:        channel_close_fds(c);
                    382:        buffer_free(&c->input);
                    383:        buffer_free(&c->output);
                    384:        buffer_free(&c->extended);
                    385:        if (c->remote_name) {
                    386:                xfree(c->remote_name);
                    387:                c->remote_name = NULL;
                    388:        }
                    389:        channels[c->self] = NULL;
                    390:        xfree(c);
                    391: }
                    392:
                    393: void
1.126     markus    394: channel_free_all(void)
1.121     markus    395: {
1.209     avsm      396:        u_int i;
1.121     markus    397:
1.126     markus    398:        for (i = 0; i < channels_alloc; i++)
                    399:                if (channels[i] != NULL)
                    400:                        channel_free(channels[i]);
1.131     markus    401: }
                    402:
1.121     markus    403: /*
                    404:  * Closes the sockets/fds of all channels.  This is used to close extra file
                    405:  * descriptors after a fork.
                    406:  */
                    407:
                    408: void
1.142     itojun    409: channel_close_all(void)
1.121     markus    410: {
1.209     avsm      411:        u_int i;
1.121     markus    412:
                    413:        for (i = 0; i < channels_alloc; i++)
                    414:                if (channels[i] != NULL)
                    415:                        channel_close_fds(channels[i]);
                    416: }
                    417:
                    418: /*
1.131     markus    419:  * Stop listening to channels.
                    420:  */
                    421:
                    422: void
                    423: channel_stop_listening(void)
                    424: {
1.209     avsm      425:        u_int i;
1.131     markus    426:        Channel *c;
                    427:
                    428:        for (i = 0; i < channels_alloc; i++) {
                    429:                c = channels[i];
                    430:                if (c != NULL) {
                    431:                        switch (c->type) {
                    432:                        case SSH_CHANNEL_AUTH_SOCKET:
                    433:                        case SSH_CHANNEL_PORT_LISTENER:
                    434:                        case SSH_CHANNEL_RPORT_LISTENER:
                    435:                        case SSH_CHANNEL_X11_LISTENER:
1.132     markus    436:                                channel_close_fd(&c->sock);
1.131     markus    437:                                channel_free(c);
                    438:                                break;
                    439:                        }
                    440:                }
                    441:        }
                    442: }
                    443:
                    444: /*
1.121     markus    445:  * Returns true if no channel has too much buffered data, and false if one or
                    446:  * more channel is overfull.
                    447:  */
                    448:
                    449: int
1.142     itojun    450: channel_not_very_much_buffered_data(void)
1.121     markus    451: {
                    452:        u_int i;
                    453:        Channel *c;
                    454:
                    455:        for (i = 0; i < channels_alloc; i++) {
                    456:                c = channels[i];
                    457:                if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
1.136     markus    458: #if 0
                    459:                        if (!compat20 &&
                    460:                            buffer_len(&c->input) > packet_get_maxsize()) {
1.185     markus    461:                                debug2("channel %d: big input buffer %d",
1.121     markus    462:                                    c->self, buffer_len(&c->input));
                    463:                                return 0;
                    464:                        }
1.136     markus    465: #endif
1.121     markus    466:                        if (buffer_len(&c->output) > packet_get_maxsize()) {
1.191     markus    467:                                debug2("channel %d: big output buffer %u > %u",
1.136     markus    468:                                    c->self, buffer_len(&c->output),
                    469:                                    packet_get_maxsize());
1.121     markus    470:                                return 0;
                    471:                        }
                    472:                }
                    473:        }
                    474:        return 1;
                    475: }
                    476:
                    477: /* Returns true if any channel is still open. */
                    478:
                    479: int
1.142     itojun    480: channel_still_open(void)
1.121     markus    481: {
1.209     avsm      482:        u_int i;
1.121     markus    483:        Channel *c;
                    484:
                    485:        for (i = 0; i < channels_alloc; i++) {
                    486:                c = channels[i];
                    487:                if (c == NULL)
                    488:                        continue;
                    489:                switch (c->type) {
                    490:                case SSH_CHANNEL_X11_LISTENER:
                    491:                case SSH_CHANNEL_PORT_LISTENER:
                    492:                case SSH_CHANNEL_RPORT_LISTENER:
                    493:                case SSH_CHANNEL_CLOSED:
                    494:                case SSH_CHANNEL_AUTH_SOCKET:
                    495:                case SSH_CHANNEL_DYNAMIC:
                    496:                case SSH_CHANNEL_CONNECTING:
                    497:                case SSH_CHANNEL_ZOMBIE:
                    498:                        continue;
                    499:                case SSH_CHANNEL_LARVAL:
                    500:                        if (!compat20)
                    501:                                fatal("cannot happen: SSH_CHANNEL_LARVAL");
                    502:                        continue;
                    503:                case SSH_CHANNEL_OPENING:
                    504:                case SSH_CHANNEL_OPEN:
                    505:                case SSH_CHANNEL_X11_OPEN:
                    506:                        return 1;
                    507:                case SSH_CHANNEL_INPUT_DRAINING:
                    508:                case SSH_CHANNEL_OUTPUT_DRAINING:
                    509:                        if (!compat13)
                    510:                                fatal("cannot happen: OUT_DRAIN");
                    511:                        return 1;
                    512:                default:
                    513:                        fatal("channel_still_open: bad channel type %d", c->type);
                    514:                        /* NOTREACHED */
                    515:                }
                    516:        }
                    517:        return 0;
                    518: }
                    519:
                    520: /* Returns the id of an open channel suitable for keepaliving */
                    521:
                    522: int
1.142     itojun    523: channel_find_open(void)
1.121     markus    524: {
1.209     avsm      525:        u_int i;
1.121     markus    526:        Channel *c;
                    527:
                    528:        for (i = 0; i < channels_alloc; i++) {
                    529:                c = channels[i];
1.206     djm       530:                if (c == NULL || c->remote_id < 0)
1.121     markus    531:                        continue;
                    532:                switch (c->type) {
                    533:                case SSH_CHANNEL_CLOSED:
                    534:                case SSH_CHANNEL_DYNAMIC:
                    535:                case SSH_CHANNEL_X11_LISTENER:
                    536:                case SSH_CHANNEL_PORT_LISTENER:
                    537:                case SSH_CHANNEL_RPORT_LISTENER:
                    538:                case SSH_CHANNEL_OPENING:
                    539:                case SSH_CHANNEL_CONNECTING:
                    540:                case SSH_CHANNEL_ZOMBIE:
                    541:                        continue;
                    542:                case SSH_CHANNEL_LARVAL:
                    543:                case SSH_CHANNEL_AUTH_SOCKET:
                    544:                case SSH_CHANNEL_OPEN:
                    545:                case SSH_CHANNEL_X11_OPEN:
                    546:                        return i;
                    547:                case SSH_CHANNEL_INPUT_DRAINING:
                    548:                case SSH_CHANNEL_OUTPUT_DRAINING:
                    549:                        if (!compat13)
                    550:                                fatal("cannot happen: OUT_DRAIN");
                    551:                        return i;
                    552:                default:
                    553:                        fatal("channel_find_open: bad channel type %d", c->type);
                    554:                        /* NOTREACHED */
                    555:                }
                    556:        }
                    557:        return -1;
                    558: }
                    559:
                    560:
                    561: /*
                    562:  * Returns a message describing the currently open forwarded connections,
                    563:  * suitable for sending to the client.  The message contains crlf pairs for
                    564:  * newlines.
                    565:  */
                    566:
                    567: char *
1.142     itojun    568: channel_open_message(void)
1.121     markus    569: {
                    570:        Buffer buffer;
                    571:        Channel *c;
                    572:        char buf[1024], *cp;
1.209     avsm      573:        u_int i;
1.121     markus    574:
                    575:        buffer_init(&buffer);
                    576:        snprintf(buf, sizeof buf, "The following connections are open:\r\n");
                    577:        buffer_append(&buffer, buf, strlen(buf));
                    578:        for (i = 0; i < channels_alloc; i++) {
                    579:                c = channels[i];
                    580:                if (c == NULL)
                    581:                        continue;
                    582:                switch (c->type) {
                    583:                case SSH_CHANNEL_X11_LISTENER:
                    584:                case SSH_CHANNEL_PORT_LISTENER:
                    585:                case SSH_CHANNEL_RPORT_LISTENER:
                    586:                case SSH_CHANNEL_CLOSED:
                    587:                case SSH_CHANNEL_AUTH_SOCKET:
                    588:                case SSH_CHANNEL_ZOMBIE:
                    589:                        continue;
                    590:                case SSH_CHANNEL_LARVAL:
                    591:                case SSH_CHANNEL_OPENING:
                    592:                case SSH_CHANNEL_CONNECTING:
                    593:                case SSH_CHANNEL_DYNAMIC:
                    594:                case SSH_CHANNEL_OPEN:
                    595:                case SSH_CHANNEL_X11_OPEN:
                    596:                case SSH_CHANNEL_INPUT_DRAINING:
                    597:                case SSH_CHANNEL_OUTPUT_DRAINING:
1.204     djm       598:                        snprintf(buf, sizeof buf,
                    599:                            "  #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d cfd %d)\r\n",
1.121     markus    600:                            c->self, c->remote_name,
                    601:                            c->type, c->remote_id,
                    602:                            c->istate, buffer_len(&c->input),
                    603:                            c->ostate, buffer_len(&c->output),
1.204     djm       604:                            c->rfd, c->wfd, c->ctl_fd);
1.121     markus    605:                        buffer_append(&buffer, buf, strlen(buf));
                    606:                        continue;
                    607:                default:
                    608:                        fatal("channel_open_message: bad channel type %d", c->type);
                    609:                        /* NOTREACHED */
                    610:                }
                    611:        }
                    612:        buffer_append(&buffer, "\0", 1);
                    613:        cp = xstrdup(buffer_ptr(&buffer));
                    614:        buffer_free(&buffer);
                    615:        return cp;
                    616: }
                    617:
                    618: void
                    619: channel_send_open(int id)
                    620: {
                    621:        Channel *c = channel_lookup(id);
1.180     deraadt   622:
1.121     markus    623:        if (c == NULL) {
1.188     itojun    624:                logit("channel_send_open: %d: bad id", id);
1.121     markus    625:                return;
                    626:        }
1.184     markus    627:        debug2("channel %d: send open", id);
1.121     markus    628:        packet_start(SSH2_MSG_CHANNEL_OPEN);
                    629:        packet_put_cstring(c->ctype);
                    630:        packet_put_int(c->self);
                    631:        packet_put_int(c->local_window);
                    632:        packet_put_int(c->local_maxpacket);
                    633:        packet_send();
                    634: }
                    635:
                    636: void
1.184     markus    637: channel_request_start(int id, char *service, int wantconfirm)
1.121     markus    638: {
1.184     markus    639:        Channel *c = channel_lookup(id);
1.180     deraadt   640:
1.121     markus    641:        if (c == NULL) {
1.188     itojun    642:                logit("channel_request_start: %d: unknown channel id", id);
1.121     markus    643:                return;
                    644:        }
1.204     djm       645:        debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
1.121     markus    646:        packet_start(SSH2_MSG_CHANNEL_REQUEST);
                    647:        packet_put_int(c->remote_id);
                    648:        packet_put_cstring(service);
                    649:        packet_put_char(wantconfirm);
                    650: }
                    651: void
1.204     djm       652: channel_register_confirm(int id, channel_callback_fn *fn, void *ctx)
1.121     markus    653: {
                    654:        Channel *c = channel_lookup(id);
1.180     deraadt   655:
1.121     markus    656:        if (c == NULL) {
1.188     itojun    657:                logit("channel_register_comfirm: %d: bad id", id);
1.121     markus    658:                return;
                    659:        }
1.165     markus    660:        c->confirm = fn;
1.204     djm       661:        c->confirm_ctx = ctx;
1.121     markus    662: }
                    663: void
1.225     djm       664: channel_register_cleanup(int id, channel_callback_fn *fn, int do_close)
1.121     markus    665: {
1.229     markus    666:        Channel *c = channel_by_id(id);
1.180     deraadt   667:
1.121     markus    668:        if (c == NULL) {
1.188     itojun    669:                logit("channel_register_cleanup: %d: bad id", id);
1.121     markus    670:                return;
                    671:        }
1.131     markus    672:        c->detach_user = fn;
1.225     djm       673:        c->detach_close = do_close;
1.121     markus    674: }
                    675: void
                    676: channel_cancel_cleanup(int id)
                    677: {
1.229     markus    678:        Channel *c = channel_by_id(id);
1.180     deraadt   679:
1.121     markus    680:        if (c == NULL) {
1.188     itojun    681:                logit("channel_cancel_cleanup: %d: bad id", id);
1.121     markus    682:                return;
1.52      markus    683:        }
1.131     markus    684:        c->detach_user = NULL;
1.225     djm       685:        c->detach_close = 0;
1.121     markus    686: }
                    687: void
1.231     reyk      688: channel_register_filter(int id, channel_infilter_fn *ifn,
                    689:     channel_outfilter_fn *ofn)
1.121     markus    690: {
                    691:        Channel *c = channel_lookup(id);
1.180     deraadt   692:
1.121     markus    693:        if (c == NULL) {
1.188     itojun    694:                logit("channel_register_filter: %d: bad id", id);
1.121     markus    695:                return;
1.52      markus    696:        }
1.231     reyk      697:        c->input_filter = ifn;
                    698:        c->output_filter = ofn;
1.52      markus    699: }
                    700:
1.49      markus    701: void
1.121     markus    702: channel_set_fds(int id, int rfd, int wfd, int efd,
1.168     markus    703:     int extusage, int nonblock, u_int window_max)
1.1       deraadt   704: {
1.121     markus    705:        Channel *c = channel_lookup(id);
1.180     deraadt   706:
1.121     markus    707:        if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
                    708:                fatal("channel_activate for non-larval channel %d.", id);
                    709:        channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
                    710:        c->type = SSH_CHANNEL_OPEN;
1.168     markus    711:        c->local_window = c->local_window_max = window_max;
1.121     markus    712:        packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
                    713:        packet_put_int(c->remote_id);
                    714:        packet_put_int(c->local_window);
                    715:        packet_send();
1.1       deraadt   716: }
                    717:
1.27      markus    718: /*
1.41      markus    719:  * 'channel_pre*' are called just before select() to add any bits relevant to
                    720:  * channels in the select bitmasks.
                    721:  */
                    722: /*
                    723:  * 'channel_post*': perform any appropriate operations for channels which
                    724:  * have events pending.
1.27      markus    725:  */
1.41      markus    726: typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
                    727: chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
                    728: chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
                    729:
1.127     itojun    730: static void
1.41      markus    731: channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
                    732: {
                    733:        FD_SET(c->sock, readset);
                    734: }
                    735:
1.127     itojun    736: static void
1.75      markus    737: channel_pre_connecting(Channel *c, fd_set * readset, fd_set * writeset)
                    738: {
                    739:        debug3("channel %d: waiting for connection", c->self);
                    740:        FD_SET(c->sock, writeset);
                    741: }
                    742:
1.127     itojun    743: static void
1.41      markus    744: channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
                    745: {
                    746:        if (buffer_len(&c->input) < packet_get_maxsize())
                    747:                FD_SET(c->sock, readset);
                    748:        if (buffer_len(&c->output) > 0)
                    749:                FD_SET(c->sock, writeset);
                    750: }
1.1       deraadt   751:
1.127     itojun    752: static void
1.157     markus    753: channel_pre_open(Channel *c, fd_set * readset, fd_set * writeset)
1.41      markus    754: {
1.157     markus    755:        u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
1.41      markus    756:
1.214     markus    757:        /* check buffer limits */
                    758:        limit = MIN(limit, (BUFFER_MAX_LEN - BUFFER_MAX_CHUNK - CHAN_RBUF));
                    759:
1.44      markus    760:        if (c->istate == CHAN_INPUT_OPEN &&
1.157     markus    761:            limit > 0 &&
                    762:            buffer_len(&c->input) < limit)
1.44      markus    763:                FD_SET(c->rfd, readset);
                    764:        if (c->ostate == CHAN_OUTPUT_OPEN ||
                    765:            c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
                    766:                if (buffer_len(&c->output) > 0) {
                    767:                        FD_SET(c->wfd, writeset);
                    768:                } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1.172     markus    769:                        if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
1.223     djm       770:                                debug2("channel %d: obuf_empty delayed efd %d/(%d)",
                    771:                                    c->self, c->efd, buffer_len(&c->extended));
1.172     markus    772:                        else
                    773:                                chan_obuf_empty(c);
1.44      markus    774:                }
                    775:        }
                    776:        /** XXX check close conditions, too */
1.157     markus    777:        if (compat20 && c->efd != -1) {
1.44      markus    778:                if (c->extended_usage == CHAN_EXTENDED_WRITE &&
                    779:                    buffer_len(&c->extended) > 0)
                    780:                        FD_SET(c->efd, writeset);
1.172     markus    781:                else if (!(c->flags & CHAN_EOF_SENT) &&
                    782:                    c->extended_usage == CHAN_EXTENDED_READ &&
1.44      markus    783:                    buffer_len(&c->extended) < c->remote_window)
                    784:                        FD_SET(c->efd, readset);
                    785:        }
1.204     djm       786:        /* XXX: What about efd? races? */
1.208     deraadt   787:        if (compat20 && c->ctl_fd != -1 &&
1.204     djm       788:            c->istate == CHAN_INPUT_OPEN && c->ostate == CHAN_OUTPUT_OPEN)
                    789:                FD_SET(c->ctl_fd, readset);
1.44      markus    790: }
                    791:
1.127     itojun    792: static void
1.41      markus    793: channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
                    794: {
                    795:        if (buffer_len(&c->input) == 0) {
                    796:                packet_start(SSH_MSG_CHANNEL_CLOSE);
                    797:                packet_put_int(c->remote_id);
                    798:                packet_send();
                    799:                c->type = SSH_CHANNEL_CLOSED;
1.194     markus    800:                debug2("channel %d: closing after input drain.", c->self);
1.41      markus    801:        }
                    802: }
                    803:
1.127     itojun    804: static void
1.41      markus    805: channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
                    806: {
                    807:        if (buffer_len(&c->output) == 0)
1.113     markus    808:                chan_mark_dead(c);
1.49      markus    809:        else
1.41      markus    810:                FD_SET(c->sock, writeset);
                    811: }
                    812:
                    813: /*
                    814:  * This is a special state for X11 authentication spoofing.  An opened X11
                    815:  * connection (when authentication spoofing is being done) remains in this
                    816:  * state until the first packet has been completely read.  The authentication
                    817:  * data in that packet is then substituted by the real data if it matches the
                    818:  * fake data, and the channel is put into normal mode.
1.51      markus    819:  * XXX All this happens at the client side.
1.121     markus    820:  * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
1.41      markus    821:  */
1.127     itojun    822: static int
1.121     markus    823: x11_open_helper(Buffer *b)
1.1       deraadt   824: {
1.77      markus    825:        u_char *ucp;
                    826:        u_int proto_len, data_len;
1.25      markus    827:
1.41      markus    828:        /* Check if the fixed size part of the packet is in buffer. */
1.121     markus    829:        if (buffer_len(b) < 12)
1.41      markus    830:                return 0;
                    831:
                    832:        /* Parse the lengths of variable-length fields. */
1.155     stevesk   833:        ucp = buffer_ptr(b);
1.41      markus    834:        if (ucp[0] == 0x42) {   /* Byte order MSB first. */
                    835:                proto_len = 256 * ucp[6] + ucp[7];
                    836:                data_len = 256 * ucp[8] + ucp[9];
                    837:        } else if (ucp[0] == 0x6c) {    /* Byte order LSB first. */
                    838:                proto_len = ucp[6] + 256 * ucp[7];
                    839:                data_len = ucp[8] + 256 * ucp[9];
                    840:        } else {
1.194     markus    841:                debug2("Initial X11 packet contains bad byte order byte: 0x%x",
1.148     deraadt   842:                    ucp[0]);
1.41      markus    843:                return -1;
                    844:        }
                    845:
                    846:        /* Check if the whole packet is in buffer. */
1.121     markus    847:        if (buffer_len(b) <
1.41      markus    848:            12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
                    849:                return 0;
                    850:
                    851:        /* Check if authentication protocol matches. */
                    852:        if (proto_len != strlen(x11_saved_proto) ||
                    853:            memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
1.194     markus    854:                debug2("X11 connection uses different authentication protocol.");
1.41      markus    855:                return -1;
                    856:        }
                    857:        /* Check if authentication data matches our fake data. */
                    858:        if (data_len != x11_fake_data_len ||
                    859:            memcmp(ucp + 12 + ((proto_len + 3) & ~3),
                    860:                x11_fake_data, x11_fake_data_len) != 0) {
1.194     markus    861:                debug2("X11 auth data does not match fake data.");
1.41      markus    862:                return -1;
                    863:        }
                    864:        /* Check fake data length */
                    865:        if (x11_fake_data_len != x11_saved_data_len) {
                    866:                error("X11 fake_data_len %d != saved_data_len %d",
                    867:                    x11_fake_data_len, x11_saved_data_len);
                    868:                return -1;
                    869:        }
                    870:        /*
                    871:         * Received authentication protocol and data match
                    872:         * our fake data. Substitute the fake data with real
                    873:         * data.
                    874:         */
                    875:        memcpy(ucp + 12 + ((proto_len + 3) & ~3),
                    876:            x11_saved_data, x11_saved_data_len);
                    877:        return 1;
                    878: }
                    879:
1.127     itojun    880: static void
1.41      markus    881: channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
                    882: {
1.121     markus    883:        int ret = x11_open_helper(&c->output);
1.180     deraadt   884:
1.41      markus    885:        if (ret == 1) {
                    886:                /* Start normal processing for the channel. */
                    887:                c->type = SSH_CHANNEL_OPEN;
1.47      markus    888:                channel_pre_open_13(c, readset, writeset);
1.41      markus    889:        } else if (ret == -1) {
                    890:                /*
                    891:                 * We have received an X11 connection that has bad
                    892:                 * authentication information.
                    893:                 */
1.188     itojun    894:                logit("X11 connection rejected because of wrong authentication.");
1.41      markus    895:                buffer_clear(&c->input);
                    896:                buffer_clear(&c->output);
1.132     markus    897:                channel_close_fd(&c->sock);
1.41      markus    898:                c->sock = -1;
                    899:                c->type = SSH_CHANNEL_CLOSED;
                    900:                packet_start(SSH_MSG_CHANNEL_CLOSE);
                    901:                packet_put_int(c->remote_id);
                    902:                packet_send();
                    903:        }
                    904: }
1.25      markus    905:
1.127     itojun    906: static void
1.51      markus    907: channel_pre_x11_open(Channel *c, fd_set * readset, fd_set * writeset)
1.41      markus    908: {
1.121     markus    909:        int ret = x11_open_helper(&c->output);
1.133     markus    910:
                    911:        /* c->force_drain = 1; */
                    912:
1.41      markus    913:        if (ret == 1) {
                    914:                c->type = SSH_CHANNEL_OPEN;
1.157     markus    915:                channel_pre_open(c, readset, writeset);
1.41      markus    916:        } else if (ret == -1) {
1.188     itojun    917:                logit("X11 connection rejected because of wrong authentication.");
1.194     markus    918:                debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
1.156     markus    919:                chan_read_failed(c);
                    920:                buffer_clear(&c->input);
                    921:                chan_ibuf_empty(c);
                    922:                buffer_clear(&c->output);
                    923:                /* for proto v1, the peer will send an IEOF */
                    924:                if (compat20)
                    925:                        chan_write_failed(c);
                    926:                else
                    927:                        c->type = SSH_CHANNEL_OPEN;
1.194     markus    928:                debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
1.41      markus    929:        }
                    930: }
1.25      markus    931:
1.104     markus    932: /* try to decode a socks4 header */
1.127     itojun    933: static int
1.104     markus    934: channel_decode_socks4(Channel *c, fd_set * readset, fd_set * writeset)
1.103     markus    935: {
1.181     markus    936:        char *p, *host;
1.217     djm       937:        u_int len, have, i, found;
1.148     deraadt   938:        char username[256];
1.103     markus    939:        struct {
                    940:                u_int8_t version;
                    941:                u_int8_t command;
                    942:                u_int16_t dest_port;
1.104     markus    943:                struct in_addr dest_addr;
1.103     markus    944:        } s4_req, s4_rsp;
                    945:
1.104     markus    946:        debug2("channel %d: decode socks4", c->self);
1.109     markus    947:
                    948:        have = buffer_len(&c->input);
                    949:        len = sizeof(s4_req);
                    950:        if (have < len)
                    951:                return 0;
                    952:        p = buffer_ptr(&c->input);
                    953:        for (found = 0, i = len; i < have; i++) {
                    954:                if (p[i] == '\0') {
                    955:                        found = 1;
                    956:                        break;
                    957:                }
                    958:                if (i > 1024) {
                    959:                        /* the peer is probably sending garbage */
                    960:                        debug("channel %d: decode socks4: too long",
                    961:                            c->self);
                    962:                        return -1;
                    963:                }
                    964:        }
                    965:        if (!found)
                    966:                return 0;
1.103     markus    967:        buffer_get(&c->input, (char *)&s4_req.version, 1);
                    968:        buffer_get(&c->input, (char *)&s4_req.command, 1);
                    969:        buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
1.104     markus    970:        buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
1.109     markus    971:        have = buffer_len(&c->input);
1.103     markus    972:        p = buffer_ptr(&c->input);
                    973:        len = strlen(p);
1.106     markus    974:        debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1.103     markus    975:        if (len > have)
1.104     markus    976:                fatal("channel %d: decode socks4: len %d > have %d",
1.103     markus    977:                    c->self, len, have);
                    978:        strlcpy(username, p, sizeof(username));
                    979:        buffer_consume(&c->input, len);
                    980:        buffer_consume(&c->input, 1);           /* trailing '\0' */
                    981:
1.104     markus    982:        host = inet_ntoa(s4_req.dest_addr);
1.103     markus    983:        strlcpy(c->path, host, sizeof(c->path));
                    984:        c->host_port = ntohs(s4_req.dest_port);
1.148     deraadt   985:
1.194     markus    986:        debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1.106     markus    987:            c->self, host, c->host_port, s4_req.command);
1.103     markus    988:
1.104     markus    989:        if (s4_req.command != 1) {
                    990:                debug("channel %d: cannot handle: socks4 cn %d",
                    991:                    c->self, s4_req.command);
                    992:                return -1;
1.103     markus    993:        }
1.104     markus    994:        s4_rsp.version = 0;                     /* vn: 0 for reply */
                    995:        s4_rsp.command = 90;                    /* cd: req granted */
1.103     markus    996:        s4_rsp.dest_port = 0;                   /* ignored */
1.104     markus    997:        s4_rsp.dest_addr.s_addr = INADDR_ANY;   /* ignored */
1.103     markus    998:        buffer_append(&c->output, (char *)&s4_rsp, sizeof(s4_rsp));
1.104     markus    999:        return 1;
                   1000: }
                   1001:
1.193     markus   1002: /* try to decode a socks5 header */
                   1003: #define SSH_SOCKS5_AUTHDONE    0x1000
                   1004: #define SSH_SOCKS5_NOAUTH      0x00
                   1005: #define SSH_SOCKS5_IPV4                0x01
                   1006: #define SSH_SOCKS5_DOMAIN      0x03
                   1007: #define SSH_SOCKS5_IPV6                0x04
                   1008: #define SSH_SOCKS5_CONNECT     0x01
                   1009: #define SSH_SOCKS5_SUCCESS     0x00
                   1010:
                   1011: static int
                   1012: channel_decode_socks5(Channel *c, fd_set * readset, fd_set * writeset)
                   1013: {
                   1014:        struct {
                   1015:                u_int8_t version;
                   1016:                u_int8_t command;
                   1017:                u_int8_t reserved;
                   1018:                u_int8_t atyp;
                   1019:        } s5_req, s5_rsp;
                   1020:        u_int16_t dest_port;
                   1021:        u_char *p, dest_addr[255+1];
1.217     djm      1022:        u_int have, i, found, nmethods, addrlen, af;
1.193     markus   1023:
                   1024:        debug2("channel %d: decode socks5", c->self);
                   1025:        p = buffer_ptr(&c->input);
                   1026:        if (p[0] != 0x05)
                   1027:                return -1;
                   1028:        have = buffer_len(&c->input);
                   1029:        if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
                   1030:                /* format: ver | nmethods | methods */
1.198     djm      1031:                if (have < 2)
1.193     markus   1032:                        return 0;
                   1033:                nmethods = p[1];
                   1034:                if (have < nmethods + 2)
                   1035:                        return 0;
                   1036:                /* look for method: "NO AUTHENTICATION REQUIRED" */
                   1037:                for (found = 0, i = 2 ; i < nmethods + 2; i++) {
                   1038:                        if (p[i] == SSH_SOCKS5_NOAUTH ) {
                   1039:                                found = 1;
                   1040:                                break;
                   1041:                        }
                   1042:                }
                   1043:                if (!found) {
                   1044:                        debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
                   1045:                            c->self);
                   1046:                        return -1;
                   1047:                }
                   1048:                buffer_consume(&c->input, nmethods + 2);
                   1049:                buffer_put_char(&c->output, 0x05);              /* version */
                   1050:                buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
                   1051:                FD_SET(c->sock, writeset);
                   1052:                c->flags |= SSH_SOCKS5_AUTHDONE;
                   1053:                debug2("channel %d: socks5 auth done", c->self);
                   1054:                return 0;                               /* need more */
                   1055:        }
                   1056:        debug2("channel %d: socks5 post auth", c->self);
                   1057:        if (have < sizeof(s5_req)+1)
                   1058:                return 0;                       /* need more */
                   1059:        memcpy((char *)&s5_req, p, sizeof(s5_req));
                   1060:        if (s5_req.version != 0x05 ||
                   1061:            s5_req.command != SSH_SOCKS5_CONNECT ||
                   1062:            s5_req.reserved != 0x00) {
1.194     markus   1063:                debug2("channel %d: only socks5 connect supported", c->self);
1.193     markus   1064:                return -1;
                   1065:        }
1.213     deraadt  1066:        switch (s5_req.atyp){
1.193     markus   1067:        case SSH_SOCKS5_IPV4:
                   1068:                addrlen = 4;
                   1069:                af = AF_INET;
                   1070:                break;
                   1071:        case SSH_SOCKS5_DOMAIN:
                   1072:                addrlen = p[sizeof(s5_req)];
                   1073:                af = -1;
                   1074:                break;
                   1075:        case SSH_SOCKS5_IPV6:
                   1076:                addrlen = 16;
                   1077:                af = AF_INET6;
                   1078:                break;
                   1079:        default:
1.194     markus   1080:                debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1.193     markus   1081:                return -1;
                   1082:        }
                   1083:        if (have < 4 + addrlen + 2)
                   1084:                return 0;
                   1085:        buffer_consume(&c->input, sizeof(s5_req));
                   1086:        if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
                   1087:                buffer_consume(&c->input, 1);    /* host string length */
                   1088:        buffer_get(&c->input, (char *)&dest_addr, addrlen);
                   1089:        buffer_get(&c->input, (char *)&dest_port, 2);
                   1090:        dest_addr[addrlen] = '\0';
                   1091:        if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1.201     deraadt  1092:                strlcpy(c->path, (char *)dest_addr, sizeof(c->path));
1.193     markus   1093:        else if (inet_ntop(af, dest_addr, c->path, sizeof(c->path)) == NULL)
                   1094:                return -1;
                   1095:        c->host_port = ntohs(dest_port);
1.198     djm      1096:
1.194     markus   1097:        debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1.193     markus   1098:            c->self, c->path, c->host_port, s5_req.command);
                   1099:
                   1100:        s5_rsp.version = 0x05;
                   1101:        s5_rsp.command = SSH_SOCKS5_SUCCESS;
                   1102:        s5_rsp.reserved = 0;                    /* ignored */
                   1103:        s5_rsp.atyp = SSH_SOCKS5_IPV4;
                   1104:        ((struct in_addr *)&dest_addr)->s_addr = INADDR_ANY;
                   1105:        dest_port = 0;                          /* ignored */
                   1106:
                   1107:        buffer_append(&c->output, (char *)&s5_rsp, sizeof(s5_rsp));
                   1108:        buffer_append(&c->output, (char *)&dest_addr, sizeof(struct in_addr));
                   1109:        buffer_append(&c->output, (char *)&dest_port, sizeof(dest_port));
                   1110:        return 1;
                   1111: }
                   1112:
1.104     markus   1113: /* dynamic port forwarding */
1.127     itojun   1114: static void
1.104     markus   1115: channel_pre_dynamic(Channel *c, fd_set * readset, fd_set * writeset)
                   1116: {
                   1117:        u_char *p;
1.217     djm      1118:        u_int have;
                   1119:        int ret;
1.103     markus   1120:
1.104     markus   1121:        have = buffer_len(&c->input);
1.137     markus   1122:        c->delayed = 0;
1.104     markus   1123:        debug2("channel %d: pre_dynamic: have %d", c->self, have);
1.105     markus   1124:        /* buffer_dump(&c->input); */
1.104     markus   1125:        /* check if the fixed size part of the packet is in buffer. */
1.193     markus   1126:        if (have < 3) {
1.104     markus   1127:                /* need more */
                   1128:                FD_SET(c->sock, readset);
                   1129:                return;
                   1130:        }
                   1131:        /* try to guess the protocol */
                   1132:        p = buffer_ptr(&c->input);
                   1133:        switch (p[0]) {
                   1134:        case 0x04:
                   1135:                ret = channel_decode_socks4(c, readset, writeset);
1.193     markus   1136:                break;
                   1137:        case 0x05:
                   1138:                ret = channel_decode_socks5(c, readset, writeset);
1.104     markus   1139:                break;
                   1140:        default:
                   1141:                ret = -1;
                   1142:                break;
                   1143:        }
                   1144:        if (ret < 0) {
1.113     markus   1145:                chan_mark_dead(c);
1.104     markus   1146:        } else if (ret == 0) {
                   1147:                debug2("channel %d: pre_dynamic: need more", c->self);
                   1148:                /* need more */
                   1149:                FD_SET(c->sock, readset);
                   1150:        } else {
                   1151:                /* switch to the next state */
                   1152:                c->type = SSH_CHANNEL_OPENING;
                   1153:                port_open_helper(c, "direct-tcpip");
                   1154:        }
1.103     markus   1155: }
                   1156:
1.41      markus   1157: /* This is our fake X11 server socket. */
1.127     itojun   1158: static void
1.41      markus   1159: channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
                   1160: {
1.113     markus   1161:        Channel *nc;
1.41      markus   1162:        struct sockaddr addr;
1.162     stevesk  1163:        int newsock;
1.41      markus   1164:        socklen_t addrlen;
1.85      markus   1165:        char buf[16384], *remote_ipaddr;
1.51      markus   1166:        int remote_port;
1.25      markus   1167:
1.41      markus   1168:        if (FD_ISSET(c->sock, readset)) {
                   1169:                debug("X11 connection requested.");
                   1170:                addrlen = sizeof(addr);
                   1171:                newsock = accept(c->sock, &addr, &addrlen);
1.149     markus   1172:                if (c->single_connection) {
1.194     markus   1173:                        debug2("single_connection: closing X11 listener.");
1.149     markus   1174:                        channel_close_fd(&c->sock);
                   1175:                        chan_mark_dead(c);
                   1176:                }
1.41      markus   1177:                if (newsock < 0) {
                   1178:                        error("accept: %.100s", strerror(errno));
                   1179:                        return;
                   1180:                }
1.162     stevesk  1181:                set_nodelay(newsock);
1.85      markus   1182:                remote_ipaddr = get_peer_ipaddr(newsock);
1.51      markus   1183:                remote_port = get_peer_port(newsock);
1.41      markus   1184:                snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1.85      markus   1185:                    remote_ipaddr, remote_port);
1.51      markus   1186:
1.113     markus   1187:                nc = channel_new("accepted x11 socket",
1.51      markus   1188:                    SSH_CHANNEL_OPENING, newsock, newsock, -1,
1.190     markus   1189:                    c->local_window_max, c->local_maxpacket, 0, buf, 1);
1.51      markus   1190:                if (compat20) {
                   1191:                        packet_start(SSH2_MSG_CHANNEL_OPEN);
                   1192:                        packet_put_cstring("x11");
1.113     markus   1193:                        packet_put_int(nc->self);
1.149     markus   1194:                        packet_put_int(nc->local_window_max);
                   1195:                        packet_put_int(nc->local_maxpacket);
1.85      markus   1196:                        /* originator ipaddr and port */
                   1197:                        packet_put_cstring(remote_ipaddr);
1.57      markus   1198:                        if (datafellows & SSH_BUG_X11FWD) {
1.194     markus   1199:                                debug2("ssh2 x11 bug compat mode");
1.57      markus   1200:                        } else {
                   1201:                                packet_put_int(remote_port);
                   1202:                        }
1.51      markus   1203:                        packet_send();
                   1204:                } else {
                   1205:                        packet_start(SSH_SMSG_X11_OPEN);
1.113     markus   1206:                        packet_put_int(nc->self);
1.121     markus   1207:                        if (packet_get_protocol_flags() &
                   1208:                            SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1.125     markus   1209:                                packet_put_cstring(buf);
1.51      markus   1210:                        packet_send();
                   1211:                }
1.85      markus   1212:                xfree(remote_ipaddr);
1.41      markus   1213:        }
                   1214: }
1.25      markus   1215:
1.127     itojun   1216: static void
1.103     markus   1217: port_open_helper(Channel *c, char *rtype)
                   1218: {
                   1219:        int direct;
                   1220:        char buf[1024];
                   1221:        char *remote_ipaddr = get_peer_ipaddr(c->sock);
1.216     markus   1222:        int remote_port = get_peer_port(c->sock);
1.103     markus   1223:
                   1224:        direct = (strcmp(rtype, "direct-tcpip") == 0);
                   1225:
                   1226:        snprintf(buf, sizeof buf,
                   1227:            "%s: listening port %d for %.100s port %d, "
                   1228:            "connect from %.200s port %d",
                   1229:            rtype, c->listening_port, c->path, c->host_port,
                   1230:            remote_ipaddr, remote_port);
                   1231:
                   1232:        xfree(c->remote_name);
                   1233:        c->remote_name = xstrdup(buf);
                   1234:
                   1235:        if (compat20) {
                   1236:                packet_start(SSH2_MSG_CHANNEL_OPEN);
                   1237:                packet_put_cstring(rtype);
                   1238:                packet_put_int(c->self);
                   1239:                packet_put_int(c->local_window_max);
                   1240:                packet_put_int(c->local_maxpacket);
                   1241:                if (direct) {
                   1242:                        /* target host, port */
                   1243:                        packet_put_cstring(c->path);
                   1244:                        packet_put_int(c->host_port);
                   1245:                } else {
                   1246:                        /* listen address, port */
                   1247:                        packet_put_cstring(c->path);
                   1248:                        packet_put_int(c->listening_port);
                   1249:                }
                   1250:                /* originator host and port */
                   1251:                packet_put_cstring(remote_ipaddr);
1.216     markus   1252:                packet_put_int((u_int)remote_port);
1.103     markus   1253:                packet_send();
                   1254:        } else {
                   1255:                packet_start(SSH_MSG_PORT_OPEN);
                   1256:                packet_put_int(c->self);
                   1257:                packet_put_cstring(c->path);
                   1258:                packet_put_int(c->host_port);
1.121     markus   1259:                if (packet_get_protocol_flags() &
                   1260:                    SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1.103     markus   1261:                        packet_put_cstring(c->remote_name);
                   1262:                packet_send();
                   1263:        }
                   1264:        xfree(remote_ipaddr);
                   1265: }
                   1266:
1.226     djm      1267: static void
                   1268: channel_set_reuseaddr(int fd)
                   1269: {
                   1270:        int on = 1;
                   1271:
                   1272:        /*
                   1273:         * Set socket options.
                   1274:         * Allow local port reuse in TIME_WAIT.
                   1275:         */
                   1276:        if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
                   1277:                error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
                   1278: }
                   1279:
1.41      markus   1280: /*
                   1281:  * This socket is listening for connections to a forwarded TCP/IP port.
                   1282:  */
1.127     itojun   1283: static void
1.41      markus   1284: channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
                   1285: {
1.103     markus   1286:        Channel *nc;
1.41      markus   1287:        struct sockaddr addr;
1.113     markus   1288:        int newsock, nextstate;
1.41      markus   1289:        socklen_t addrlen;
1.103     markus   1290:        char *rtype;
1.73      markus   1291:
1.41      markus   1292:        if (FD_ISSET(c->sock, readset)) {
                   1293:                debug("Connection to port %d forwarding "
                   1294:                    "to %.100s port %d requested.",
                   1295:                    c->listening_port, c->path, c->host_port);
1.103     markus   1296:
1.137     markus   1297:                if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
                   1298:                        nextstate = SSH_CHANNEL_OPENING;
                   1299:                        rtype = "forwarded-tcpip";
                   1300:                } else {
                   1301:                        if (c->host_port == 0) {
                   1302:                                nextstate = SSH_CHANNEL_DYNAMIC;
1.138     markus   1303:                                rtype = "dynamic-tcpip";
1.137     markus   1304:                        } else {
                   1305:                                nextstate = SSH_CHANNEL_OPENING;
                   1306:                                rtype = "direct-tcpip";
                   1307:                        }
                   1308:                }
1.103     markus   1309:
1.41      markus   1310:                addrlen = sizeof(addr);
                   1311:                newsock = accept(c->sock, &addr, &addrlen);
                   1312:                if (newsock < 0) {
                   1313:                        error("accept: %.100s", strerror(errno));
                   1314:                        return;
                   1315:                }
1.169     stevesk  1316:                set_nodelay(newsock);
1.190     markus   1317:                nc = channel_new(rtype, nextstate, newsock, newsock, -1,
                   1318:                    c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1.103     markus   1319:                nc->listening_port = c->listening_port;
                   1320:                nc->host_port = c->host_port;
                   1321:                strlcpy(nc->path, c->path, sizeof(nc->path));
                   1322:
1.137     markus   1323:                if (nextstate == SSH_CHANNEL_DYNAMIC) {
                   1324:                        /*
                   1325:                         * do not call the channel_post handler until
                   1326:                         * this flag has been reset by a pre-handler.
                   1327:                         * otherwise the FD_ISSET calls might overflow
                   1328:                         */
                   1329:                        nc->delayed = 1;
                   1330:                } else {
1.103     markus   1331:                        port_open_helper(nc, rtype);
1.137     markus   1332:                }
1.41      markus   1333:        }
                   1334: }
1.25      markus   1335:
1.41      markus   1336: /*
                   1337:  * This is the authentication agent socket listening for connections from
                   1338:  * clients.
                   1339:  */
1.127     itojun   1340: static void
1.41      markus   1341: channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
                   1342: {
1.113     markus   1343:        Channel *nc;
                   1344:        int newsock;
1.41      markus   1345:        struct sockaddr addr;
                   1346:        socklen_t addrlen;
1.25      markus   1347:
1.41      markus   1348:        if (FD_ISSET(c->sock, readset)) {
                   1349:                addrlen = sizeof(addr);
                   1350:                newsock = accept(c->sock, &addr, &addrlen);
                   1351:                if (newsock < 0) {
                   1352:                        error("accept from auth socket: %.100s", strerror(errno));
                   1353:                        return;
                   1354:                }
1.113     markus   1355:                nc = channel_new("accepted auth socket",
1.73      markus   1356:                    SSH_CHANNEL_OPENING, newsock, newsock, -1,
                   1357:                    c->local_window_max, c->local_maxpacket,
1.190     markus   1358:                    0, "accepted auth socket", 1);
1.73      markus   1359:                if (compat20) {
                   1360:                        packet_start(SSH2_MSG_CHANNEL_OPEN);
                   1361:                        packet_put_cstring("auth-agent@openssh.com");
1.113     markus   1362:                        packet_put_int(nc->self);
1.73      markus   1363:                        packet_put_int(c->local_window_max);
                   1364:                        packet_put_int(c->local_maxpacket);
                   1365:                } else {
                   1366:                        packet_start(SSH_SMSG_AGENT_OPEN);
1.113     markus   1367:                        packet_put_int(nc->self);
1.73      markus   1368:                }
1.41      markus   1369:                packet_send();
                   1370:        }
                   1371: }
1.25      markus   1372:
1.127     itojun   1373: static void
1.75      markus   1374: channel_post_connecting(Channel *c, fd_set * readset, fd_set * writeset)
                   1375: {
1.114     markus   1376:        int err = 0;
1.129     stevesk  1377:        socklen_t sz = sizeof(err);
1.114     markus   1378:
1.75      markus   1379:        if (FD_ISSET(c->sock, writeset)) {
1.170     stevesk  1380:                if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1.114     markus   1381:                        err = errno;
                   1382:                        error("getsockopt SO_ERROR failed");
                   1383:                }
                   1384:                if (err == 0) {
                   1385:                        debug("channel %d: connected", c->self);
                   1386:                        c->type = SSH_CHANNEL_OPEN;
                   1387:                        if (compat20) {
                   1388:                                packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1389:                                packet_put_int(c->remote_id);
                   1390:                                packet_put_int(c->self);
                   1391:                                packet_put_int(c->local_window);
                   1392:                                packet_put_int(c->local_maxpacket);
                   1393:                        } else {
                   1394:                                packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1395:                                packet_put_int(c->remote_id);
                   1396:                                packet_put_int(c->self);
                   1397:                        }
1.75      markus   1398:                } else {
1.114     markus   1399:                        debug("channel %d: not connected: %s",
                   1400:                            c->self, strerror(err));
                   1401:                        if (compat20) {
                   1402:                                packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
                   1403:                                packet_put_int(c->remote_id);
                   1404:                                packet_put_int(SSH2_OPEN_CONNECT_FAILED);
                   1405:                                if (!(datafellows & SSH_BUG_OPENFAILURE)) {
                   1406:                                        packet_put_cstring(strerror(err));
                   1407:                                        packet_put_cstring("");
                   1408:                                }
1.75      markus   1409:                        } else {
1.114     markus   1410:                                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   1411:                                packet_put_int(c->remote_id);
1.75      markus   1412:                        }
1.114     markus   1413:                        chan_mark_dead(c);
1.75      markus   1414:                }
1.114     markus   1415:                packet_send();
1.75      markus   1416:        }
                   1417: }
                   1418:
1.127     itojun   1419: static int
1.41      markus   1420: channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
                   1421: {
1.214     markus   1422:        char buf[CHAN_RBUF];
1.41      markus   1423:        int len;
1.25      markus   1424:
1.118     markus   1425:        if (c->rfd != -1 &&
1.41      markus   1426:            FD_ISSET(c->rfd, readset)) {
                   1427:                len = read(c->rfd, buf, sizeof(buf));
1.53      markus   1428:                if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1429:                        return 1;
1.41      markus   1430:                if (len <= 0) {
1.194     markus   1431:                        debug2("channel %d: read<=0 rfd %d len %d",
1.41      markus   1432:                            c->self, c->rfd, len);
1.104     markus   1433:                        if (c->type != SSH_CHANNEL_OPEN) {
1.194     markus   1434:                                debug2("channel %d: not open", c->self);
1.113     markus   1435:                                chan_mark_dead(c);
1.103     markus   1436:                                return -1;
1.104     markus   1437:                        } else if (compat13) {
1.158     markus   1438:                                buffer_clear(&c->output);
1.41      markus   1439:                                c->type = SSH_CHANNEL_INPUT_DRAINING;
1.194     markus   1440:                                debug2("channel %d: input draining.", c->self);
1.25      markus   1441:                        } else {
1.41      markus   1442:                                chan_read_failed(c);
1.25      markus   1443:                        }
1.41      markus   1444:                        return -1;
                   1445:                }
1.143     deraadt  1446:                if (c->input_filter != NULL) {
1.66      markus   1447:                        if (c->input_filter(c, buf, len) == -1) {
1.194     markus   1448:                                debug2("channel %d: filter stops", c->self);
1.65      markus   1449:                                chan_read_failed(c);
                   1450:                        }
1.228     reyk     1451:                } else if (c->datagram) {
                   1452:                        buffer_put_string(&c->input, buf, len);
1.65      markus   1453:                } else {
                   1454:                        buffer_append(&c->input, buf, len);
                   1455:                }
1.41      markus   1456:        }
                   1457:        return 1;
                   1458: }
1.127     itojun   1459: static int
1.41      markus   1460: channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
                   1461: {
1.95      markus   1462:        struct termios tio;
1.231     reyk     1463:        u_char *data = NULL, *buf;
1.134     markus   1464:        u_int dlen;
1.41      markus   1465:        int len;
1.25      markus   1466:
1.41      markus   1467:        /* Send buffered output data to the socket. */
1.118     markus   1468:        if (c->wfd != -1 &&
1.41      markus   1469:            FD_ISSET(c->wfd, writeset) &&
                   1470:            buffer_len(&c->output) > 0) {
1.231     reyk     1471:                if (c->output_filter != NULL) {
                   1472:                        if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
                   1473:                                debug2("channel %d: filter stops", c->self);
1.232     reyk     1474:                                if (c->type != SSH_CHANNEL_OPEN)
                   1475:                                        chan_mark_dead(c);
                   1476:                                else
                   1477:                                        chan_write_failed(c);
                   1478:                                return -1;
1.231     reyk     1479:                        }
                   1480:                } else if (c->datagram) {
                   1481:                        buf = data = buffer_get_string(&c->output, &dlen);
                   1482:                } else {
                   1483:                        buf = data = buffer_ptr(&c->output);
                   1484:                        dlen = buffer_len(&c->output);
                   1485:                }
                   1486:
1.228     reyk     1487:                if (c->datagram) {
                   1488:                        /* ignore truncated writes, datagrams might get lost */
                   1489:                        c->local_consumed += dlen + 4;
1.231     reyk     1490:                        len = write(c->wfd, buf, dlen);
1.228     reyk     1491:                        xfree(data);
                   1492:                        if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1493:                                return 1;
                   1494:                        if (len <= 0) {
                   1495:                                if (c->type != SSH_CHANNEL_OPEN)
                   1496:                                        chan_mark_dead(c);
                   1497:                                else
                   1498:                                        chan_write_failed(c);
                   1499:                                return -1;
                   1500:                        }
                   1501:                        return 1;
                   1502:                }
1.231     reyk     1503:
                   1504:                len = write(c->wfd, buf, dlen);
1.53      markus   1505:                if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1506:                        return 1;
1.41      markus   1507:                if (len <= 0) {
1.104     markus   1508:                        if (c->type != SSH_CHANNEL_OPEN) {
1.194     markus   1509:                                debug2("channel %d: not open", c->self);
1.113     markus   1510:                                chan_mark_dead(c);
1.104     markus   1511:                                return -1;
                   1512:                        } else if (compat13) {
1.158     markus   1513:                                buffer_clear(&c->output);
1.194     markus   1514:                                debug2("channel %d: input draining.", c->self);
1.41      markus   1515:                                c->type = SSH_CHANNEL_INPUT_DRAINING;
                   1516:                        } else {
                   1517:                                chan_write_failed(c);
                   1518:                        }
                   1519:                        return -1;
1.91      markus   1520:                }
1.231     reyk     1521:                if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
1.91      markus   1522:                        if (tcgetattr(c->wfd, &tio) == 0 &&
                   1523:                            !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
                   1524:                                /*
                   1525:                                 * Simulate echo to reduce the impact of
1.96      markus   1526:                                 * traffic analysis. We need to match the
1.95      markus   1527:                                 * size of a SSH2_MSG_CHANNEL_DATA message
1.231     reyk     1528:                                 * (4 byte channel id + buf)
1.91      markus   1529:                                 */
1.95      markus   1530:                                packet_send_ignore(4 + len);
1.91      markus   1531:                                packet_send();
                   1532:                        }
1.25      markus   1533:                }
1.41      markus   1534:                buffer_consume(&c->output, len);
1.44      markus   1535:                if (compat20 && len > 0) {
                   1536:                        c->local_consumed += len;
                   1537:                }
                   1538:        }
                   1539:        return 1;
                   1540: }
1.127     itojun   1541: static int
1.44      markus   1542: channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
                   1543: {
1.214     markus   1544:        char buf[CHAN_RBUF];
1.44      markus   1545:        int len;
                   1546:
1.45      markus   1547: /** XXX handle drain efd, too */
1.44      markus   1548:        if (c->efd != -1) {
                   1549:                if (c->extended_usage == CHAN_EXTENDED_WRITE &&
                   1550:                    FD_ISSET(c->efd, writeset) &&
                   1551:                    buffer_len(&c->extended) > 0) {
                   1552:                        len = write(c->efd, buffer_ptr(&c->extended),
                   1553:                            buffer_len(&c->extended));
1.70      markus   1554:                        debug2("channel %d: written %d to efd %d",
1.44      markus   1555:                            c->self, len, c->efd);
1.93      markus   1556:                        if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1557:                                return 1;
                   1558:                        if (len <= 0) {
                   1559:                                debug2("channel %d: closing write-efd %d",
                   1560:                                    c->self, c->efd);
1.132     markus   1561:                                channel_close_fd(&c->efd);
1.93      markus   1562:                        } else {
1.44      markus   1563:                                buffer_consume(&c->extended, len);
                   1564:                                c->local_consumed += len;
                   1565:                        }
                   1566:                } else if (c->extended_usage == CHAN_EXTENDED_READ &&
                   1567:                    FD_ISSET(c->efd, readset)) {
                   1568:                        len = read(c->efd, buf, sizeof(buf));
1.70      markus   1569:                        debug2("channel %d: read %d from efd %d",
1.148     deraadt  1570:                            c->self, len, c->efd);
1.93      markus   1571:                        if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1572:                                return 1;
                   1573:                        if (len <= 0) {
                   1574:                                debug2("channel %d: closing read-efd %d",
1.45      markus   1575:                                    c->self, c->efd);
1.132     markus   1576:                                channel_close_fd(&c->efd);
1.93      markus   1577:                        } else {
1.44      markus   1578:                                buffer_append(&c->extended, buf, len);
1.93      markus   1579:                        }
1.44      markus   1580:                }
                   1581:        }
                   1582:        return 1;
                   1583: }
1.127     itojun   1584: static int
1.204     djm      1585: channel_handle_ctl(Channel *c, fd_set * readset, fd_set * writeset)
                   1586: {
                   1587:        char buf[16];
                   1588:        int len;
                   1589:
                   1590:        /* Monitor control fd to detect if the slave client exits */
                   1591:        if (c->ctl_fd != -1 && FD_ISSET(c->ctl_fd, readset)) {
                   1592:                len = read(c->ctl_fd, buf, sizeof(buf));
                   1593:                if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1594:                        return 1;
                   1595:                if (len <= 0) {
                   1596:                        debug2("channel %d: ctl read<=0", c->self);
                   1597:                        if (c->type != SSH_CHANNEL_OPEN) {
                   1598:                                debug2("channel %d: not open", c->self);
                   1599:                                chan_mark_dead(c);
                   1600:                                return -1;
                   1601:                        } else {
                   1602:                                chan_read_failed(c);
                   1603:                                chan_write_failed(c);
                   1604:                        }
                   1605:                        return -1;
                   1606:                } else
                   1607:                        fatal("%s: unexpected data on ctl fd", __func__);
                   1608:        }
                   1609:        return 1;
                   1610: }
                   1611: static int
1.93      markus   1612: channel_check_window(Channel *c)
1.44      markus   1613: {
1.104     markus   1614:        if (c->type == SSH_CHANNEL_OPEN &&
                   1615:            !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1.44      markus   1616:            c->local_window < c->local_window_max/2 &&
                   1617:            c->local_consumed > 0) {
                   1618:                packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
                   1619:                packet_put_int(c->remote_id);
                   1620:                packet_put_int(c->local_consumed);
                   1621:                packet_send();
1.70      markus   1622:                debug2("channel %d: window %d sent adjust %d",
1.44      markus   1623:                    c->self, c->local_window,
                   1624:                    c->local_consumed);
                   1625:                c->local_window += c->local_consumed;
                   1626:                c->local_consumed = 0;
1.1       deraadt  1627:        }
1.41      markus   1628:        return 1;
1.1       deraadt  1629: }
                   1630:
1.127     itojun   1631: static void
1.157     markus   1632: channel_post_open(Channel *c, fd_set * readset, fd_set * writeset)
1.41      markus   1633: {
1.137     markus   1634:        if (c->delayed)
                   1635:                return;
1.41      markus   1636:        channel_handle_rfd(c, readset, writeset);
                   1637:        channel_handle_wfd(c, readset, writeset);
1.157     markus   1638:        if (!compat20)
1.137     markus   1639:                return;
1.44      markus   1640:        channel_handle_efd(c, readset, writeset);
1.204     djm      1641:        channel_handle_ctl(c, readset, writeset);
1.93      markus   1642:        channel_check_window(c);
1.44      markus   1643: }
                   1644:
1.127     itojun   1645: static void
1.41      markus   1646: channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
1.1       deraadt  1647: {
1.41      markus   1648:        int len;
1.180     deraadt  1649:
1.41      markus   1650:        /* Send buffered output data to the socket. */
                   1651:        if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
                   1652:                len = write(c->sock, buffer_ptr(&c->output),
                   1653:                            buffer_len(&c->output));
                   1654:                if (len <= 0)
1.158     markus   1655:                        buffer_clear(&c->output);
1.41      markus   1656:                else
                   1657:                        buffer_consume(&c->output, len);
                   1658:        }
                   1659: }
1.25      markus   1660:
1.127     itojun   1661: static void
1.44      markus   1662: channel_handler_init_20(void)
                   1663: {
1.157     markus   1664:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open;
1.51      markus   1665:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
1.44      markus   1666:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
1.73      markus   1667:        channel_pre[SSH_CHANNEL_RPORT_LISTENER] =       &channel_pre_listener;
1.51      markus   1668:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
1.73      markus   1669:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1.75      markus   1670:        channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1.103     markus   1671:        channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1.44      markus   1672:
1.157     markus   1673:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open;
1.44      markus   1674:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
1.73      markus   1675:        channel_post[SSH_CHANNEL_RPORT_LISTENER] =      &channel_post_port_listener;
1.51      markus   1676:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
1.73      markus   1677:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1.75      markus   1678:        channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1.157     markus   1679:        channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
1.44      markus   1680: }
                   1681:
1.127     itojun   1682: static void
1.41      markus   1683: channel_handler_init_13(void)
                   1684: {
                   1685:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_13;
                   1686:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open_13;
                   1687:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
                   1688:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
                   1689:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
                   1690:        channel_pre[SSH_CHANNEL_INPUT_DRAINING] =       &channel_pre_input_draining;
                   1691:        channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] =      &channel_pre_output_draining;
1.75      markus   1692:        channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1.103     markus   1693:        channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1.25      markus   1694:
1.157     markus   1695:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open;
1.41      markus   1696:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
                   1697:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
                   1698:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
                   1699:        channel_post[SSH_CHANNEL_OUTPUT_DRAINING] =     &channel_post_output_drain_13;
1.75      markus   1700:        channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1.157     markus   1701:        channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
1.41      markus   1702: }
1.25      markus   1703:
1.127     itojun   1704: static void
1.41      markus   1705: channel_handler_init_15(void)
                   1706: {
1.157     markus   1707:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open;
1.51      markus   1708:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
1.41      markus   1709:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
                   1710:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
                   1711:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1.75      markus   1712:        channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1.103     markus   1713:        channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1.25      markus   1714:
1.41      markus   1715:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
                   1716:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
                   1717:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1.157     markus   1718:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open;
1.75      markus   1719:        channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1.157     markus   1720:        channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
1.41      markus   1721: }
1.27      markus   1722:
1.127     itojun   1723: static void
1.41      markus   1724: channel_handler_init(void)
                   1725: {
                   1726:        int i;
1.180     deraadt  1727:
1.148     deraadt  1728:        for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1.41      markus   1729:                channel_pre[i] = NULL;
                   1730:                channel_post[i] = NULL;
                   1731:        }
1.44      markus   1732:        if (compat20)
                   1733:                channel_handler_init_20();
                   1734:        else if (compat13)
1.41      markus   1735:                channel_handler_init_13();
                   1736:        else
                   1737:                channel_handler_init_15();
                   1738: }
1.25      markus   1739:
1.140     markus   1740: /* gc dead channels */
                   1741: static void
                   1742: channel_garbage_collect(Channel *c)
                   1743: {
                   1744:        if (c == NULL)
                   1745:                return;
                   1746:        if (c->detach_user != NULL) {
1.225     djm      1747:                if (!chan_is_dead(c, c->detach_close))
1.140     markus   1748:                        return;
1.194     markus   1749:                debug2("channel %d: gc: notify user", c->self);
1.140     markus   1750:                c->detach_user(c->self, NULL);
                   1751:                /* if we still have a callback */
                   1752:                if (c->detach_user != NULL)
                   1753:                        return;
1.194     markus   1754:                debug2("channel %d: gc: user detached", c->self);
1.140     markus   1755:        }
                   1756:        if (!chan_is_dead(c, 1))
                   1757:                return;
1.194     markus   1758:        debug2("channel %d: garbage collecting", c->self);
1.140     markus   1759:        channel_free(c);
                   1760: }
                   1761:
1.127     itojun   1762: static void
1.41      markus   1763: channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
                   1764: {
                   1765:        static int did_init = 0;
1.209     avsm     1766:        u_int i;
1.41      markus   1767:        Channel *c;
1.25      markus   1768:
1.41      markus   1769:        if (!did_init) {
                   1770:                channel_handler_init();
                   1771:                did_init = 1;
                   1772:        }
                   1773:        for (i = 0; i < channels_alloc; i++) {
1.113     markus   1774:                c = channels[i];
                   1775:                if (c == NULL)
1.41      markus   1776:                        continue;
1.118     markus   1777:                if (ftab[c->type] != NULL)
                   1778:                        (*ftab[c->type])(c, readset, writeset);
1.140     markus   1779:                channel_garbage_collect(c);
1.1       deraadt  1780:        }
                   1781: }
                   1782:
1.121     markus   1783: /*
                   1784:  * Allocate/update select bitmasks and add any bits relevant to channels in
                   1785:  * select bitmasks.
                   1786:  */
1.49      markus   1787: void
1.100     markus   1788: channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1.209     avsm     1789:     u_int *nallocp, int rekeying)
1.41      markus   1790: {
1.209     avsm     1791:        u_int n, sz;
1.84      markus   1792:
                   1793:        n = MAX(*maxfdp, channel_max_fd);
                   1794:
                   1795:        sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1.132     markus   1796:        /* perhaps check sz < nalloc/2 and shrink? */
                   1797:        if (*readsetp == NULL || sz > *nallocp) {
                   1798:                *readsetp = xrealloc(*readsetp, sz);
                   1799:                *writesetp = xrealloc(*writesetp, sz);
                   1800:                *nallocp = sz;
1.84      markus   1801:        }
1.132     markus   1802:        *maxfdp = n;
1.84      markus   1803:        memset(*readsetp, 0, sz);
                   1804:        memset(*writesetp, 0, sz);
                   1805:
1.100     markus   1806:        if (!rekeying)
                   1807:                channel_handler(channel_pre, *readsetp, *writesetp);
1.41      markus   1808: }
                   1809:
1.121     markus   1810: /*
                   1811:  * After select, perform any appropriate operations for channels which have
                   1812:  * events pending.
                   1813:  */
1.49      markus   1814: void
1.41      markus   1815: channel_after_select(fd_set * readset, fd_set * writeset)
                   1816: {
                   1817:        channel_handler(channel_post, readset, writeset);
                   1818: }
                   1819:
1.121     markus   1820:
1.84      markus   1821: /* If there is data to send to the connection, enqueue some of it now. */
1.1       deraadt  1822:
1.49      markus   1823: void
1.142     itojun   1824: channel_output_poll(void)
1.1       deraadt  1825: {
1.41      markus   1826:        Channel *c;
1.209     avsm     1827:        u_int i, len;
1.1       deraadt  1828:
1.25      markus   1829:        for (i = 0; i < channels_alloc; i++) {
1.113     markus   1830:                c = channels[i];
                   1831:                if (c == NULL)
                   1832:                        continue;
1.37      markus   1833:
1.121     markus   1834:                /*
                   1835:                 * We are only interested in channels that can have buffered
                   1836:                 * incoming data.
                   1837:                 */
1.37      markus   1838:                if (compat13) {
1.41      markus   1839:                        if (c->type != SSH_CHANNEL_OPEN &&
                   1840:                            c->type != SSH_CHANNEL_INPUT_DRAINING)
1.37      markus   1841:                                continue;
                   1842:                } else {
1.41      markus   1843:                        if (c->type != SSH_CHANNEL_OPEN)
1.37      markus   1844:                                continue;
                   1845:                }
1.46      markus   1846:                if (compat20 &&
                   1847:                    (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1.93      markus   1848:                        /* XXX is this true? */
1.140     markus   1849:                        debug3("channel %d: will not send data after close", c->self);
1.44      markus   1850:                        continue;
                   1851:                }
1.25      markus   1852:
                   1853:                /* Get the amount of buffered data for this channel. */
1.93      markus   1854:                if ((c->istate == CHAN_INPUT_OPEN ||
                   1855:                    c->istate == CHAN_INPUT_WAIT_DRAIN) &&
                   1856:                    (len = buffer_len(&c->input)) > 0) {
1.228     reyk     1857:                        if (c->datagram) {
                   1858:                                if (len > 0) {
                   1859:                                        u_char *data;
                   1860:                                        u_int dlen;
                   1861:
                   1862:                                        data = buffer_get_string(&c->input,
                   1863:                                            &dlen);
                   1864:                                        packet_start(SSH2_MSG_CHANNEL_DATA);
                   1865:                                        packet_put_int(c->remote_id);
                   1866:                                        packet_put_string(data, dlen);
                   1867:                                        packet_send();
                   1868:                                        c->remote_window -= dlen + 4;
                   1869:                                        xfree(data);
                   1870:                                }
                   1871:                                continue;
                   1872:                        }
1.121     markus   1873:                        /*
                   1874:                         * Send some data for the other side over the secure
                   1875:                         * connection.
                   1876:                         */
1.44      markus   1877:                        if (compat20) {
                   1878:                                if (len > c->remote_window)
                   1879:                                        len = c->remote_window;
                   1880:                                if (len > c->remote_maxpacket)
                   1881:                                        len = c->remote_maxpacket;
1.25      markus   1882:                        } else {
1.44      markus   1883:                                if (packet_is_interactive()) {
                   1884:                                        if (len > 1024)
                   1885:                                                len = 512;
                   1886:                                } else {
                   1887:                                        /* Keep the packets at reasonable size. */
                   1888:                                        if (len > packet_get_maxsize()/2)
                   1889:                                                len = packet_get_maxsize()/2;
                   1890:                                }
1.25      markus   1891:                        }
1.41      markus   1892:                        if (len > 0) {
1.44      markus   1893:                                packet_start(compat20 ?
                   1894:                                    SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1.41      markus   1895:                                packet_put_int(c->remote_id);
                   1896:                                packet_put_string(buffer_ptr(&c->input), len);
                   1897:                                packet_send();
                   1898:                                buffer_consume(&c->input, len);
                   1899:                                c->remote_window -= len;
                   1900:                        }
                   1901:                } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1.25      markus   1902:                        if (compat13)
                   1903:                                fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1.27      markus   1904:                        /*
                   1905:                         * input-buffer is empty and read-socket shutdown:
1.172     markus   1906:                         * tell peer, that we will not send more data: send IEOF.
                   1907:                         * hack for extended data: delay EOF if EFD still in use.
1.27      markus   1908:                         */
1.172     markus   1909:                        if (CHANNEL_EFD_INPUT_ACTIVE(c))
1.223     djm      1910:                                debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
                   1911:                                    c->self, c->efd, buffer_len(&c->extended));
1.172     markus   1912:                        else
                   1913:                                chan_ibuf_empty(c);
1.25      markus   1914:                }
1.44      markus   1915:                /* Send extended data, i.e. stderr */
                   1916:                if (compat20 &&
1.172     markus   1917:                    !(c->flags & CHAN_EOF_SENT) &&
1.44      markus   1918:                    c->remote_window > 0 &&
                   1919:                    (len = buffer_len(&c->extended)) > 0 &&
                   1920:                    c->extended_usage == CHAN_EXTENDED_READ) {
1.178     markus   1921:                        debug2("channel %d: rwin %u elen %u euse %d",
1.93      markus   1922:                            c->self, c->remote_window, buffer_len(&c->extended),
                   1923:                            c->extended_usage);
1.44      markus   1924:                        if (len > c->remote_window)
                   1925:                                len = c->remote_window;
                   1926:                        if (len > c->remote_maxpacket)
                   1927:                                len = c->remote_maxpacket;
                   1928:                        packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
                   1929:                        packet_put_int(c->remote_id);
                   1930:                        packet_put_int(SSH2_EXTENDED_DATA_STDERR);
                   1931:                        packet_put_string(buffer_ptr(&c->extended), len);
                   1932:                        packet_send();
                   1933:                        buffer_consume(&c->extended, len);
                   1934:                        c->remote_window -= len;
1.93      markus   1935:                        debug2("channel %d: sent ext data %d", c->self, len);
1.44      markus   1936:                }
1.25      markus   1937:        }
1.1       deraadt  1938: }
                   1939:
1.121     markus   1940:
                   1941: /* -- protocol input */
1.1       deraadt  1942:
1.49      markus   1943: void
1.154     markus   1944: channel_input_data(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  1945: {
1.37      markus   1946:        int id;
1.25      markus   1947:        char *data;
1.77      markus   1948:        u_int data_len;
1.41      markus   1949:        Channel *c;
1.25      markus   1950:
                   1951:        /* Get the channel number and verify it. */
1.37      markus   1952:        id = packet_get_int();
1.41      markus   1953:        c = channel_lookup(id);
                   1954:        if (c == NULL)
1.37      markus   1955:                packet_disconnect("Received data for nonexistent channel %d.", id);
1.25      markus   1956:
                   1957:        /* Ignore any data for non-open channels (might happen on close) */
1.41      markus   1958:        if (c->type != SSH_CHANNEL_OPEN &&
                   1959:            c->type != SSH_CHANNEL_X11_OPEN)
1.37      markus   1960:                return;
                   1961:
1.25      markus   1962:        /* Get the data. */
                   1963:        data = packet_get_string(&data_len);
1.200     markus   1964:
                   1965:        /*
                   1966:         * Ignore data for protocol > 1.3 if output end is no longer open.
                   1967:         * For protocol 2 the sending side is reducing its window as it sends
                   1968:         * data, so we must 'fake' consumption of the data in order to ensure
                   1969:         * that window updates are sent back.  Otherwise the connection might
                   1970:         * deadlock.
                   1971:         */
                   1972:        if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
                   1973:                if (compat20) {
                   1974:                        c->local_window -= data_len;
                   1975:                        c->local_consumed += data_len;
                   1976:                }
                   1977:                xfree(data);
                   1978:                return;
                   1979:        }
1.41      markus   1980:
1.143     deraadt  1981:        if (compat20) {
1.44      markus   1982:                if (data_len > c->local_maxpacket) {
1.188     itojun   1983:                        logit("channel %d: rcvd big packet %d, maxpack %d",
1.44      markus   1984:                            c->self, data_len, c->local_maxpacket);
                   1985:                }
                   1986:                if (data_len > c->local_window) {
1.188     itojun   1987:                        logit("channel %d: rcvd too much data %d, win %d",
1.44      markus   1988:                            c->self, data_len, c->local_window);
                   1989:                        xfree(data);
                   1990:                        return;
                   1991:                }
                   1992:                c->local_window -= data_len;
                   1993:        }
1.152     markus   1994:        packet_check_eom();
1.228     reyk     1995:        if (c->datagram)
                   1996:                buffer_put_string(&c->output, data, data_len);
                   1997:        else
                   1998:                buffer_append(&c->output, data, data_len);
1.25      markus   1999:        xfree(data);
1.1       deraadt  2000: }
1.121     markus   2001:
1.49      markus   2002: void
1.154     markus   2003: channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
1.44      markus   2004: {
                   2005:        int id;
                   2006:        char *data;
1.177     markus   2007:        u_int data_len, tcode;
1.44      markus   2008:        Channel *c;
                   2009:
                   2010:        /* Get the channel number and verify it. */
                   2011:        id = packet_get_int();
                   2012:        c = channel_lookup(id);
                   2013:
                   2014:        if (c == NULL)
                   2015:                packet_disconnect("Received extended_data for bad channel %d.", id);
                   2016:        if (c->type != SSH_CHANNEL_OPEN) {
1.188     itojun   2017:                logit("channel %d: ext data for non open", id);
1.44      markus   2018:                return;
1.172     markus   2019:        }
                   2020:        if (c->flags & CHAN_EOF_RCVD) {
                   2021:                if (datafellows & SSH_BUG_EXTEOF)
                   2022:                        debug("channel %d: accepting ext data after eof", id);
                   2023:                else
                   2024:                        packet_disconnect("Received extended_data after EOF "
                   2025:                            "on channel %d.", id);
1.44      markus   2026:        }
                   2027:        tcode = packet_get_int();
                   2028:        if (c->efd == -1 ||
                   2029:            c->extended_usage != CHAN_EXTENDED_WRITE ||
                   2030:            tcode != SSH2_EXTENDED_DATA_STDERR) {
1.188     itojun   2031:                logit("channel %d: bad ext data", c->self);
1.44      markus   2032:                return;
                   2033:        }
                   2034:        data = packet_get_string(&data_len);
1.152     markus   2035:        packet_check_eom();
1.44      markus   2036:        if (data_len > c->local_window) {
1.188     itojun   2037:                logit("channel %d: rcvd too much extended_data %d, win %d",
1.44      markus   2038:                    c->self, data_len, c->local_window);
                   2039:                xfree(data);
                   2040:                return;
                   2041:        }
1.70      markus   2042:        debug2("channel %d: rcvd ext data %d", c->self, data_len);
1.44      markus   2043:        c->local_window -= data_len;
                   2044:        buffer_append(&c->extended, data, data_len);
                   2045:        xfree(data);
                   2046: }
                   2047:
1.49      markus   2048: void
1.154     markus   2049: channel_input_ieof(int type, u_int32_t seq, void *ctxt)
1.41      markus   2050: {
                   2051:        int id;
                   2052:        Channel *c;
                   2053:
                   2054:        id = packet_get_int();
1.152     markus   2055:        packet_check_eom();
1.41      markus   2056:        c = channel_lookup(id);
                   2057:        if (c == NULL)
                   2058:                packet_disconnect("Received ieof for nonexistent channel %d.", id);
                   2059:        chan_rcvd_ieof(c);
1.133     markus   2060:
                   2061:        /* XXX force input close */
1.156     markus   2062:        if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
1.133     markus   2063:                debug("channel %d: FORCE input drain", c->self);
                   2064:                c->istate = CHAN_INPUT_WAIT_DRAIN;
1.161     markus   2065:                if (buffer_len(&c->input) == 0)
                   2066:                        chan_ibuf_empty(c);
1.133     markus   2067:        }
                   2068:
1.41      markus   2069: }
1.1       deraadt  2070:
1.49      markus   2071: void
1.154     markus   2072: channel_input_close(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2073: {
1.41      markus   2074:        int id;
                   2075:        Channel *c;
1.1       deraadt  2076:
1.41      markus   2077:        id = packet_get_int();
1.152     markus   2078:        packet_check_eom();
1.41      markus   2079:        c = channel_lookup(id);
                   2080:        if (c == NULL)
                   2081:                packet_disconnect("Received close for nonexistent channel %d.", id);
1.27      markus   2082:
                   2083:        /*
                   2084:         * Send a confirmation that we have closed the channel and no more
                   2085:         * data is coming for it.
                   2086:         */
1.25      markus   2087:        packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1.41      markus   2088:        packet_put_int(c->remote_id);
1.25      markus   2089:        packet_send();
                   2090:
1.27      markus   2091:        /*
                   2092:         * If the channel is in closed state, we have sent a close request,
                   2093:         * and the other side will eventually respond with a confirmation.
                   2094:         * Thus, we cannot free the channel here, because then there would be
                   2095:         * no-one to receive the confirmation.  The channel gets freed when
                   2096:         * the confirmation arrives.
                   2097:         */
1.41      markus   2098:        if (c->type != SSH_CHANNEL_CLOSED) {
1.27      markus   2099:                /*
                   2100:                 * Not a closed channel - mark it as draining, which will
                   2101:                 * cause it to be freed later.
                   2102:                 */
1.158     markus   2103:                buffer_clear(&c->input);
1.41      markus   2104:                c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1.25      markus   2105:        }
1.1       deraadt  2106: }
                   2107:
1.41      markus   2108: /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1.49      markus   2109: void
1.154     markus   2110: channel_input_oclose(int type, u_int32_t seq, void *ctxt)
1.41      markus   2111: {
                   2112:        int id = packet_get_int();
                   2113:        Channel *c = channel_lookup(id);
1.151     markus   2114:
1.152     markus   2115:        packet_check_eom();
1.41      markus   2116:        if (c == NULL)
                   2117:                packet_disconnect("Received oclose for nonexistent channel %d.", id);
                   2118:        chan_rcvd_oclose(c);
                   2119: }
1.1       deraadt  2120:
1.49      markus   2121: void
1.154     markus   2122: channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2123: {
1.41      markus   2124:        int id = packet_get_int();
                   2125:        Channel *c = channel_lookup(id);
1.1       deraadt  2126:
1.152     markus   2127:        packet_check_eom();
1.41      markus   2128:        if (c == NULL)
                   2129:                packet_disconnect("Received close confirmation for "
                   2130:                    "out-of-range channel %d.", id);
                   2131:        if (c->type != SSH_CHANNEL_CLOSED)
                   2132:                packet_disconnect("Received close confirmation for "
                   2133:                    "non-closed channel %d (type %d).", id, c->type);
1.113     markus   2134:        channel_free(c);
1.1       deraadt  2135: }
                   2136:
1.49      markus   2137: void
1.154     markus   2138: channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2139: {
1.41      markus   2140:        int id, remote_id;
                   2141:        Channel *c;
1.1       deraadt  2142:
1.41      markus   2143:        id = packet_get_int();
                   2144:        c = channel_lookup(id);
1.25      markus   2145:
1.41      markus   2146:        if (c==NULL || c->type != SSH_CHANNEL_OPENING)
                   2147:                packet_disconnect("Received open confirmation for "
                   2148:                    "non-opening channel %d.", id);
                   2149:        remote_id = packet_get_int();
1.27      markus   2150:        /* Record the remote channel number and mark that the channel is now open. */
1.41      markus   2151:        c->remote_id = remote_id;
                   2152:        c->type = SSH_CHANNEL_OPEN;
1.44      markus   2153:
                   2154:        if (compat20) {
                   2155:                c->remote_window = packet_get_int();
                   2156:                c->remote_maxpacket = packet_get_int();
1.165     markus   2157:                if (c->confirm) {
1.70      markus   2158:                        debug2("callback start");
1.204     djm      2159:                        c->confirm(c->self, c->confirm_ctx);
1.70      markus   2160:                        debug2("callback done");
1.44      markus   2161:                }
1.194     markus   2162:                debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
1.44      markus   2163:                    c->remote_window, c->remote_maxpacket);
                   2164:        }
1.152     markus   2165:        packet_check_eom();
1.1       deraadt  2166: }
                   2167:
1.127     itojun   2168: static char *
1.114     markus   2169: reason2txt(int reason)
                   2170: {
1.143     deraadt  2171:        switch (reason) {
1.114     markus   2172:        case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
                   2173:                return "administratively prohibited";
                   2174:        case SSH2_OPEN_CONNECT_FAILED:
                   2175:                return "connect failed";
                   2176:        case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
                   2177:                return "unknown channel type";
                   2178:        case SSH2_OPEN_RESOURCE_SHORTAGE:
                   2179:                return "resource shortage";
                   2180:        }
1.117     stevesk  2181:        return "unknown reason";
1.114     markus   2182: }
                   2183:
1.49      markus   2184: void
1.154     markus   2185: channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2186: {
1.86      markus   2187:        int id, reason;
                   2188:        char *msg = NULL, *lang = NULL;
1.41      markus   2189:        Channel *c;
                   2190:
                   2191:        id = packet_get_int();
                   2192:        c = channel_lookup(id);
1.25      markus   2193:
1.41      markus   2194:        if (c==NULL || c->type != SSH_CHANNEL_OPENING)
                   2195:                packet_disconnect("Received open failure for "
                   2196:                    "non-opening channel %d.", id);
1.44      markus   2197:        if (compat20) {
1.86      markus   2198:                reason = packet_get_int();
1.110     markus   2199:                if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1.86      markus   2200:                        msg  = packet_get_string(NULL);
                   2201:                        lang = packet_get_string(NULL);
                   2202:                }
1.188     itojun   2203:                logit("channel %d: open failed: %s%s%s", id,
1.114     markus   2204:                    reason2txt(reason), msg ? ": ": "", msg ? msg : "");
1.86      markus   2205:                if (msg != NULL)
                   2206:                        xfree(msg);
                   2207:                if (lang != NULL)
                   2208:                        xfree(lang);
1.44      markus   2209:        }
1.152     markus   2210:        packet_check_eom();
1.25      markus   2211:        /* Free the channel.  This will also close the socket. */
1.113     markus   2212:        channel_free(c);
1.44      markus   2213: }
                   2214:
1.121     markus   2215: void
1.154     markus   2216: channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
1.121     markus   2217: {
                   2218:        Channel *c;
1.178     markus   2219:        int id;
                   2220:        u_int adjust;
1.121     markus   2221:
                   2222:        if (!compat20)
                   2223:                return;
                   2224:
                   2225:        /* Get the channel number and verify it. */
                   2226:        id = packet_get_int();
                   2227:        c = channel_lookup(id);
1.1       deraadt  2228:
1.229     markus   2229:        if (c == NULL) {
                   2230:                logit("Received window adjust for non-open channel %d.", id);
1.121     markus   2231:                return;
                   2232:        }
                   2233:        adjust = packet_get_int();
1.152     markus   2234:        packet_check_eom();
1.178     markus   2235:        debug2("channel %d: rcvd adjust %u", id, adjust);
1.121     markus   2236:        c->remote_window += adjust;
                   2237: }
1.1       deraadt  2238:
1.121     markus   2239: void
1.154     markus   2240: channel_input_port_open(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2241: {
1.121     markus   2242:        Channel *c = NULL;
                   2243:        u_short host_port;
                   2244:        char *host, *originator_string;
                   2245:        int remote_id, sock = -1;
                   2246:
                   2247:        remote_id = packet_get_int();
                   2248:        host = packet_get_string(NULL);
                   2249:        host_port = packet_get_int();
1.25      markus   2250:
1.121     markus   2251:        if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
                   2252:                originator_string = packet_get_string(NULL);
                   2253:        } else {
                   2254:                originator_string = xstrdup("unknown (remote did not supply name)");
                   2255:        }
1.152     markus   2256:        packet_check_eom();
1.121     markus   2257:        sock = channel_connect_to(host, host_port);
                   2258:        if (sock != -1) {
                   2259:                c = channel_new("connected socket",
                   2260:                    SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
                   2261:                    originator_string, 1);
1.167     markus   2262:                c->remote_id = remote_id;
1.25      markus   2263:        }
1.190     markus   2264:        xfree(originator_string);
1.121     markus   2265:        if (c == NULL) {
                   2266:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   2267:                packet_put_int(remote_id);
                   2268:                packet_send();
                   2269:        }
                   2270:        xfree(host);
1.1       deraadt  2271: }
                   2272:
1.121     markus   2273:
                   2274: /* -- tcp forwarding */
1.135     markus   2275:
                   2276: void
                   2277: channel_set_af(int af)
                   2278: {
                   2279:        IPv4or6 = af;
                   2280: }
1.121     markus   2281:
1.160     markus   2282: static int
                   2283: channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port,
                   2284:     const char *host_to_connect, u_short port_to_connect, int gateway_ports)
1.25      markus   2285: {
1.113     markus   2286:        Channel *c;
1.226     djm      2287:        int sock, r, success = 0, wildcard = 0, is_client;
1.35      markus   2288:        struct addrinfo hints, *ai, *aitop;
1.212     djm      2289:        const char *host, *addr;
1.35      markus   2290:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1.25      markus   2291:
1.160     markus   2292:        host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
                   2293:            listen_addr : host_to_connect;
1.212     djm      2294:        is_client = (type == SSH_CHANNEL_PORT_LISTENER);
1.87      markus   2295:
1.160     markus   2296:        if (host == NULL) {
                   2297:                error("No forward host name.");
1.218     markus   2298:                return 0;
1.73      markus   2299:        }
1.113     markus   2300:        if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
1.87      markus   2301:                error("Forward host name too long.");
1.218     markus   2302:                return 0;
1.87      markus   2303:        }
1.25      markus   2304:
1.28      markus   2305:        /*
1.212     djm      2306:         * Determine whether or not a port forward listens to loopback,
1.213     deraadt  2307:         * specified address or wildcard. On the client, a specified bind
                   2308:         * address will always override gateway_ports. On the server, a
                   2309:         * gateway_ports of 1 (``yes'') will override the client's
                   2310:         * specification and force a wildcard bind, whereas a value of 2
                   2311:         * (``clientspecified'') will bind to whatever address the client
1.212     djm      2312:         * asked for.
                   2313:         *
                   2314:         * Special-case listen_addrs are:
                   2315:         *
                   2316:         * "0.0.0.0"               -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
                   2317:         * "" (empty string), "*"  -> wildcard v4/v6
                   2318:         * "localhost"             -> loopback v4/v6
                   2319:         */
                   2320:        addr = NULL;
                   2321:        if (listen_addr == NULL) {
                   2322:                /* No address specified: default to gateway_ports setting */
                   2323:                if (gateway_ports)
                   2324:                        wildcard = 1;
                   2325:        } else if (gateway_ports || is_client) {
                   2326:                if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
                   2327:                    strcmp(listen_addr, "0.0.0.0") == 0) ||
                   2328:                    *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
                   2329:                    (!is_client && gateway_ports == 1))
                   2330:                        wildcard = 1;
                   2331:                else if (strcmp(listen_addr, "localhost") != 0)
                   2332:                        addr = listen_addr;
                   2333:        }
                   2334:
                   2335:        debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
                   2336:            type, wildcard, (addr == NULL) ? "NULL" : addr);
                   2337:
                   2338:        /*
1.35      markus   2339:         * getaddrinfo returns a loopback address if the hostname is
                   2340:         * set to NULL and hints.ai_flags is not AI_PASSIVE
1.28      markus   2341:         */
1.35      markus   2342:        memset(&hints, 0, sizeof(hints));
                   2343:        hints.ai_family = IPv4or6;
1.212     djm      2344:        hints.ai_flags = wildcard ? AI_PASSIVE : 0;
1.35      markus   2345:        hints.ai_socktype = SOCK_STREAM;
1.73      markus   2346:        snprintf(strport, sizeof strport, "%d", listen_port);
1.212     djm      2347:        if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
                   2348:                if (addr == NULL) {
                   2349:                        /* This really shouldn't happen */
                   2350:                        packet_disconnect("getaddrinfo: fatal error: %s",
                   2351:                            gai_strerror(r));
                   2352:                } else {
1.218     markus   2353:                        error("channel_setup_fwd_listener: "
1.212     djm      2354:                            "getaddrinfo(%.64s): %s", addr, gai_strerror(r));
                   2355:                }
1.218     markus   2356:                return 0;
1.212     djm      2357:        }
1.35      markus   2358:
                   2359:        for (ai = aitop; ai; ai = ai->ai_next) {
                   2360:                if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   2361:                        continue;
                   2362:                if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
                   2363:                    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1.160     markus   2364:                        error("channel_setup_fwd_listener: getnameinfo failed");
1.35      markus   2365:                        continue;
                   2366:                }
                   2367:                /* Create a port to listen for the host. */
1.189     markus   2368:                sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1.35      markus   2369:                if (sock < 0) {
                   2370:                        /* this is no error since kernel may not support ipv6 */
                   2371:                        verbose("socket: %.100s", strerror(errno));
                   2372:                        continue;
                   2373:                }
1.226     djm      2374:
                   2375:                channel_set_reuseaddr(sock);
1.182     stevesk  2376:
1.35      markus   2377:                debug("Local forwarding listening on %s port %s.", ntop, strport);
                   2378:
                   2379:                /* Bind the socket to the address. */
                   2380:                if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   2381:                        /* address can be in use ipv6 address is already bound */
                   2382:                        verbose("bind: %.100s", strerror(errno));
                   2383:                        close(sock);
                   2384:                        continue;
                   2385:                }
                   2386:                /* Start listening for connections on the socket. */
1.199     markus   2387:                if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1.35      markus   2388:                        error("listen: %.100s", strerror(errno));
                   2389:                        close(sock);
                   2390:                        continue;
                   2391:                }
                   2392:                /* Allocate a channel number for the socket. */
1.121     markus   2393:                c = channel_new("port listener", type, sock, sock, -1,
1.51      markus   2394:                    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1.190     markus   2395:                    0, "port listener", 1);
1.113     markus   2396:                strlcpy(c->path, host, sizeof(c->path));
                   2397:                c->host_port = port_to_connect;
                   2398:                c->listening_port = listen_port;
1.35      markus   2399:                success = 1;
                   2400:        }
                   2401:        if (success == 0)
1.160     markus   2402:                error("channel_setup_fwd_listener: cannot listen to port: %d",
1.87      markus   2403:                    listen_port);
1.35      markus   2404:        freeaddrinfo(aitop);
1.87      markus   2405:        return success;
1.25      markus   2406: }
1.1       deraadt  2407:
1.202     djm      2408: int
                   2409: channel_cancel_rport_listener(const char *host, u_short port)
                   2410: {
1.209     avsm     2411:        u_int i;
                   2412:        int found = 0;
1.202     djm      2413:
1.213     deraadt  2414:        for (i = 0; i < channels_alloc; i++) {
1.202     djm      2415:                Channel *c = channels[i];
                   2416:
                   2417:                if (c != NULL && c->type == SSH_CHANNEL_RPORT_LISTENER &&
                   2418:                    strncmp(c->path, host, sizeof(c->path)) == 0 &&
1.208     deraadt  2419:                    c->listening_port == port) {
1.210     djm      2420:                        debug2("%s: close channel %d", __func__, i);
1.202     djm      2421:                        channel_free(c);
                   2422:                        found = 1;
                   2423:                }
                   2424:        }
                   2425:
                   2426:        return (found);
                   2427: }
                   2428:
1.160     markus   2429: /* protocol local port fwd, used by ssh (and sshd in v1) */
                   2430: int
1.212     djm      2431: channel_setup_local_fwd_listener(const char *listen_host, u_short listen_port,
1.160     markus   2432:     const char *host_to_connect, u_short port_to_connect, int gateway_ports)
                   2433: {
                   2434:        return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
1.212     djm      2435:            listen_host, listen_port, host_to_connect, port_to_connect,
                   2436:            gateway_ports);
1.160     markus   2437: }
                   2438:
                   2439: /* protocol v2 remote port fwd, used by sshd */
                   2440: int
                   2441: channel_setup_remote_fwd_listener(const char *listen_address,
                   2442:     u_short listen_port, int gateway_ports)
                   2443: {
                   2444:        return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
                   2445:            listen_address, listen_port, NULL, 0, gateway_ports);
                   2446: }
                   2447:
1.27      markus   2448: /*
                   2449:  * Initiate forwarding of connections to port "port" on remote host through
                   2450:  * the secure channel to host:port from local side.
                   2451:  */
1.1       deraadt  2452:
1.49      markus   2453: void
1.212     djm      2454: channel_request_remote_forwarding(const char *listen_host, u_short listen_port,
1.73      markus   2455:     const char *host_to_connect, u_short port_to_connect)
1.25      markus   2456: {
1.153     markus   2457:        int type, success = 0;
1.73      markus   2458:
1.25      markus   2459:        /* Record locally that connection to this host/port is permitted. */
                   2460:        if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
                   2461:                fatal("channel_request_remote_forwarding: too many forwards");
                   2462:
                   2463:        /* Send the forward request to the remote side. */
1.44      markus   2464:        if (compat20) {
1.212     djm      2465:                const char *address_to_bind;
                   2466:                if (listen_host == NULL)
                   2467:                        address_to_bind = "localhost";
                   2468:                else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0)
                   2469:                        address_to_bind = "";
                   2470:                else
                   2471:                        address_to_bind = listen_host;
                   2472:
1.44      markus   2473:                packet_start(SSH2_MSG_GLOBAL_REQUEST);
                   2474:                packet_put_cstring("tcpip-forward");
1.173     markus   2475:                packet_put_char(1);                     /* boolean: want reply */
1.44      markus   2476:                packet_put_cstring(address_to_bind);
                   2477:                packet_put_int(listen_port);
1.73      markus   2478:                packet_send();
                   2479:                packet_write_wait();
                   2480:                /* Assume that server accepts the request */
                   2481:                success = 1;
1.44      markus   2482:        } else {
                   2483:                packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1.50      markus   2484:                packet_put_int(listen_port);
                   2485:                packet_put_cstring(host_to_connect);
1.44      markus   2486:                packet_put_int(port_to_connect);
                   2487:                packet_send();
                   2488:                packet_write_wait();
1.73      markus   2489:
                   2490:                /* Wait for response from the remote side. */
1.153     markus   2491:                type = packet_read();
1.73      markus   2492:                switch (type) {
                   2493:                case SSH_SMSG_SUCCESS:
                   2494:                        success = 1;
                   2495:                        break;
                   2496:                case SSH_SMSG_FAILURE:
1.188     itojun   2497:                        logit("Warning: Server denied remote port forwarding.");
1.73      markus   2498:                        break;
                   2499:                default:
                   2500:                        /* Unknown packet */
                   2501:                        packet_disconnect("Protocol error for port forward request:"
                   2502:                            "received packet type %d.", type);
                   2503:                }
                   2504:        }
                   2505:        if (success) {
                   2506:                permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
                   2507:                permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
                   2508:                permitted_opens[num_permitted_opens].listen_port = listen_port;
                   2509:                num_permitted_opens++;
1.44      markus   2510:        }
1.1       deraadt  2511: }
                   2512:
1.27      markus   2513: /*
1.208     deraadt  2514:  * Request cancellation of remote forwarding of connection host:port from
1.202     djm      2515:  * local side.
                   2516:  */
                   2517: void
1.212     djm      2518: channel_request_rforward_cancel(const char *host, u_short port)
1.202     djm      2519: {
                   2520:        int i;
                   2521:
                   2522:        if (!compat20)
                   2523:                return;
                   2524:
                   2525:        for (i = 0; i < num_permitted_opens; i++) {
1.208     deraadt  2526:                if (permitted_opens[i].host_to_connect != NULL &&
1.202     djm      2527:                    permitted_opens[i].listen_port == port)
                   2528:                        break;
                   2529:        }
                   2530:        if (i >= num_permitted_opens) {
                   2531:                debug("%s: requested forward not found", __func__);
                   2532:                return;
                   2533:        }
                   2534:        packet_start(SSH2_MSG_GLOBAL_REQUEST);
                   2535:        packet_put_cstring("cancel-tcpip-forward");
                   2536:        packet_put_char(0);
1.212     djm      2537:        packet_put_cstring(host == NULL ? "" : host);
1.202     djm      2538:        packet_put_int(port);
                   2539:        packet_send();
                   2540:
                   2541:        permitted_opens[i].listen_port = 0;
                   2542:        permitted_opens[i].port_to_connect = 0;
1.227     stevesk  2543:        xfree(permitted_opens[i].host_to_connect);
1.202     djm      2544:        permitted_opens[i].host_to_connect = NULL;
                   2545: }
                   2546:
                   2547: /*
1.27      markus   2548:  * This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
                   2549:  * listening for the port, and sends back a success reply (or disconnect
                   2550:  * message if there was an error).  This never returns if there was an error.
                   2551:  */
1.1       deraadt  2552:
1.49      markus   2553: void
1.56      markus   2554: channel_input_port_forward_request(int is_root, int gateway_ports)
1.1       deraadt  2555: {
1.31      markus   2556:        u_short port, host_port;
1.25      markus   2557:        char *hostname;
1.1       deraadt  2558:
1.25      markus   2559:        /* Get arguments from the packet. */
                   2560:        port = packet_get_int();
                   2561:        hostname = packet_get_string(NULL);
                   2562:        host_port = packet_get_int();
                   2563:
1.27      markus   2564:        /*
                   2565:         * Check that an unprivileged user is not trying to forward a
                   2566:         * privileged port.
                   2567:         */
1.25      markus   2568:        if (port < IPPORT_RESERVED && !is_root)
1.192     markus   2569:                packet_disconnect(
                   2570:                    "Requested forwarding of port %d but user is not root.",
                   2571:                    port);
                   2572:        if (host_port == 0)
                   2573:                packet_disconnect("Dynamic forwarding denied.");
                   2574:
1.73      markus   2575:        /* Initiate forwarding */
1.212     djm      2576:        channel_setup_local_fwd_listener(NULL, port, hostname,
                   2577:            host_port, gateway_ports);
1.25      markus   2578:
                   2579:        /* Free the argument string. */
                   2580:        xfree(hostname);
1.1       deraadt  2581: }
                   2582:
1.99      markus   2583: /*
                   2584:  * Permits opening to any host/port if permitted_opens[] is empty.  This is
                   2585:  * usually called by the server, because the user could connect to any port
                   2586:  * anyway, and the server has no way to know but to trust the client anyway.
                   2587:  */
                   2588: void
1.142     itojun   2589: channel_permit_all_opens(void)
1.99      markus   2590: {
                   2591:        if (num_permitted_opens == 0)
                   2592:                all_opens_permitted = 1;
                   2593: }
                   2594:
1.101     markus   2595: void
1.99      markus   2596: channel_add_permitted_opens(char *host, int port)
                   2597: {
                   2598:        if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
                   2599:                fatal("channel_request_remote_forwarding: too many forwards");
                   2600:        debug("allow port forwarding to host %s port %d", host, port);
                   2601:
                   2602:        permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
                   2603:        permitted_opens[num_permitted_opens].port_to_connect = port;
                   2604:        num_permitted_opens++;
                   2605:
                   2606:        all_opens_permitted = 0;
                   2607: }
                   2608:
1.101     markus   2609: void
1.99      markus   2610: channel_clear_permitted_opens(void)
                   2611: {
                   2612:        int i;
                   2613:
                   2614:        for (i = 0; i < num_permitted_opens; i++)
1.202     djm      2615:                if (permitted_opens[i].host_to_connect != NULL)
                   2616:                        xfree(permitted_opens[i].host_to_connect);
1.99      markus   2617:        num_permitted_opens = 0;
                   2618:
                   2619: }
                   2620:
                   2621:
                   2622: /* return socket to remote host, port */
1.127     itojun   2623: static int
1.99      markus   2624: connect_to(const char *host, u_short port)
1.41      markus   2625: {
                   2626:        struct addrinfo hints, *ai, *aitop;
                   2627:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
                   2628:        int gaierr;
                   2629:        int sock = -1;
                   2630:
                   2631:        memset(&hints, 0, sizeof(hints));
                   2632:        hints.ai_family = IPv4or6;
                   2633:        hints.ai_socktype = SOCK_STREAM;
1.99      markus   2634:        snprintf(strport, sizeof strport, "%d", port);
1.41      markus   2635:        if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
1.99      markus   2636:                error("connect_to %.100s: unknown host (%s)", host,
                   2637:                    gai_strerror(gaierr));
1.41      markus   2638:                return -1;
                   2639:        }
                   2640:        for (ai = aitop; ai; ai = ai->ai_next) {
                   2641:                if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   2642:                        continue;
                   2643:                if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
                   2644:                    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1.99      markus   2645:                        error("connect_to: getnameinfo failed");
1.41      markus   2646:                        continue;
                   2647:                }
1.189     markus   2648:                sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1.41      markus   2649:                if (sock < 0) {
1.186     djm      2650:                        if (ai->ai_next == NULL)
                   2651:                                error("socket: %.100s", strerror(errno));
                   2652:                        else
                   2653:                                verbose("socket: %.100s", strerror(errno));
1.41      markus   2654:                        continue;
                   2655:                }
1.205     djm      2656:                if (set_nonblock(sock) == -1)
                   2657:                        fatal("%s: set_nonblock(%d)", __func__, sock);
1.75      markus   2658:                if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
                   2659:                    errno != EINPROGRESS) {
1.99      markus   2660:                        error("connect_to %.100s port %s: %.100s", ntop, strport,
1.41      markus   2661:                            strerror(errno));
                   2662:                        close(sock);
1.89      stevesk  2663:                        continue;       /* fail -- try next */
1.41      markus   2664:                }
                   2665:                break; /* success */
                   2666:
                   2667:        }
                   2668:        freeaddrinfo(aitop);
                   2669:        if (!ai) {
1.99      markus   2670:                error("connect_to %.100s port %d: failed.", host, port);
1.41      markus   2671:                return -1;
                   2672:        }
                   2673:        /* success */
1.169     stevesk  2674:        set_nodelay(sock);
1.41      markus   2675:        return sock;
                   2676: }
1.99      markus   2677:
1.73      markus   2678: int
1.130     stevesk  2679: channel_connect_by_listen_address(u_short listen_port)
1.73      markus   2680: {
                   2681:        int i;
1.99      markus   2682:
1.73      markus   2683:        for (i = 0; i < num_permitted_opens; i++)
1.202     djm      2684:                if (permitted_opens[i].host_to_connect != NULL &&
                   2685:                    permitted_opens[i].listen_port == listen_port)
1.99      markus   2686:                        return connect_to(
1.73      markus   2687:                            permitted_opens[i].host_to_connect,
                   2688:                            permitted_opens[i].port_to_connect);
1.74      markus   2689:        error("WARNING: Server requests forwarding for unknown listen_port %d",
                   2690:            listen_port);
1.73      markus   2691:        return -1;
                   2692: }
                   2693:
1.99      markus   2694: /* Check if connecting to that port is permitted and connect. */
                   2695: int
                   2696: channel_connect_to(const char *host, u_short port)
                   2697: {
                   2698:        int i, permit;
                   2699:
                   2700:        permit = all_opens_permitted;
                   2701:        if (!permit) {
                   2702:                for (i = 0; i < num_permitted_opens; i++)
1.202     djm      2703:                        if (permitted_opens[i].host_to_connect != NULL &&
                   2704:                            permitted_opens[i].port_to_connect == port &&
1.99      markus   2705:                            strcmp(permitted_opens[i].host_to_connect, host) == 0)
                   2706:                                permit = 1;
                   2707:
                   2708:        }
                   2709:        if (!permit) {
1.188     itojun   2710:                logit("Received request to connect to host %.100s port %d, "
1.99      markus   2711:                    "but the request was denied.", host, port);
                   2712:                return -1;
                   2713:        }
                   2714:        return connect_to(host, port);
1.204     djm      2715: }
                   2716:
                   2717: void
                   2718: channel_send_window_changes(void)
                   2719: {
1.209     avsm     2720:        u_int i;
1.204     djm      2721:        struct winsize ws;
                   2722:
                   2723:        for (i = 0; i < channels_alloc; i++) {
1.213     deraadt  2724:                if (channels[i] == NULL || !channels[i]->client_tty ||
1.204     djm      2725:                    channels[i]->type != SSH_CHANNEL_OPEN)
                   2726:                        continue;
                   2727:                if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
                   2728:                        continue;
                   2729:                channel_request_start(i, "window-change", 0);
                   2730:                packet_put_int(ws.ws_col);
                   2731:                packet_put_int(ws.ws_row);
                   2732:                packet_put_int(ws.ws_xpixel);
                   2733:                packet_put_int(ws.ws_ypixel);
                   2734:                packet_send();
                   2735:        }
1.99      markus   2736: }
                   2737:
1.121     markus   2738: /* -- X11 forwarding */
1.1       deraadt  2739:
1.27      markus   2740: /*
                   2741:  * Creates an internet domain socket for listening for X11 connections.
1.176     deraadt  2742:  * Returns 0 and a suitable display number for the DISPLAY variable
                   2743:  * stored in display_numberp , or -1 if an error occurs.
1.27      markus   2744:  */
1.141     stevesk  2745: int
1.163     stevesk  2746: x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
1.222     djm      2747:     int single_connection, u_int *display_numberp, int **chanids)
1.1       deraadt  2748: {
1.149     markus   2749:        Channel *nc = NULL;
1.31      markus   2750:        int display_number, sock;
                   2751:        u_short port;
1.35      markus   2752:        struct addrinfo hints, *ai, *aitop;
                   2753:        char strport[NI_MAXSERV];
                   2754:        int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
1.25      markus   2755:
1.224     markus   2756:        if (chanids == NULL)
                   2757:                return -1;
                   2758:
1.33      markus   2759:        for (display_number = x11_display_offset;
1.148     deraadt  2760:            display_number < MAX_DISPLAYS;
                   2761:            display_number++) {
1.25      markus   2762:                port = 6000 + display_number;
1.35      markus   2763:                memset(&hints, 0, sizeof(hints));
                   2764:                hints.ai_family = IPv4or6;
1.163     stevesk  2765:                hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
1.35      markus   2766:                hints.ai_socktype = SOCK_STREAM;
                   2767:                snprintf(strport, sizeof strport, "%d", port);
                   2768:                if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
                   2769:                        error("getaddrinfo: %.100s", gai_strerror(gaierr));
1.141     stevesk  2770:                        return -1;
1.25      markus   2771:                }
1.35      markus   2772:                for (ai = aitop; ai; ai = ai->ai_next) {
                   2773:                        if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   2774:                                continue;
1.189     markus   2775:                        sock = socket(ai->ai_family, ai->ai_socktype,
                   2776:                            ai->ai_protocol);
1.35      markus   2777:                        if (sock < 0) {
                   2778:                                error("socket: %.100s", strerror(errno));
1.203     markus   2779:                                freeaddrinfo(aitop);
1.141     stevesk  2780:                                return -1;
1.35      markus   2781:                        }
1.226     djm      2782:                        channel_set_reuseaddr(sock);
1.35      markus   2783:                        if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1.194     markus   2784:                                debug2("bind port %d: %.100s", port, strerror(errno));
1.35      markus   2785:                                close(sock);
1.183     itojun   2786:
                   2787:                                if (ai->ai_next)
                   2788:                                        continue;
                   2789:
1.35      markus   2790:                                for (n = 0; n < num_socks; n++) {
                   2791:                                        close(socks[n]);
                   2792:                                }
                   2793:                                num_socks = 0;
                   2794:                                break;
                   2795:                        }
                   2796:                        socks[num_socks++] = sock;
                   2797:                        if (num_socks == NUM_SOCKS)
                   2798:                                break;
1.25      markus   2799:                }
1.83      stevesk  2800:                freeaddrinfo(aitop);
1.35      markus   2801:                if (num_socks > 0)
                   2802:                        break;
1.25      markus   2803:        }
                   2804:        if (display_number >= MAX_DISPLAYS) {
                   2805:                error("Failed to allocate internet-domain X11 display socket.");
1.141     stevesk  2806:                return -1;
1.25      markus   2807:        }
                   2808:        /* Start listening for connections on the socket. */
1.35      markus   2809:        for (n = 0; n < num_socks; n++) {
                   2810:                sock = socks[n];
1.199     markus   2811:                if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1.35      markus   2812:                        error("listen: %.100s", strerror(errno));
                   2813:                        close(sock);
1.141     stevesk  2814:                        return -1;
1.35      markus   2815:                }
1.25      markus   2816:        }
1.35      markus   2817:
                   2818:        /* Allocate a channel for each socket. */
1.224     markus   2819:        *chanids = xmalloc(sizeof(**chanids) * (num_socks + 1));
1.35      markus   2820:        for (n = 0; n < num_socks; n++) {
                   2821:                sock = socks[n];
1.149     markus   2822:                nc = channel_new("x11 listener",
1.51      markus   2823:                    SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
                   2824:                    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
1.190     markus   2825:                    0, "X11 inet listener", 1);
1.167     markus   2826:                nc->single_connection = single_connection;
1.224     markus   2827:                (*chanids)[n] = nc->self;
1.35      markus   2828:        }
1.224     markus   2829:        (*chanids)[n] = -1;
1.1       deraadt  2830:
1.141     stevesk  2831:        /* Return the display number for the DISPLAY environment variable. */
1.176     deraadt  2832:        *display_numberp = display_number;
                   2833:        return (0);
1.1       deraadt  2834: }
                   2835:
1.127     itojun   2836: static int
1.77      markus   2837: connect_local_xsocket(u_int dnr)
1.1       deraadt  2838: {
1.25      markus   2839:        int sock;
                   2840:        struct sockaddr_un addr;
                   2841:
1.147     stevesk  2842:        sock = socket(AF_UNIX, SOCK_STREAM, 0);
                   2843:        if (sock < 0)
                   2844:                error("socket: %.100s", strerror(errno));
                   2845:        memset(&addr, 0, sizeof(addr));
                   2846:        addr.sun_family = AF_UNIX;
                   2847:        snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
                   2848:        if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
                   2849:                return sock;
                   2850:        close(sock);
1.25      markus   2851:        error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
                   2852:        return -1;
1.1       deraadt  2853: }
                   2854:
1.51      markus   2855: int
                   2856: x11_connect_display(void)
1.1       deraadt  2857: {
1.162     stevesk  2858:        int display_number, sock = 0;
1.25      markus   2859:        const char *display;
1.51      markus   2860:        char buf[1024], *cp;
1.35      markus   2861:        struct addrinfo hints, *ai, *aitop;
                   2862:        char strport[NI_MAXSERV];
                   2863:        int gaierr;
1.25      markus   2864:
                   2865:        /* Try to open a socket for the local X server. */
                   2866:        display = getenv("DISPLAY");
                   2867:        if (!display) {
                   2868:                error("DISPLAY not set.");
1.51      markus   2869:                return -1;
1.25      markus   2870:        }
1.27      markus   2871:        /*
                   2872:         * Now we decode the value of the DISPLAY variable and make a
                   2873:         * connection to the real X server.
                   2874:         */
                   2875:
                   2876:        /*
                   2877:         * Check if it is a unix domain socket.  Unix domain displays are in
                   2878:         * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
                   2879:         */
1.25      markus   2880:        if (strncmp(display, "unix:", 5) == 0 ||
                   2881:            display[0] == ':') {
                   2882:                /* Connect to the unix domain socket. */
                   2883:                if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
                   2884:                        error("Could not parse display number from DISPLAY: %.100s",
1.148     deraadt  2885:                            display);
1.51      markus   2886:                        return -1;
1.25      markus   2887:                }
                   2888:                /* Create a socket. */
                   2889:                sock = connect_local_xsocket(display_number);
                   2890:                if (sock < 0)
1.51      markus   2891:                        return -1;
1.25      markus   2892:
                   2893:                /* OK, we now have a connection to the display. */
1.51      markus   2894:                return sock;
1.25      markus   2895:        }
1.27      markus   2896:        /*
                   2897:         * Connect to an inet socket.  The DISPLAY value is supposedly
                   2898:         * hostname:d[.s], where hostname may also be numeric IP address.
                   2899:         */
1.145     stevesk  2900:        strlcpy(buf, display, sizeof(buf));
1.25      markus   2901:        cp = strchr(buf, ':');
                   2902:        if (!cp) {
                   2903:                error("Could not find ':' in DISPLAY: %.100s", display);
1.51      markus   2904:                return -1;
1.25      markus   2905:        }
                   2906:        *cp = 0;
1.27      markus   2907:        /* buf now contains the host name.  But first we parse the display number. */
1.25      markus   2908:        if (sscanf(cp + 1, "%d", &display_number) != 1) {
                   2909:                error("Could not parse display number from DISPLAY: %.100s",
1.148     deraadt  2910:                    display);
1.51      markus   2911:                return -1;
1.25      markus   2912:        }
1.35      markus   2913:
                   2914:        /* Look up the host address */
                   2915:        memset(&hints, 0, sizeof(hints));
                   2916:        hints.ai_family = IPv4or6;
                   2917:        hints.ai_socktype = SOCK_STREAM;
                   2918:        snprintf(strport, sizeof strport, "%d", 6000 + display_number);
                   2919:        if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
                   2920:                error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
1.51      markus   2921:                return -1;
1.25      markus   2922:        }
1.35      markus   2923:        for (ai = aitop; ai; ai = ai->ai_next) {
                   2924:                /* Create a socket. */
1.189     markus   2925:                sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1.35      markus   2926:                if (sock < 0) {
1.194     markus   2927:                        debug2("socket: %.100s", strerror(errno));
1.41      markus   2928:                        continue;
                   2929:                }
                   2930:                /* Connect it to the display. */
                   2931:                if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1.194     markus   2932:                        debug2("connect %.100s port %d: %.100s", buf,
1.41      markus   2933:                            6000 + display_number, strerror(errno));
                   2934:                        close(sock);
                   2935:                        continue;
                   2936:                }
                   2937:                /* Success */
                   2938:                break;
1.35      markus   2939:        }
                   2940:        freeaddrinfo(aitop);
                   2941:        if (!ai) {
1.49      markus   2942:                error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
1.35      markus   2943:                    strerror(errno));
1.51      markus   2944:                return -1;
1.25      markus   2945:        }
1.162     stevesk  2946:        set_nodelay(sock);
1.51      markus   2947:        return sock;
                   2948: }
                   2949:
                   2950: /*
                   2951:  * This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
                   2952:  * the remote channel number.  We should do whatever we want, and respond
                   2953:  * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
                   2954:  */
                   2955:
                   2956: void
1.154     markus   2957: x11_input_open(int type, u_int32_t seq, void *ctxt)
1.51      markus   2958: {
1.113     markus   2959:        Channel *c = NULL;
                   2960:        int remote_id, sock = 0;
1.51      markus   2961:        char *remote_host;
1.25      markus   2962:
1.113     markus   2963:        debug("Received X11 open request.");
1.51      markus   2964:
1.113     markus   2965:        remote_id = packet_get_int();
1.121     markus   2966:
                   2967:        if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
1.113     markus   2968:                remote_host = packet_get_string(NULL);
1.51      markus   2969:        } else {
                   2970:                remote_host = xstrdup("unknown (remote did not supply name)");
                   2971:        }
1.152     markus   2972:        packet_check_eom();
1.25      markus   2973:
1.51      markus   2974:        /* Obtain a connection to the real X display. */
                   2975:        sock = x11_connect_display();
1.113     markus   2976:        if (sock != -1) {
                   2977:                /* Allocate a channel for this connection. */
                   2978:                c = channel_new("connected x11 socket",
                   2979:                    SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
                   2980:                    remote_host, 1);
1.167     markus   2981:                c->remote_id = remote_id;
                   2982:                c->force_drain = 1;
1.113     markus   2983:        }
1.190     markus   2984:        xfree(remote_host);
1.113     markus   2985:        if (c == NULL) {
1.51      markus   2986:                /* Send refusal to the remote host. */
                   2987:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1.113     markus   2988:                packet_put_int(remote_id);
1.51      markus   2989:        } else {
                   2990:                /* Send a confirmation to the remote host. */
                   2991:                packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1.113     markus   2992:                packet_put_int(remote_id);
                   2993:                packet_put_int(c->self);
1.51      markus   2994:        }
1.113     markus   2995:        packet_send();
1.72      markus   2996: }
                   2997:
                   2998: /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
                   2999: void
1.154     markus   3000: deny_input_open(int type, u_int32_t seq, void *ctxt)
1.72      markus   3001: {
                   3002:        int rchan = packet_get_int();
1.180     deraadt  3003:
1.143     deraadt  3004:        switch (type) {
1.72      markus   3005:        case SSH_SMSG_AGENT_OPEN:
                   3006:                error("Warning: ssh server tried agent forwarding.");
                   3007:                break;
                   3008:        case SSH_SMSG_X11_OPEN:
                   3009:                error("Warning: ssh server tried X11 forwarding.");
                   3010:                break;
                   3011:        default:
1.154     markus   3012:                error("deny_input_open: type %d", type);
1.72      markus   3013:                break;
                   3014:        }
1.230     stevesk  3015:        error("Warning: this is probably a break-in attempt by a malicious server.");
1.72      markus   3016:        packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   3017:        packet_put_int(rchan);
                   3018:        packet_send();
1.1       deraadt  3019: }
                   3020:
1.27      markus   3021: /*
                   3022:  * Requests forwarding of X11 connections, generates fake authentication
                   3023:  * data, and enables authentication spoofing.
1.121     markus   3024:  * This should be called in the client only.
1.27      markus   3025:  */
1.49      markus   3026: void
1.215     djm      3027: x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
1.51      markus   3028:     const char *proto, const char *data)
1.1       deraadt  3029: {
1.77      markus   3030:        u_int data_len = (u_int) strlen(data) / 2;
1.219     djm      3031:        u_int i, value;
1.25      markus   3032:        char *new_data;
                   3033:        int screen_number;
                   3034:        const char *cp;
1.207     avsm     3035:        u_int32_t rnd = 0;
1.25      markus   3036:
1.220     markus   3037:        if (x11_saved_display == NULL)
                   3038:                x11_saved_display = xstrdup(disp);
                   3039:        else if (strcmp(disp, x11_saved_display) != 0) {
1.219     djm      3040:                error("x11_request_forwarding_with_spoofing: different "
                   3041:                    "$DISPLAY already forwarded");
                   3042:                return;
                   3043:        }
                   3044:
1.215     djm      3045:        cp = disp;
                   3046:        if (disp)
                   3047:                cp = strchr(disp, ':');
1.25      markus   3048:        if (cp)
                   3049:                cp = strchr(cp, '.');
                   3050:        if (cp)
                   3051:                screen_number = atoi(cp + 1);
                   3052:        else
                   3053:                screen_number = 0;
                   3054:
1.219     djm      3055:        if (x11_saved_proto == NULL) {
                   3056:                /* Save protocol name. */
                   3057:                x11_saved_proto = xstrdup(proto);
                   3058:                /*
1.221     djm      3059:                 * Extract real authentication data and generate fake data
1.219     djm      3060:                 * of the same length.
                   3061:                 */
                   3062:                x11_saved_data = xmalloc(data_len);
                   3063:                x11_fake_data = xmalloc(data_len);
                   3064:                for (i = 0; i < data_len; i++) {
                   3065:                        if (sscanf(data + 2 * i, "%2x", &value) != 1)
                   3066:                                fatal("x11_request_forwarding: bad "
                   3067:                                    "authentication data: %.100s", data);
                   3068:                        if (i % 4 == 0)
                   3069:                                rnd = arc4random();
                   3070:                        x11_saved_data[i] = value;
                   3071:                        x11_fake_data[i] = rnd & 0xff;
                   3072:                        rnd >>= 8;
                   3073:                }
                   3074:                x11_saved_data_len = data_len;
                   3075:                x11_fake_data_len = data_len;
1.25      markus   3076:        }
                   3077:
                   3078:        /* Convert the fake data into hex. */
1.219     djm      3079:        new_data = tohex(x11_fake_data, data_len);
1.25      markus   3080:
                   3081:        /* Send the request packet. */
1.51      markus   3082:        if (compat20) {
                   3083:                channel_request_start(client_session_id, "x11-req", 0);
                   3084:                packet_put_char(0);     /* XXX bool single connection */
                   3085:        } else {
                   3086:                packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
                   3087:        }
                   3088:        packet_put_cstring(proto);
                   3089:        packet_put_cstring(new_data);
1.25      markus   3090:        packet_put_int(screen_number);
                   3091:        packet_send();
                   3092:        packet_write_wait();
                   3093:        xfree(new_data);
1.1       deraadt  3094: }
                   3095:
1.121     markus   3096:
                   3097: /* -- agent forwarding */
                   3098:
1.1       deraadt  3099: /* Sends a message to the server to request authentication fd forwarding. */
                   3100:
1.49      markus   3101: void
1.142     itojun   3102: auth_request_forwarding(void)
1.1       deraadt  3103: {
1.25      markus   3104:        packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
                   3105:        packet_send();
                   3106:        packet_write_wait();
1.1       deraadt  3107: }