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

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