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

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