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

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