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

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