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

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