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

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