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

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