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

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