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

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