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

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