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

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