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

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