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

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