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

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