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

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