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

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