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

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