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

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