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

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