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

1.1       deraadt     1: /*
1.26      deraadt     2:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      3:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      4:  *                    All rights reserved
                      5:  * This file contains functions for generic socket connection forwarding.
                      6:  * There is also code for initiating connection forwarding for X11 connections,
                      7:  * arbitrary tcp/ip connections, and the authentication agent connection.
1.49      markus      8:  *
1.67      deraadt     9:  * As far as I am concerned, the code I have written for this software
                     10:  * can be used freely for any purpose.  Any derived versions of this
                     11:  * software must be clearly marked as such, and if the derived work is
                     12:  * incompatible with the protocol description in the RFC file, it must be
                     13:  * called by a name other than "ssh" or "Secure Shell".
                     14:  *
                     15:  *
1.44      markus     16:  * SSH2 support added by Markus Friedl.
1.67      deraadt    17:  * Copyright (c) 1999,2000 Markus Friedl.  All rights reserved.
                     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.91    ! markus     43: RCSID("$OpenBSD: channels.c,v 1.90 2001/02/08 21:58:28 markus Exp $");
1.82      markus     44:
                     45: #include <openssl/rsa.h>
                     46: #include <openssl/dsa.h>
1.1       deraadt    47:
                     48: #include "ssh.h"
1.82      markus     49: #include "ssh1.h"
                     50: #include "ssh2.h"
1.1       deraadt    51: #include "packet.h"
                     52: #include "xmalloc.h"
                     53: #include "buffer.h"
                     54: #include "uidswap.h"
1.82      markus     55: #include "log.h"
                     56: #include "misc.h"
1.14      markus     57: #include "channels.h"
                     58: #include "nchan.h"
                     59: #include "compat.h"
1.82      markus     60: #include "canohost.h"
1.64      markus     61: #include "key.h"
                     62: #include "authfd.h"
1.44      markus     63:
1.1       deraadt    64: /* Maximum number of fake X11 displays to try. */
                     65: #define MAX_DISPLAYS  1000
                     66:
1.12      markus     67: /* Max len of agent socket */
                     68: #define MAX_SOCKET_NAME 100
                     69:
1.27      markus     70: /*
                     71:  * Pointer to an array containing all allocated channels.  The array is
                     72:  * dynamically extended as needed.
                     73:  */
1.1       deraadt    74: static Channel *channels = NULL;
                     75:
1.27      markus     76: /*
                     77:  * Size of the channel array.  All slots of the array must always be
                     78:  * initialized (at least the type field); unused slots are marked with type
                     79:  * SSH_CHANNEL_FREE.
                     80:  */
1.1       deraadt    81: static int channels_alloc = 0;
                     82:
1.27      markus     83: /*
                     84:  * Maximum file descriptor value used in any of the channels.  This is
                     85:  * updated in channel_allocate.
                     86:  */
1.84      markus     87: static int channel_max_fd = 0;
1.1       deraadt    88:
1.12      markus     89: /* Name and directory of socket for authentication agent forwarding. */
1.1       deraadt    90: static char *channel_forwarded_auth_socket_name = NULL;
1.25      markus     91: static char *channel_forwarded_auth_socket_dir = NULL;
1.1       deraadt    92:
                     93: /* Saved X11 authentication protocol name. */
                     94: char *x11_saved_proto = NULL;
                     95:
                     96: /* Saved X11 authentication data.  This is the real data. */
                     97: char *x11_saved_data = NULL;
1.77      markus     98: u_int x11_saved_data_len = 0;
1.1       deraadt    99:
1.27      markus    100: /*
                    101:  * Fake X11 authentication data.  This is what the server will be sending us;
                    102:  * we should replace any occurrences of this by the real data.
                    103:  */
1.1       deraadt   104: char *x11_fake_data = NULL;
1.77      markus    105: u_int x11_fake_data_len;
1.1       deraadt   106:
1.27      markus    107: /*
                    108:  * Data structure for storing which hosts are permitted for forward requests.
                    109:  * The local sides of any remote forwards are stored in this array to prevent
                    110:  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
                    111:  * network (which might be behind a firewall).
                    112:  */
1.25      markus    113: typedef struct {
1.41      markus    114:        char *host_to_connect;          /* Connect to 'host'. */
                    115:        u_short port_to_connect;        /* Connect to 'port'. */
                    116:        u_short listen_port;            /* Remote side should listen port number. */
1.1       deraadt   117: } ForwardPermission;
                    118:
                    119: /* List of all permitted host/port pairs to connect. */
                    120: static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
                    121: /* Number of permitted host/port pairs in the array. */
                    122: static int num_permitted_opens = 0;
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:
                    130: /* This is set to true if both sides support SSH_PROTOFLAG_HOST_IN_FWD_OPEN. */
                    131: static int have_hostname_in_open = 0;
1.82      markus    132:
                    133: /* AF_UNSPEC or AF_INET or AF_INET6 */
                    134: extern int IPv4or6;
1.1       deraadt   135:
                    136: /* Sets specific protocol options. */
                    137:
1.49      markus    138: void
1.25      markus    139: channel_set_options(int hostname_in_open)
1.1       deraadt   140: {
1.25      markus    141:        have_hostname_in_open = hostname_in_open;
1.1       deraadt   142: }
                    143:
1.27      markus    144: /*
                    145:  * Permits opening to any host/port in SSH_MSG_PORT_OPEN.  This is usually
                    146:  * called by the server, because the user could connect to any port anyway,
                    147:  * and the server has no way to know but to trust the client anyway.
                    148:  */
1.1       deraadt   149:
1.49      markus    150: void
1.25      markus    151: channel_permit_all_opens()
1.1       deraadt   152: {
1.25      markus    153:        all_opens_permitted = 1;
1.1       deraadt   154: }
                    155:
1.41      markus    156: /* lookup channel by id */
                    157:
                    158: Channel *
                    159: channel_lookup(int id)
                    160: {
                    161:        Channel *c;
1.63      provos    162:        if (id < 0 || id > channels_alloc) {
1.41      markus    163:                log("channel_lookup: %d: bad id", id);
                    164:                return NULL;
                    165:        }
                    166:        c = &channels[id];
                    167:        if (c->type == SSH_CHANNEL_FREE) {
                    168:                log("channel_lookup: %d: bad id: channel free", id);
                    169:                return NULL;
                    170:        }
                    171:        return c;
1.55      markus    172: }
                    173:
1.27      markus    174: /*
1.55      markus    175:  * Register filedescriptors for a channel, used when allocating a channel or
1.52      markus    176:  * when the channel consumer/producer is ready, e.g. shell exec'd
1.27      markus    177:  */
1.1       deraadt   178:
1.52      markus    179: void
1.71      markus    180: channel_register_fds(Channel *c, int rfd, int wfd, int efd,
                    181:     int extusage, int nonblock)
1.1       deraadt   182: {
1.25      markus    183:        /* Update the maximum file descriptor value. */
1.84      markus    184:        channel_max_fd = MAX(channel_max_fd, rfd);
                    185:        channel_max_fd = MAX(channel_max_fd, wfd);
                    186:        channel_max_fd = MAX(channel_max_fd, efd);
                    187:
1.27      markus    188:        /* XXX set close-on-exec -markus */
1.55      markus    189:
1.52      markus    190:        c->rfd = rfd;
                    191:        c->wfd = wfd;
                    192:        c->sock = (rfd == wfd) ? rfd : -1;
                    193:        c->efd = efd;
                    194:        c->extended_usage = extusage;
1.71      markus    195:
1.91    ! markus    196:        /* XXX ugly hack: nonblock is only set by the server */
        !           197:        if (nonblock && isatty(c->rfd)) {
        !           198:                debug("channel: %d: rfd %d isatty", c->self, c->rfd);
        !           199:                c->isatty = 1;
        !           200:                if (!isatty(c->wfd)) {
        !           201:                        error("channel: %d: wfd %d is not a tty?",
        !           202:                            c->self, c->wfd);
        !           203:                }
        !           204:        } else {
        !           205:                c->isatty = 0;
        !           206:        }
        !           207:
1.71      markus    208:        /* enable nonblocking mode */
                    209:        if (nonblock) {
                    210:                if (rfd != -1)
                    211:                        set_nonblock(rfd);
                    212:                if (wfd != -1)
                    213:                        set_nonblock(wfd);
                    214:                if (efd != -1)
                    215:                        set_nonblock(efd);
                    216:        }
1.52      markus    217: }
                    218:
                    219: /*
                    220:  * Allocate a new channel object and set its type and socket. This will cause
                    221:  * remote_name to be freed.
                    222:  */
                    223:
                    224: int
                    225: channel_new(char *ctype, int type, int rfd, int wfd, int efd,
1.71      markus    226:     int window, int maxpack, int extusage, char *remote_name, int nonblock)
1.52      markus    227: {
                    228:        int i, found;
                    229:        Channel *c;
1.25      markus    230:
                    231:        /* Do initial allocation if this is the first call. */
                    232:        if (channels_alloc == 0) {
1.44      markus    233:                chan_init();
1.25      markus    234:                channels_alloc = 10;
                    235:                channels = xmalloc(channels_alloc * sizeof(Channel));
                    236:                for (i = 0; i < channels_alloc; i++)
                    237:                        channels[i].type = SSH_CHANNEL_FREE;
1.27      markus    238:                /*
                    239:                 * Kludge: arrange a call to channel_stop_listening if we
                    240:                 * terminate with fatal().
                    241:                 */
1.25      markus    242:                fatal_add_cleanup((void (*) (void *)) channel_stop_listening, NULL);
                    243:        }
                    244:        /* Try to find a free slot where to put the new channel. */
                    245:        for (found = -1, i = 0; i < channels_alloc; i++)
                    246:                if (channels[i].type == SSH_CHANNEL_FREE) {
                    247:                        /* Found a free slot. */
                    248:                        found = i;
                    249:                        break;
                    250:                }
                    251:        if (found == -1) {
1.27      markus    252:                /* There are no free slots.  Take last+1 slot and expand the array.  */
1.25      markus    253:                found = channels_alloc;
                    254:                channels_alloc += 10;
1.70      markus    255:                debug2("channel: expanding %d", channels_alloc);
1.25      markus    256:                channels = xrealloc(channels, channels_alloc * sizeof(Channel));
                    257:                for (i = found; i < channels_alloc; i++)
                    258:                        channels[i].type = SSH_CHANNEL_FREE;
                    259:        }
                    260:        /* Initialize and return new channel number. */
                    261:        c = &channels[found];
                    262:        buffer_init(&c->input);
                    263:        buffer_init(&c->output);
1.41      markus    264:        buffer_init(&c->extended);
1.25      markus    265:        chan_init_iostates(c);
1.71      markus    266:        channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
1.25      markus    267:        c->self = found;
                    268:        c->type = type;
1.41      markus    269:        c->ctype = ctype;
1.51      markus    270:        c->local_window = window;
                    271:        c->local_window_max = window;
                    272:        c->local_consumed = 0;
                    273:        c->local_maxpacket = maxpack;
1.25      markus    274:        c->remote_id = -1;
                    275:        c->remote_name = remote_name;
1.41      markus    276:        c->remote_window = 0;
                    277:        c->remote_maxpacket = 0;
                    278:        c->cb_fn = NULL;
                    279:        c->cb_arg = NULL;
                    280:        c->cb_event = 0;
                    281:        c->dettach_user = NULL;
1.65      markus    282:        c->input_filter = NULL;
1.25      markus    283:        debug("channel %d: new [%s]", found, remote_name);
                    284:        return found;
1.1       deraadt   285: }
1.52      markus    286: /* old interface XXX */
1.49      markus    287: int
1.41      markus    288: channel_allocate(int type, int sock, char *remote_name)
                    289: {
1.71      markus    290:        return channel_new("", type, sock, sock, -1, 0, 0, 0, remote_name, 1);
1.41      markus    291: }
1.1       deraadt   292:
1.52      markus    293:
                    294: /* Close all channel fd/socket. */
                    295:
                    296: void
                    297: channel_close_fds(Channel *c)
                    298: {
                    299:        if (c->sock != -1) {
                    300:                close(c->sock);
                    301:                c->sock = -1;
                    302:        }
                    303:        if (c->rfd != -1) {
                    304:                close(c->rfd);
                    305:                c->rfd = -1;
                    306:        }
                    307:        if (c->wfd != -1) {
                    308:                close(c->wfd);
                    309:                c->wfd = -1;
                    310:        }
                    311:        if (c->efd != -1) {
                    312:                close(c->efd);
                    313:                c->efd = -1;
                    314:        }
                    315: }
                    316:
                    317: /* Free the channel and close its fd/socket. */
1.1       deraadt   318:
1.49      markus    319: void
1.41      markus    320: channel_free(int id)
1.1       deraadt   321: {
1.41      markus    322:        Channel *c = channel_lookup(id);
1.79      markus    323:        char *s = channel_open_message();
                    324:
1.41      markus    325:        if (c == NULL)
                    326:                packet_disconnect("channel free: bad local channel %d", id);
1.79      markus    327:        debug("channel_free: channel %d: status: %s", id, s);
                    328:        xfree(s);
                    329:
1.44      markus    330:        if (c->dettach_user != NULL) {
                    331:                debug("channel_free: channel %d: dettaching channel user", id);
                    332:                c->dettach_user(c->self, NULL);
                    333:        }
1.54      markus    334:        if (c->sock != -1)
                    335:                shutdown(c->sock, SHUT_RDWR);
1.52      markus    336:        channel_close_fds(c);
1.41      markus    337:        buffer_free(&c->input);
                    338:        buffer_free(&c->output);
                    339:        buffer_free(&c->extended);
                    340:        c->type = SSH_CHANNEL_FREE;
                    341:        if (c->remote_name) {
                    342:                xfree(c->remote_name);
                    343:                c->remote_name = NULL;
1.25      markus    344:        }
1.1       deraadt   345: }
                    346:
1.27      markus    347: /*
1.41      markus    348:  * 'channel_pre*' are called just before select() to add any bits relevant to
                    349:  * channels in the select bitmasks.
                    350:  */
                    351: /*
                    352:  * 'channel_post*': perform any appropriate operations for channels which
                    353:  * have events pending.
1.27      markus    354:  */
1.41      markus    355: typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
                    356: chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
                    357: chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
                    358:
                    359: void
                    360: channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
                    361: {
                    362:        FD_SET(c->sock, readset);
                    363: }
                    364:
                    365: void
1.75      markus    366: channel_pre_connecting(Channel *c, fd_set * readset, fd_set * writeset)
                    367: {
                    368:        debug3("channel %d: waiting for connection", c->self);
                    369:        FD_SET(c->sock, writeset);
                    370: }
                    371:
                    372: void
1.41      markus    373: channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
                    374: {
                    375:        if (buffer_len(&c->input) < packet_get_maxsize())
                    376:                FD_SET(c->sock, readset);
                    377:        if (buffer_len(&c->output) > 0)
                    378:                FD_SET(c->sock, writeset);
                    379: }
1.1       deraadt   380:
1.41      markus    381: void
                    382: channel_pre_open_15(Channel *c, fd_set * readset, fd_set * writeset)
                    383: {
                    384:        /* test whether sockets are 'alive' for read/write */
                    385:        if (c->istate == CHAN_INPUT_OPEN)
                    386:                if (buffer_len(&c->input) < packet_get_maxsize())
                    387:                        FD_SET(c->sock, readset);
                    388:        if (c->ostate == CHAN_OUTPUT_OPEN ||
                    389:            c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
                    390:                if (buffer_len(&c->output) > 0) {
                    391:                        FD_SET(c->sock, writeset);
                    392:                } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
                    393:                        chan_obuf_empty(c);
                    394:                }
                    395:        }
                    396: }
                    397:
                    398: void
1.44      markus    399: channel_pre_open_20(Channel *c, fd_set * readset, fd_set * writeset)
                    400: {
                    401:        if (c->istate == CHAN_INPUT_OPEN &&
                    402:            c->remote_window > 0 &&
                    403:            buffer_len(&c->input) < c->remote_window)
                    404:                FD_SET(c->rfd, readset);
                    405:        if (c->ostate == CHAN_OUTPUT_OPEN ||
                    406:            c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
                    407:                if (buffer_len(&c->output) > 0) {
                    408:                        FD_SET(c->wfd, writeset);
                    409:                } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
                    410:                        chan_obuf_empty(c);
                    411:                }
                    412:        }
                    413:        /** XXX check close conditions, too */
                    414:        if (c->efd != -1) {
                    415:                if (c->extended_usage == CHAN_EXTENDED_WRITE &&
                    416:                    buffer_len(&c->extended) > 0)
                    417:                        FD_SET(c->efd, writeset);
                    418:                else if (c->extended_usage == CHAN_EXTENDED_READ &&
                    419:                    buffer_len(&c->extended) < c->remote_window)
                    420:                        FD_SET(c->efd, readset);
                    421:        }
                    422: }
                    423:
                    424: void
1.41      markus    425: channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
                    426: {
                    427:        if (buffer_len(&c->input) == 0) {
                    428:                packet_start(SSH_MSG_CHANNEL_CLOSE);
                    429:                packet_put_int(c->remote_id);
                    430:                packet_send();
                    431:                c->type = SSH_CHANNEL_CLOSED;
                    432:                debug("Closing channel %d after input drain.", c->self);
                    433:        }
                    434: }
                    435:
                    436: void
                    437: channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
                    438: {
                    439:        if (buffer_len(&c->output) == 0)
                    440:                channel_free(c->self);
1.49      markus    441:        else
1.41      markus    442:                FD_SET(c->sock, writeset);
                    443: }
                    444:
                    445: /*
                    446:  * This is a special state for X11 authentication spoofing.  An opened X11
                    447:  * connection (when authentication spoofing is being done) remains in this
                    448:  * state until the first packet has been completely read.  The authentication
                    449:  * data in that packet is then substituted by the real data if it matches the
                    450:  * fake data, and the channel is put into normal mode.
1.51      markus    451:  * XXX All this happens at the client side.
1.41      markus    452:  */
                    453: int
                    454: x11_open_helper(Channel *c)
1.1       deraadt   455: {
1.77      markus    456:        u_char *ucp;
                    457:        u_int proto_len, data_len;
1.25      markus    458:
1.41      markus    459:        /* Check if the fixed size part of the packet is in buffer. */
                    460:        if (buffer_len(&c->output) < 12)
                    461:                return 0;
                    462:
                    463:        /* Parse the lengths of variable-length fields. */
1.77      markus    464:        ucp = (u_char *) buffer_ptr(&c->output);
1.41      markus    465:        if (ucp[0] == 0x42) {   /* Byte order MSB first. */
                    466:                proto_len = 256 * ucp[6] + ucp[7];
                    467:                data_len = 256 * ucp[8] + ucp[9];
                    468:        } else if (ucp[0] == 0x6c) {    /* Byte order LSB first. */
                    469:                proto_len = ucp[6] + 256 * ucp[7];
                    470:                data_len = ucp[8] + 256 * ucp[9];
                    471:        } else {
                    472:                debug("Initial X11 packet contains bad byte order byte: 0x%x",
                    473:                      ucp[0]);
                    474:                return -1;
                    475:        }
                    476:
                    477:        /* Check if the whole packet is in buffer. */
                    478:        if (buffer_len(&c->output) <
                    479:            12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
                    480:                return 0;
                    481:
                    482:        /* Check if authentication protocol matches. */
                    483:        if (proto_len != strlen(x11_saved_proto) ||
                    484:            memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
                    485:                debug("X11 connection uses different authentication protocol.");
                    486:                return -1;
                    487:        }
                    488:        /* Check if authentication data matches our fake data. */
                    489:        if (data_len != x11_fake_data_len ||
                    490:            memcmp(ucp + 12 + ((proto_len + 3) & ~3),
                    491:                x11_fake_data, x11_fake_data_len) != 0) {
                    492:                debug("X11 auth data does not match fake data.");
                    493:                return -1;
                    494:        }
                    495:        /* Check fake data length */
                    496:        if (x11_fake_data_len != x11_saved_data_len) {
                    497:                error("X11 fake_data_len %d != saved_data_len %d",
                    498:                    x11_fake_data_len, x11_saved_data_len);
                    499:                return -1;
                    500:        }
                    501:        /*
                    502:         * Received authentication protocol and data match
                    503:         * our fake data. Substitute the fake data with real
                    504:         * data.
                    505:         */
                    506:        memcpy(ucp + 12 + ((proto_len + 3) & ~3),
                    507:            x11_saved_data, x11_saved_data_len);
                    508:        return 1;
                    509: }
                    510:
                    511: void
                    512: channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
                    513: {
                    514:        int ret = x11_open_helper(c);
                    515:        if (ret == 1) {
                    516:                /* Start normal processing for the channel. */
                    517:                c->type = SSH_CHANNEL_OPEN;
1.47      markus    518:                channel_pre_open_13(c, readset, writeset);
1.41      markus    519:        } else if (ret == -1) {
                    520:                /*
                    521:                 * We have received an X11 connection that has bad
                    522:                 * authentication information.
                    523:                 */
                    524:                log("X11 connection rejected because of wrong authentication.\r\n");
                    525:                buffer_clear(&c->input);
                    526:                buffer_clear(&c->output);
                    527:                close(c->sock);
                    528:                c->sock = -1;
                    529:                c->type = SSH_CHANNEL_CLOSED;
                    530:                packet_start(SSH_MSG_CHANNEL_CLOSE);
                    531:                packet_put_int(c->remote_id);
                    532:                packet_send();
                    533:        }
                    534: }
1.25      markus    535:
1.41      markus    536: void
1.51      markus    537: channel_pre_x11_open(Channel *c, fd_set * readset, fd_set * writeset)
1.41      markus    538: {
                    539:        int ret = x11_open_helper(c);
                    540:        if (ret == 1) {
                    541:                c->type = SSH_CHANNEL_OPEN;
1.57      markus    542:                if (compat20)
                    543:                        channel_pre_open_20(c, readset, writeset);
                    544:                else
                    545:                        channel_pre_open_15(c, readset, writeset);
1.41      markus    546:        } else if (ret == -1) {
                    547:                debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
1.51      markus    548:                chan_read_failed(c);    /** force close? */
1.41      markus    549:                chan_write_failed(c);
                    550:                debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
                    551:        }
                    552: }
1.25      markus    553:
1.41      markus    554: /* This is our fake X11 server socket. */
                    555: void
                    556: channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
                    557: {
                    558:        struct sockaddr addr;
                    559:        int newsock, newch;
                    560:        socklen_t addrlen;
1.85      markus    561:        char buf[16384], *remote_ipaddr;
1.51      markus    562:        int remote_port;
1.25      markus    563:
1.41      markus    564:        if (FD_ISSET(c->sock, readset)) {
                    565:                debug("X11 connection requested.");
                    566:                addrlen = sizeof(addr);
                    567:                newsock = accept(c->sock, &addr, &addrlen);
                    568:                if (newsock < 0) {
                    569:                        error("accept: %.100s", strerror(errno));
                    570:                        return;
                    571:                }
1.85      markus    572:                remote_ipaddr = get_peer_ipaddr(newsock);
1.51      markus    573:                remote_port = get_peer_port(newsock);
1.41      markus    574:                snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1.85      markus    575:                    remote_ipaddr, remote_port);
1.51      markus    576:
                    577:                newch = channel_new("x11",
                    578:                    SSH_CHANNEL_OPENING, newsock, newsock, -1,
                    579:                    c->local_window_max, c->local_maxpacket,
1.71      markus    580:                    0, xstrdup(buf), 1);
1.51      markus    581:                if (compat20) {
                    582:                        packet_start(SSH2_MSG_CHANNEL_OPEN);
                    583:                        packet_put_cstring("x11");
                    584:                        packet_put_int(newch);
                    585:                        packet_put_int(c->local_window_max);
                    586:                        packet_put_int(c->local_maxpacket);
1.85      markus    587:                        /* originator ipaddr and port */
                    588:                        packet_put_cstring(remote_ipaddr);
1.57      markus    589:                        if (datafellows & SSH_BUG_X11FWD) {
                    590:                                debug("ssh2 x11 bug compat mode");
                    591:                        } else {
                    592:                                packet_put_int(remote_port);
                    593:                        }
1.51      markus    594:                        packet_send();
                    595:                } else {
                    596:                        packet_start(SSH_SMSG_X11_OPEN);
                    597:                        packet_put_int(newch);
                    598:                        if (have_hostname_in_open)
                    599:                                packet_put_string(buf, strlen(buf));
                    600:                        packet_send();
                    601:                }
1.85      markus    602:                xfree(remote_ipaddr);
1.41      markus    603:        }
                    604: }
1.25      markus    605:
1.41      markus    606: /*
                    607:  * This socket is listening for connections to a forwarded TCP/IP port.
                    608:  */
                    609: void
                    610: channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
                    611: {
                    612:        struct sockaddr addr;
                    613:        int newsock, newch;
                    614:        socklen_t addrlen;
1.88      markus    615:        char buf[1024], *remote_ipaddr, *rtype;
1.41      markus    616:        int remote_port;
1.25      markus    617:
1.73      markus    618:        rtype = (c->type == SSH_CHANNEL_RPORT_LISTENER) ?
                    619:            "forwarded-tcpip" : "direct-tcpip";
                    620:
1.41      markus    621:        if (FD_ISSET(c->sock, readset)) {
                    622:                debug("Connection to port %d forwarding "
                    623:                    "to %.100s port %d requested.",
                    624:                    c->listening_port, c->path, c->host_port);
                    625:                addrlen = sizeof(addr);
                    626:                newsock = accept(c->sock, &addr, &addrlen);
                    627:                if (newsock < 0) {
                    628:                        error("accept: %.100s", strerror(errno));
                    629:                        return;
                    630:                }
1.88      markus    631:                remote_ipaddr = get_peer_ipaddr(newsock);
1.41      markus    632:                remote_port = get_peer_port(newsock);
                    633:                snprintf(buf, sizeof buf,
                    634:                    "listen port %d for %.100s port %d, "
                    635:                    "connect from %.200s port %d",
                    636:                    c->listening_port, c->path, c->host_port,
1.88      markus    637:                    remote_ipaddr, remote_port);
1.73      markus    638:
                    639:                newch = channel_new(rtype,
1.41      markus    640:                    SSH_CHANNEL_OPENING, newsock, newsock, -1,
                    641:                    c->local_window_max, c->local_maxpacket,
1.71      markus    642:                    0, xstrdup(buf), 1);
1.44      markus    643:                if (compat20) {
                    644:                        packet_start(SSH2_MSG_CHANNEL_OPEN);
1.73      markus    645:                        packet_put_cstring(rtype);
1.44      markus    646:                        packet_put_int(newch);
                    647:                        packet_put_int(c->local_window_max);
                    648:                        packet_put_int(c->local_maxpacket);
1.73      markus    649:                        if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
                    650:                                /* listen address, port */
                    651:                                packet_put_string(c->path, strlen(c->path));
                    652:                                packet_put_int(c->listening_port);
                    653:                        } else {
                    654:                                /* target host, port */
                    655:                                packet_put_string(c->path, strlen(c->path));
                    656:                                packet_put_int(c->host_port);
                    657:                        }
1.48      markus    658:                        /* originator host and port */
1.88      markus    659:                        packet_put_cstring(remote_ipaddr);
1.44      markus    660:                        packet_put_int(remote_port);
                    661:                        packet_send();
                    662:                } else {
                    663:                        packet_start(SSH_MSG_PORT_OPEN);
                    664:                        packet_put_int(newch);
                    665:                        packet_put_string(c->path, strlen(c->path));
                    666:                        packet_put_int(c->host_port);
                    667:                        if (have_hostname_in_open) {
                    668:                                packet_put_string(buf, strlen(buf));
                    669:                        }
                    670:                        packet_send();
1.41      markus    671:                }
1.88      markus    672:                xfree(remote_ipaddr);
1.41      markus    673:        }
                    674: }
1.25      markus    675:
1.41      markus    676: /*
                    677:  * This is the authentication agent socket listening for connections from
                    678:  * clients.
                    679:  */
                    680: void
                    681: channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
                    682: {
                    683:        struct sockaddr addr;
                    684:        int newsock, newch;
                    685:        socklen_t addrlen;
1.25      markus    686:
1.41      markus    687:        if (FD_ISSET(c->sock, readset)) {
                    688:                addrlen = sizeof(addr);
                    689:                newsock = accept(c->sock, &addr, &addrlen);
                    690:                if (newsock < 0) {
                    691:                        error("accept from auth socket: %.100s", strerror(errno));
                    692:                        return;
                    693:                }
1.73      markus    694:                newch = channel_new("accepted auth socket",
                    695:                    SSH_CHANNEL_OPENING, newsock, newsock, -1,
                    696:                    c->local_window_max, c->local_maxpacket,
                    697:                    0, xstrdup("accepted auth socket"), 1);
                    698:                if (compat20) {
                    699:                        packet_start(SSH2_MSG_CHANNEL_OPEN);
                    700:                        packet_put_cstring("auth-agent@openssh.com");
                    701:                        packet_put_int(newch);
                    702:                        packet_put_int(c->local_window_max);
                    703:                        packet_put_int(c->local_maxpacket);
                    704:                } else {
                    705:                        packet_start(SSH_SMSG_AGENT_OPEN);
                    706:                        packet_put_int(newch);
                    707:                }
1.41      markus    708:                packet_send();
                    709:        }
                    710: }
1.25      markus    711:
1.75      markus    712: void
                    713: channel_post_connecting(Channel *c, fd_set * readset, fd_set * writeset)
                    714: {
                    715:        if (FD_ISSET(c->sock, writeset)) {
                    716:                int err = 0;
                    717:                int sz = sizeof(err);
                    718:                c->type = SSH_CHANNEL_OPEN;
1.89      stevesk   719:                if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, (char *)&err, &sz) < 0) {
1.75      markus    720:                        debug("getsockopt SO_ERROR failed");
                    721:                } else {
                    722:                        if (err == 0) {
                    723:                                debug("channel %d: connected)", c->self);
                    724:                        } else {
                    725:                                debug("channel %d: not connected: %s",
                    726:                                    c->self, strerror(err));
                    727:                                chan_read_failed(c);
                    728:                                chan_write_failed(c);
                    729:                        }
                    730:                }
                    731:        }
                    732: }
                    733:
1.41      markus    734: int
                    735: channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
                    736: {
                    737:        char buf[16*1024];
                    738:        int len;
1.25      markus    739:
1.41      markus    740:        if (c->rfd != -1 &&
                    741:            FD_ISSET(c->rfd, readset)) {
                    742:                len = read(c->rfd, buf, sizeof(buf));
1.53      markus    743:                if (len < 0 && (errno == EINTR || errno == EAGAIN))
                    744:                        return 1;
1.41      markus    745:                if (len <= 0) {
1.51      markus    746:                        debug("channel %d: read<=0 rfd %d len %d",
1.41      markus    747:                            c->self, c->rfd, len);
1.25      markus    748:                        if (compat13) {
1.41      markus    749:                                buffer_consume(&c->output, buffer_len(&c->output));
                    750:                                c->type = SSH_CHANNEL_INPUT_DRAINING;
                    751:                                debug("Channel %d status set to input draining.", c->self);
1.25      markus    752:                        } else {
1.41      markus    753:                                chan_read_failed(c);
1.25      markus    754:                        }
1.41      markus    755:                        return -1;
                    756:                }
1.65      markus    757:                if(c->input_filter != NULL) {
1.66      markus    758:                        if (c->input_filter(c, buf, len) == -1) {
1.65      markus    759:                                debug("filter stops channel %d", c->self);
                    760:                                chan_read_failed(c);
                    761:                        }
                    762:                } else {
                    763:                        buffer_append(&c->input, buf, len);
                    764:                }
1.41      markus    765:        }
                    766:        return 1;
                    767: }
                    768: int
                    769: channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
                    770: {
                    771:        int len;
1.25      markus    772:
1.41      markus    773:        /* Send buffered output data to the socket. */
                    774:        if (c->wfd != -1 &&
                    775:            FD_ISSET(c->wfd, writeset) &&
                    776:            buffer_len(&c->output) > 0) {
                    777:                len = write(c->wfd, buffer_ptr(&c->output),
1.53      markus    778:                    buffer_len(&c->output));
                    779:                if (len < 0 && (errno == EINTR || errno == EAGAIN))
                    780:                        return 1;
1.41      markus    781:                if (len <= 0) {
                    782:                        if (compat13) {
                    783:                                buffer_consume(&c->output, buffer_len(&c->output));
                    784:                                debug("Channel %d status set to input draining.", c->self);
                    785:                                c->type = SSH_CHANNEL_INPUT_DRAINING;
                    786:                        } else {
                    787:                                chan_write_failed(c);
                    788:                        }
                    789:                        return -1;
1.91    ! markus    790:                }
        !           791:                if (compat20 && c->isatty) {
        !           792:                        struct termios tio;
        !           793:                        if (tcgetattr(c->wfd, &tio) == 0 &&
        !           794:                            !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
        !           795:                                /*
        !           796:                                 * Simulate echo to reduce the impact of
        !           797:                                 * traffic analysis.
        !           798:                                 */
        !           799:                                packet_start(SSH2_MSG_IGNORE);
        !           800:                                memset(buffer_ptr(&c->output), 0, len);
        !           801:                                packet_put_string(buffer_ptr(&c->output), len);
        !           802:                                packet_send();
        !           803:                                debug("channel: %d simulate echo (%d)", c->self, len);
        !           804:                        }
1.25      markus    805:                }
1.41      markus    806:                buffer_consume(&c->output, len);
1.44      markus    807:                if (compat20 && len > 0) {
                    808:                        c->local_consumed += len;
                    809:                }
                    810:        }
                    811:        return 1;
                    812: }
                    813: int
                    814: channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
                    815: {
                    816:        char buf[16*1024];
                    817:        int len;
                    818:
1.45      markus    819: /** XXX handle drain efd, too */
1.44      markus    820:        if (c->efd != -1) {
                    821:                if (c->extended_usage == CHAN_EXTENDED_WRITE &&
                    822:                    FD_ISSET(c->efd, writeset) &&
                    823:                    buffer_len(&c->extended) > 0) {
                    824:                        len = write(c->efd, buffer_ptr(&c->extended),
                    825:                            buffer_len(&c->extended));
1.70      markus    826:                        debug2("channel %d: written %d to efd %d",
1.44      markus    827:                            c->self, len, c->efd);
                    828:                        if (len > 0) {
                    829:                                buffer_consume(&c->extended, len);
                    830:                                c->local_consumed += len;
                    831:                        }
                    832:                } else if (c->extended_usage == CHAN_EXTENDED_READ &&
                    833:                    FD_ISSET(c->efd, readset)) {
                    834:                        len = read(c->efd, buf, sizeof(buf));
1.70      markus    835:                        debug2("channel %d: read %d from efd %d",
1.44      markus    836:                             c->self, len, c->efd);
1.45      markus    837:                        if (len == 0) {
                    838:                                debug("channel %d: closing efd %d",
                    839:                                    c->self, c->efd);
                    840:                                close(c->efd);
                    841:                                c->efd = -1;
                    842:                        } else if (len > 0)
1.44      markus    843:                                buffer_append(&c->extended, buf, len);
                    844:                }
                    845:        }
                    846:        return 1;
                    847: }
                    848: int
                    849: channel_check_window(Channel *c, fd_set * readset, fd_set * writeset)
                    850: {
1.46      markus    851:        if (!(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1.44      markus    852:            c->local_window < c->local_window_max/2 &&
                    853:            c->local_consumed > 0) {
                    854:                packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
                    855:                packet_put_int(c->remote_id);
                    856:                packet_put_int(c->local_consumed);
                    857:                packet_send();
1.70      markus    858:                debug2("channel %d: window %d sent adjust %d",
1.44      markus    859:                    c->self, c->local_window,
                    860:                    c->local_consumed);
                    861:                c->local_window += c->local_consumed;
                    862:                c->local_consumed = 0;
1.1       deraadt   863:        }
1.41      markus    864:        return 1;
1.1       deraadt   865: }
                    866:
1.41      markus    867: void
                    868: channel_post_open_1(Channel *c, fd_set * readset, fd_set * writeset)
                    869: {
                    870:        channel_handle_rfd(c, readset, writeset);
                    871:        channel_handle_wfd(c, readset, writeset);
                    872: }
1.1       deraadt   873:
1.41      markus    874: void
1.44      markus    875: channel_post_open_2(Channel *c, fd_set * readset, fd_set * writeset)
                    876: {
                    877:        channel_handle_rfd(c, readset, writeset);
                    878:        channel_handle_wfd(c, readset, writeset);
                    879:        channel_handle_efd(c, readset, writeset);
                    880:        channel_check_window(c, readset, writeset);
                    881: }
                    882:
                    883: void
1.41      markus    884: channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
1.1       deraadt   885: {
1.41      markus    886:        int len;
                    887:        /* Send buffered output data to the socket. */
                    888:        if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
                    889:                len = write(c->sock, buffer_ptr(&c->output),
                    890:                            buffer_len(&c->output));
                    891:                if (len <= 0)
                    892:                        buffer_consume(&c->output, buffer_len(&c->output));
                    893:                else
                    894:                        buffer_consume(&c->output, len);
                    895:        }
                    896: }
1.25      markus    897:
1.41      markus    898: void
1.44      markus    899: channel_handler_init_20(void)
                    900: {
                    901:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_20;
1.51      markus    902:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
1.44      markus    903:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
1.73      markus    904:        channel_pre[SSH_CHANNEL_RPORT_LISTENER] =       &channel_pre_listener;
1.51      markus    905:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
1.73      markus    906:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1.75      markus    907:        channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1.44      markus    908:
                    909:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_2;
                    910:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
1.73      markus    911:        channel_post[SSH_CHANNEL_RPORT_LISTENER] =      &channel_post_port_listener;
1.51      markus    912:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
1.73      markus    913:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1.75      markus    914:        channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1.44      markus    915: }
                    916:
                    917: void
1.41      markus    918: channel_handler_init_13(void)
                    919: {
                    920:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_13;
                    921:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open_13;
                    922:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
                    923:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
                    924:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
                    925:        channel_pre[SSH_CHANNEL_INPUT_DRAINING] =       &channel_pre_input_draining;
                    926:        channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] =      &channel_pre_output_draining;
1.75      markus    927:        channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1.25      markus    928:
1.41      markus    929:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_1;
                    930:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
                    931:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
                    932:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
                    933:        channel_post[SSH_CHANNEL_OUTPUT_DRAINING] =     &channel_post_output_drain_13;
1.75      markus    934:        channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1.41      markus    935: }
1.25      markus    936:
1.41      markus    937: void
                    938: channel_handler_init_15(void)
                    939: {
                    940:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_15;
1.51      markus    941:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
1.41      markus    942:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
                    943:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
                    944:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1.75      markus    945:        channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1.25      markus    946:
1.41      markus    947:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
                    948:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
                    949:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
                    950:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_1;
1.75      markus    951:        channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1.41      markus    952: }
1.27      markus    953:
1.41      markus    954: void
                    955: channel_handler_init(void)
                    956: {
                    957:        int i;
                    958:        for(i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
                    959:                channel_pre[i] = NULL;
                    960:                channel_post[i] = NULL;
                    961:        }
1.44      markus    962:        if (compat20)
                    963:                channel_handler_init_20();
                    964:        else if (compat13)
1.41      markus    965:                channel_handler_init_13();
                    966:        else
                    967:                channel_handler_init_15();
                    968: }
1.25      markus    969:
1.49      markus    970: void
1.41      markus    971: channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
                    972: {
                    973:        static int did_init = 0;
                    974:        int i;
                    975:        Channel *c;
1.25      markus    976:
1.41      markus    977:        if (!did_init) {
                    978:                channel_handler_init();
                    979:                did_init = 1;
                    980:        }
                    981:        for (i = 0; i < channels_alloc; i++) {
                    982:                c = &channels[i];
                    983:                if (c->type == SSH_CHANNEL_FREE)
                    984:                        continue;
                    985:                if (ftab[c->type] == NULL)
1.25      markus    986:                        continue;
1.41      markus    987:                (*ftab[c->type])(c, readset, writeset);
1.44      markus    988:                chan_delete_if_full_closed(c);
1.1       deraadt   989:        }
                    990: }
                    991:
1.49      markus    992: void
1.84      markus    993: channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp)
1.41      markus    994: {
1.84      markus    995:        int n;
                    996:        u_int sz;
                    997:
                    998:        n = MAX(*maxfdp, channel_max_fd);
                    999:
                   1000:        sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
                   1001:        if (*readsetp == NULL || n > *maxfdp) {
                   1002:                if (*readsetp)
                   1003:                        xfree(*readsetp);
                   1004:                if (*writesetp)
                   1005:                        xfree(*writesetp);
                   1006:                *readsetp = xmalloc(sz);
                   1007:                *writesetp = xmalloc(sz);
                   1008:                *maxfdp = n;
                   1009:        }
                   1010:        memset(*readsetp, 0, sz);
                   1011:        memset(*writesetp, 0, sz);
                   1012:
                   1013:        channel_handler(channel_pre, *readsetp, *writesetp);
1.41      markus   1014: }
                   1015:
1.49      markus   1016: void
1.41      markus   1017: channel_after_select(fd_set * readset, fd_set * writeset)
                   1018: {
                   1019:        channel_handler(channel_post, readset, writeset);
                   1020: }
                   1021:
1.84      markus   1022: /* If there is data to send to the connection, enqueue some of it now. */
1.1       deraadt  1023:
1.49      markus   1024: void
1.25      markus   1025: channel_output_poll()
1.1       deraadt  1026: {
1.25      markus   1027:        int len, i;
1.41      markus   1028:        Channel *c;
1.1       deraadt  1029:
1.25      markus   1030:        for (i = 0; i < channels_alloc; i++) {
1.41      markus   1031:                c = &channels[i];
1.37      markus   1032:
1.27      markus   1033:                /* We are only interested in channels that can have buffered incoming data. */
1.37      markus   1034:                if (compat13) {
1.41      markus   1035:                        if (c->type != SSH_CHANNEL_OPEN &&
                   1036:                            c->type != SSH_CHANNEL_INPUT_DRAINING)
1.37      markus   1037:                                continue;
                   1038:                } else {
1.41      markus   1039:                        if (c->type != SSH_CHANNEL_OPEN)
1.37      markus   1040:                                continue;
1.41      markus   1041:                        if (c->istate != CHAN_INPUT_OPEN &&
                   1042:                            c->istate != CHAN_INPUT_WAIT_DRAIN)
1.37      markus   1043:                                continue;
                   1044:                }
1.46      markus   1045:                if (compat20 &&
                   1046:                    (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1.44      markus   1047:                        debug("channel: %d: no data after CLOSE", c->self);
                   1048:                        continue;
                   1049:                }
1.25      markus   1050:
                   1051:                /* Get the amount of buffered data for this channel. */
1.41      markus   1052:                len = buffer_len(&c->input);
1.25      markus   1053:                if (len > 0) {
1.27      markus   1054:                        /* Send some data for the other side over the secure connection. */
1.44      markus   1055:                        if (compat20) {
                   1056:                                if (len > c->remote_window)
                   1057:                                        len = c->remote_window;
                   1058:                                if (len > c->remote_maxpacket)
                   1059:                                        len = c->remote_maxpacket;
1.25      markus   1060:                        } else {
1.44      markus   1061:                                if (packet_is_interactive()) {
                   1062:                                        if (len > 1024)
                   1063:                                                len = 512;
                   1064:                                } else {
                   1065:                                        /* Keep the packets at reasonable size. */
                   1066:                                        if (len > packet_get_maxsize()/2)
                   1067:                                                len = packet_get_maxsize()/2;
                   1068:                                }
1.25      markus   1069:                        }
1.41      markus   1070:                        if (len > 0) {
1.44      markus   1071:                                packet_start(compat20 ?
                   1072:                                    SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1.41      markus   1073:                                packet_put_int(c->remote_id);
                   1074:                                packet_put_string(buffer_ptr(&c->input), len);
                   1075:                                packet_send();
                   1076:                                buffer_consume(&c->input, len);
                   1077:                                c->remote_window -= len;
                   1078:                        }
                   1079:                } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1.25      markus   1080:                        if (compat13)
                   1081:                                fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1.27      markus   1082:                        /*
                   1083:                         * input-buffer is empty and read-socket shutdown:
                   1084:                         * tell peer, that we will not send more data: send IEOF
                   1085:                         */
1.41      markus   1086:                        chan_ibuf_empty(c);
1.25      markus   1087:                }
1.44      markus   1088:                /* Send extended data, i.e. stderr */
                   1089:                if (compat20 &&
                   1090:                    c->remote_window > 0 &&
                   1091:                    (len = buffer_len(&c->extended)) > 0 &&
                   1092:                    c->extended_usage == CHAN_EXTENDED_READ) {
                   1093:                        if (len > c->remote_window)
                   1094:                                len = c->remote_window;
                   1095:                        if (len > c->remote_maxpacket)
                   1096:                                len = c->remote_maxpacket;
                   1097:                        packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
                   1098:                        packet_put_int(c->remote_id);
                   1099:                        packet_put_int(SSH2_EXTENDED_DATA_STDERR);
                   1100:                        packet_put_string(buffer_ptr(&c->extended), len);
                   1101:                        packet_send();
                   1102:                        buffer_consume(&c->extended, len);
                   1103:                        c->remote_window -= len;
                   1104:                }
1.25      markus   1105:        }
1.1       deraadt  1106: }
                   1107:
1.27      markus   1108: /*
                   1109:  * This is called when a packet of type CHANNEL_DATA has just been received.
                   1110:  * The message type has already been consumed, but channel number and data is
                   1111:  * still there.
                   1112:  */
1.1       deraadt  1113:
1.49      markus   1114: void
1.69      markus   1115: channel_input_data(int type, int plen, void *ctxt)
1.1       deraadt  1116: {
1.37      markus   1117:        int id;
1.25      markus   1118:        char *data;
1.77      markus   1119:        u_int data_len;
1.41      markus   1120:        Channel *c;
1.25      markus   1121:
                   1122:        /* Get the channel number and verify it. */
1.37      markus   1123:        id = packet_get_int();
1.41      markus   1124:        c = channel_lookup(id);
                   1125:        if (c == NULL)
1.37      markus   1126:                packet_disconnect("Received data for nonexistent channel %d.", id);
1.25      markus   1127:
                   1128:        /* Ignore any data for non-open channels (might happen on close) */
1.41      markus   1129:        if (c->type != SSH_CHANNEL_OPEN &&
                   1130:            c->type != SSH_CHANNEL_X11_OPEN)
1.37      markus   1131:                return;
                   1132:
                   1133:        /* same for protocol 1.5 if output end is no longer open */
1.41      markus   1134:        if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
1.25      markus   1135:                return;
                   1136:
                   1137:        /* Get the data. */
                   1138:        data = packet_get_string(&data_len);
1.48      markus   1139:        packet_done();
1.41      markus   1140:
1.44      markus   1141:        if (compat20){
                   1142:                if (data_len > c->local_maxpacket) {
                   1143:                        log("channel %d: rcvd big packet %d, maxpack %d",
                   1144:                            c->self, data_len, c->local_maxpacket);
                   1145:                }
                   1146:                if (data_len > c->local_window) {
                   1147:                        log("channel %d: rcvd too much data %d, win %d",
                   1148:                            c->self, data_len, c->local_window);
                   1149:                        xfree(data);
                   1150:                        return;
                   1151:                }
                   1152:                c->local_window -= data_len;
                   1153:        }else{
                   1154:                packet_integrity_check(plen, 4 + 4 + data_len, type);
                   1155:        }
1.41      markus   1156:        buffer_append(&c->output, data, data_len);
1.25      markus   1157:        xfree(data);
1.1       deraadt  1158: }
1.49      markus   1159: void
1.69      markus   1160: channel_input_extended_data(int type, int plen, void *ctxt)
1.44      markus   1161: {
                   1162:        int id;
                   1163:        int tcode;
                   1164:        char *data;
1.77      markus   1165:        u_int data_len;
1.44      markus   1166:        Channel *c;
                   1167:
                   1168:        /* Get the channel number and verify it. */
                   1169:        id = packet_get_int();
                   1170:        c = channel_lookup(id);
                   1171:
                   1172:        if (c == NULL)
                   1173:                packet_disconnect("Received extended_data for bad channel %d.", id);
                   1174:        if (c->type != SSH_CHANNEL_OPEN) {
                   1175:                log("channel %d: ext data for non open", id);
                   1176:                return;
                   1177:        }
                   1178:        tcode = packet_get_int();
                   1179:        if (c->efd == -1 ||
                   1180:            c->extended_usage != CHAN_EXTENDED_WRITE ||
                   1181:            tcode != SSH2_EXTENDED_DATA_STDERR) {
                   1182:                log("channel %d: bad ext data", c->self);
                   1183:                return;
                   1184:        }
                   1185:        data = packet_get_string(&data_len);
1.48      markus   1186:        packet_done();
1.44      markus   1187:        if (data_len > c->local_window) {
                   1188:                log("channel %d: rcvd too much extended_data %d, win %d",
                   1189:                    c->self, data_len, c->local_window);
                   1190:                xfree(data);
                   1191:                return;
                   1192:        }
1.70      markus   1193:        debug2("channel %d: rcvd ext data %d", c->self, data_len);
1.44      markus   1194:        c->local_window -= data_len;
                   1195:        buffer_append(&c->extended, data, data_len);
                   1196:        xfree(data);
                   1197: }
                   1198:
1.1       deraadt  1199:
1.27      markus   1200: /*
                   1201:  * Returns true if no channel has too much buffered data, and false if one or
                   1202:  * more channel is overfull.
                   1203:  */
1.1       deraadt  1204:
1.49      markus   1205: int
1.25      markus   1206: channel_not_very_much_buffered_data()
1.1       deraadt  1207: {
1.77      markus   1208:        u_int i;
1.41      markus   1209:        Channel *c;
1.25      markus   1210:
                   1211:        for (i = 0; i < channels_alloc; i++) {
1.41      markus   1212:                c = &channels[i];
                   1213:                if (c->type == SSH_CHANNEL_OPEN) {
1.44      markus   1214:                        if (!compat20 && buffer_len(&c->input) > packet_get_maxsize()) {
1.41      markus   1215:                                debug("channel %d: big input buffer %d",
                   1216:                                    c->self, buffer_len(&c->input));
1.25      markus   1217:                                return 0;
1.41      markus   1218:                        }
                   1219:                        if (buffer_len(&c->output) > packet_get_maxsize()) {
                   1220:                                debug("channel %d: big output buffer %d",
                   1221:                                    c->self, buffer_len(&c->output));
1.25      markus   1222:                                return 0;
1.41      markus   1223:                        }
1.25      markus   1224:                }
1.1       deraadt  1225:        }
1.25      markus   1226:        return 1;
1.1       deraadt  1227: }
                   1228:
1.49      markus   1229: void
1.69      markus   1230: channel_input_ieof(int type, int plen, void *ctxt)
1.41      markus   1231: {
                   1232:        int id;
                   1233:        Channel *c;
                   1234:
                   1235:        packet_integrity_check(plen, 4, type);
                   1236:
                   1237:        id = packet_get_int();
                   1238:        c = channel_lookup(id);
                   1239:        if (c == NULL)
                   1240:                packet_disconnect("Received ieof for nonexistent channel %d.", id);
                   1241:        chan_rcvd_ieof(c);
                   1242: }
1.1       deraadt  1243:
1.49      markus   1244: void
1.69      markus   1245: channel_input_close(int type, int plen, void *ctxt)
1.1       deraadt  1246: {
1.41      markus   1247:        int id;
                   1248:        Channel *c;
1.1       deraadt  1249:
1.41      markus   1250:        packet_integrity_check(plen, 4, type);
                   1251:
                   1252:        id = packet_get_int();
                   1253:        c = channel_lookup(id);
                   1254:        if (c == NULL)
                   1255:                packet_disconnect("Received close for nonexistent channel %d.", id);
1.27      markus   1256:
                   1257:        /*
                   1258:         * Send a confirmation that we have closed the channel and no more
                   1259:         * data is coming for it.
                   1260:         */
1.25      markus   1261:        packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1.41      markus   1262:        packet_put_int(c->remote_id);
1.25      markus   1263:        packet_send();
                   1264:
1.27      markus   1265:        /*
                   1266:         * If the channel is in closed state, we have sent a close request,
                   1267:         * and the other side will eventually respond with a confirmation.
                   1268:         * Thus, we cannot free the channel here, because then there would be
                   1269:         * no-one to receive the confirmation.  The channel gets freed when
                   1270:         * the confirmation arrives.
                   1271:         */
1.41      markus   1272:        if (c->type != SSH_CHANNEL_CLOSED) {
1.27      markus   1273:                /*
                   1274:                 * Not a closed channel - mark it as draining, which will
                   1275:                 * cause it to be freed later.
                   1276:                 */
1.41      markus   1277:                buffer_consume(&c->input, buffer_len(&c->input));
                   1278:                c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1.25      markus   1279:        }
1.1       deraadt  1280: }
                   1281:
1.41      markus   1282: /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1.49      markus   1283: void
1.69      markus   1284: channel_input_oclose(int type, int plen, void *ctxt)
1.41      markus   1285: {
                   1286:        int id = packet_get_int();
                   1287:        Channel *c = channel_lookup(id);
                   1288:        packet_integrity_check(plen, 4, type);
                   1289:        if (c == NULL)
                   1290:                packet_disconnect("Received oclose for nonexistent channel %d.", id);
                   1291:        chan_rcvd_oclose(c);
                   1292: }
1.1       deraadt  1293:
1.49      markus   1294: void
1.69      markus   1295: channel_input_close_confirmation(int type, int plen, void *ctxt)
1.1       deraadt  1296: {
1.41      markus   1297:        int id = packet_get_int();
                   1298:        Channel *c = channel_lookup(id);
1.1       deraadt  1299:
1.48      markus   1300:        packet_done();
1.41      markus   1301:        if (c == NULL)
                   1302:                packet_disconnect("Received close confirmation for "
                   1303:                    "out-of-range channel %d.", id);
                   1304:        if (c->type != SSH_CHANNEL_CLOSED)
                   1305:                packet_disconnect("Received close confirmation for "
                   1306:                    "non-closed channel %d (type %d).", id, c->type);
                   1307:        channel_free(c->self);
1.1       deraadt  1308: }
                   1309:
1.49      markus   1310: void
1.69      markus   1311: channel_input_open_confirmation(int type, int plen, void *ctxt)
1.1       deraadt  1312: {
1.41      markus   1313:        int id, remote_id;
                   1314:        Channel *c;
1.1       deraadt  1315:
1.44      markus   1316:        if (!compat20)
                   1317:                packet_integrity_check(plen, 4 + 4, type);
1.25      markus   1318:
1.41      markus   1319:        id = packet_get_int();
                   1320:        c = channel_lookup(id);
1.25      markus   1321:
1.41      markus   1322:        if (c==NULL || c->type != SSH_CHANNEL_OPENING)
                   1323:                packet_disconnect("Received open confirmation for "
                   1324:                    "non-opening channel %d.", id);
                   1325:        remote_id = packet_get_int();
1.27      markus   1326:        /* Record the remote channel number and mark that the channel is now open. */
1.41      markus   1327:        c->remote_id = remote_id;
                   1328:        c->type = SSH_CHANNEL_OPEN;
1.44      markus   1329:
                   1330:        if (compat20) {
                   1331:                c->remote_window = packet_get_int();
                   1332:                c->remote_maxpacket = packet_get_int();
1.48      markus   1333:                packet_done();
1.44      markus   1334:                if (c->cb_fn != NULL && c->cb_event == type) {
1.70      markus   1335:                        debug2("callback start");
1.44      markus   1336:                        c->cb_fn(c->self, c->cb_arg);
1.70      markus   1337:                        debug2("callback done");
1.44      markus   1338:                }
                   1339:                debug("channel %d: open confirm rwindow %d rmax %d", c->self,
                   1340:                    c->remote_window, c->remote_maxpacket);
                   1341:        }
1.1       deraadt  1342: }
                   1343:
1.49      markus   1344: void
1.69      markus   1345: channel_input_open_failure(int type, int plen, void *ctxt)
1.1       deraadt  1346: {
1.86      markus   1347:        int id, reason;
                   1348:        char *msg = NULL, *lang = NULL;
1.41      markus   1349:        Channel *c;
                   1350:
1.44      markus   1351:        if (!compat20)
                   1352:                packet_integrity_check(plen, 4, type);
1.41      markus   1353:
                   1354:        id = packet_get_int();
                   1355:        c = channel_lookup(id);
1.25      markus   1356:
1.41      markus   1357:        if (c==NULL || c->type != SSH_CHANNEL_OPENING)
                   1358:                packet_disconnect("Received open failure for "
                   1359:                    "non-opening channel %d.", id);
1.44      markus   1360:        if (compat20) {
1.86      markus   1361:                reason = packet_get_int();
                   1362:                if (packet_remaining() > 0) {
                   1363:                        msg  = packet_get_string(NULL);
                   1364:                        lang = packet_get_string(NULL);
                   1365:                }
1.48      markus   1366:                packet_done();
1.86      markus   1367:                log("channel_open_failure: %d: reason %d %s", id,
                   1368:                    reason, msg ? msg : "<no additional info>");
                   1369:                if (msg != NULL)
                   1370:                        xfree(msg);
                   1371:                if (lang != NULL)
                   1372:                        xfree(lang);
1.44      markus   1373:        }
1.25      markus   1374:        /* Free the channel.  This will also close the socket. */
1.41      markus   1375:        channel_free(id);
1.1       deraadt  1376: }
                   1377:
1.44      markus   1378: void
1.69      markus   1379: channel_input_channel_request(int type, int plen, void *ctxt)
1.44      markus   1380: {
                   1381:        int id;
                   1382:        Channel *c;
                   1383:
                   1384:        id = packet_get_int();
                   1385:        c = channel_lookup(id);
                   1386:
                   1387:        if (c == NULL ||
                   1388:            (c->type != SSH_CHANNEL_OPEN && c->type != SSH_CHANNEL_LARVAL))
                   1389:                packet_disconnect("Received request for "
                   1390:                    "non-open channel %d.", id);
                   1391:        if (c->cb_fn != NULL && c->cb_event == type) {
1.70      markus   1392:                debug2("callback start");
1.44      markus   1393:                c->cb_fn(c->self, c->cb_arg);
1.70      markus   1394:                debug2("callback done");
1.44      markus   1395:        } else {
                   1396:                char *service = packet_get_string(NULL);
                   1397:                debug("channel: %d rcvd request for %s", c->self, service);
1.70      markus   1398:                debug("cb_fn %p cb_event %d", c->cb_fn , c->cb_event);
1.44      markus   1399:                xfree(service);
                   1400:        }
                   1401: }
                   1402:
1.49      markus   1403: void
1.69      markus   1404: channel_input_window_adjust(int type, int plen, void *ctxt)
1.44      markus   1405: {
                   1406:        Channel *c;
                   1407:        int id, adjust;
                   1408:
                   1409:        if (!compat20)
                   1410:                return;
                   1411:
                   1412:        /* Get the channel number and verify it. */
                   1413:        id = packet_get_int();
                   1414:        c = channel_lookup(id);
                   1415:
                   1416:        if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
                   1417:                log("Received window adjust for "
                   1418:                    "non-open channel %d.", id);
                   1419:                return;
                   1420:        }
                   1421:        adjust = packet_get_int();
1.48      markus   1422:        packet_done();
1.70      markus   1423:        debug2("channel %d: rcvd adjust %d", id, adjust);
1.44      markus   1424:        c->remote_window += adjust;
                   1425: }
                   1426:
1.27      markus   1427: /*
                   1428:  * Stops listening for channels, and removes any unix domain sockets that we
                   1429:  * might have.
                   1430:  */
1.1       deraadt  1431:
1.49      markus   1432: void
1.25      markus   1433: channel_stop_listening()
1.1       deraadt  1434: {
1.25      markus   1435:        int i;
                   1436:        for (i = 0; i < channels_alloc; i++) {
                   1437:                switch (channels[i].type) {
                   1438:                case SSH_CHANNEL_AUTH_SOCKET:
                   1439:                        close(channels[i].sock);
1.76      markus   1440:                        unlink(channels[i].path);
1.25      markus   1441:                        channel_free(i);
                   1442:                        break;
                   1443:                case SSH_CHANNEL_PORT_LISTENER:
1.73      markus   1444:                case SSH_CHANNEL_RPORT_LISTENER:
1.25      markus   1445:                case SSH_CHANNEL_X11_LISTENER:
                   1446:                        close(channels[i].sock);
                   1447:                        channel_free(i);
                   1448:                        break;
                   1449:                default:
                   1450:                        break;
                   1451:                }
1.1       deraadt  1452:        }
                   1453: }
                   1454:
1.27      markus   1455: /*
1.52      markus   1456:  * Closes the sockets/fds of all channels.  This is used to close extra file
1.27      markus   1457:  * descriptors after a fork.
                   1458:  */
1.1       deraadt  1459:
1.49      markus   1460: void
1.25      markus   1461: channel_close_all()
1.1       deraadt  1462: {
1.25      markus   1463:        int i;
1.52      markus   1464:        for (i = 0; i < channels_alloc; i++)
1.25      markus   1465:                if (channels[i].type != SSH_CHANNEL_FREE)
1.52      markus   1466:                        channel_close_fds(&channels[i]);
1.1       deraadt  1467: }
                   1468:
                   1469: /* Returns true if any channel is still open. */
                   1470:
1.49      markus   1471: int
1.25      markus   1472: channel_still_open()
1.1       deraadt  1473: {
1.77      markus   1474:        u_int i;
1.25      markus   1475:        for (i = 0; i < channels_alloc; i++)
                   1476:                switch (channels[i].type) {
                   1477:                case SSH_CHANNEL_FREE:
                   1478:                case SSH_CHANNEL_X11_LISTENER:
                   1479:                case SSH_CHANNEL_PORT_LISTENER:
1.73      markus   1480:                case SSH_CHANNEL_RPORT_LISTENER:
1.25      markus   1481:                case SSH_CHANNEL_CLOSED:
                   1482:                case SSH_CHANNEL_AUTH_SOCKET:
1.75      markus   1483:                case SSH_CHANNEL_CONNECTING:    /* XXX ??? */
1.25      markus   1484:                        continue;
1.44      markus   1485:                case SSH_CHANNEL_LARVAL:
                   1486:                        if (!compat20)
                   1487:                                fatal("cannot happen: SSH_CHANNEL_LARVAL");
                   1488:                        continue;
1.25      markus   1489:                case SSH_CHANNEL_OPENING:
                   1490:                case SSH_CHANNEL_OPEN:
                   1491:                case SSH_CHANNEL_X11_OPEN:
                   1492:                        return 1;
                   1493:                case SSH_CHANNEL_INPUT_DRAINING:
                   1494:                case SSH_CHANNEL_OUTPUT_DRAINING:
                   1495:                        if (!compat13)
                   1496:                                fatal("cannot happen: OUT_DRAIN");
                   1497:                        return 1;
                   1498:                default:
                   1499:                        fatal("channel_still_open: bad channel type %d", channels[i].type);
                   1500:                        /* NOTREACHED */
                   1501:                }
                   1502:        return 0;
1.1       deraadt  1503: }
                   1504:
1.27      markus   1505: /*
                   1506:  * Returns a message describing the currently open forwarded connections,
                   1507:  * suitable for sending to the client.  The message contains crlf pairs for
                   1508:  * newlines.
                   1509:  */
1.1       deraadt  1510:
1.25      markus   1511: char *
                   1512: channel_open_message()
1.1       deraadt  1513: {
1.25      markus   1514:        Buffer buffer;
                   1515:        int i;
                   1516:        char buf[512], *cp;
                   1517:
                   1518:        buffer_init(&buffer);
                   1519:        snprintf(buf, sizeof buf, "The following connections are open:\r\n");
1.1       deraadt  1520:        buffer_append(&buffer, buf, strlen(buf));
1.25      markus   1521:        for (i = 0; i < channels_alloc; i++) {
                   1522:                Channel *c = &channels[i];
                   1523:                switch (c->type) {
                   1524:                case SSH_CHANNEL_FREE:
                   1525:                case SSH_CHANNEL_X11_LISTENER:
                   1526:                case SSH_CHANNEL_PORT_LISTENER:
1.73      markus   1527:                case SSH_CHANNEL_RPORT_LISTENER:
1.25      markus   1528:                case SSH_CHANNEL_CLOSED:
                   1529:                case SSH_CHANNEL_AUTH_SOCKET:
                   1530:                        continue;
1.44      markus   1531:                case SSH_CHANNEL_LARVAL:
1.25      markus   1532:                case SSH_CHANNEL_OPENING:
1.75      markus   1533:                case SSH_CHANNEL_CONNECTING:
1.25      markus   1534:                case SSH_CHANNEL_OPEN:
                   1535:                case SSH_CHANNEL_X11_OPEN:
                   1536:                case SSH_CHANNEL_INPUT_DRAINING:
                   1537:                case SSH_CHANNEL_OUTPUT_DRAINING:
1.41      markus   1538:                        snprintf(buf, sizeof buf, "  #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
1.37      markus   1539:                            c->self, c->remote_name,
                   1540:                            c->type, c->remote_id,
                   1541:                            c->istate, buffer_len(&c->input),
1.41      markus   1542:                            c->ostate, buffer_len(&c->output),
                   1543:                            c->rfd, c->wfd);
1.25      markus   1544:                        buffer_append(&buffer, buf, strlen(buf));
                   1545:                        continue;
                   1546:                default:
1.41      markus   1547:                        fatal("channel_open_message: bad channel type %d", c->type);
1.25      markus   1548:                        /* NOTREACHED */
                   1549:                }
                   1550:        }
                   1551:        buffer_append(&buffer, "\0", 1);
                   1552:        cp = xstrdup(buffer_ptr(&buffer));
                   1553:        buffer_free(&buffer);
                   1554:        return cp;
1.1       deraadt  1555: }
                   1556:
1.27      markus   1557: /*
                   1558:  * Initiate forwarding of connections to local port "port" through the secure
                   1559:  * channel to host:port from remote side.
                   1560:  */
1.87      markus   1561: int
1.73      markus   1562: channel_request_local_forwarding(u_short listen_port, const char *host_to_connect,
                   1563:     u_short port_to_connect, int gateway_ports)
                   1564: {
1.87      markus   1565:        return channel_request_forwarding(
1.73      markus   1566:            NULL, listen_port,
                   1567:            host_to_connect, port_to_connect,
                   1568:            gateway_ports, /*remote_fwd*/ 0);
                   1569: }
1.1       deraadt  1570:
1.73      markus   1571: /*
                   1572:  * If 'remote_fwd' is true we have a '-R style' listener for protocol 2
                   1573:  * (SSH_CHANNEL_RPORT_LISTENER).
                   1574:  */
1.87      markus   1575: int
1.73      markus   1576: channel_request_forwarding(
                   1577:     const char *listen_address, u_short listen_port,
                   1578:     const char *host_to_connect, u_short port_to_connect,
                   1579:     int gateway_ports, int remote_fwd)
1.25      markus   1580: {
1.73      markus   1581:        int success, ch, sock, on = 1, ctype;
1.35      markus   1582:        struct addrinfo hints, *ai, *aitop;
                   1583:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1.73      markus   1584:        const char *host;
1.28      markus   1585:        struct linger linger;
1.25      markus   1586:
1.87      markus   1587:        success = 0;
                   1588:
1.73      markus   1589:        if (remote_fwd) {
                   1590:                host = listen_address;
1.89      stevesk  1591:                ctype = SSH_CHANNEL_RPORT_LISTENER;
1.73      markus   1592:        } else {
                   1593:                host = host_to_connect;
                   1594:                ctype  =SSH_CHANNEL_PORT_LISTENER;
                   1595:        }
                   1596:
1.87      markus   1597:        if (strlen(host) > sizeof(channels[0].path) - 1) {
                   1598:                error("Forward host name too long.");
                   1599:                return success;
                   1600:        }
1.25      markus   1601:
1.73      markus   1602:        /* XXX listen_address is currently ignored */
1.28      markus   1603:        /*
1.35      markus   1604:         * getaddrinfo returns a loopback address if the hostname is
                   1605:         * set to NULL and hints.ai_flags is not AI_PASSIVE
1.28      markus   1606:         */
1.35      markus   1607:        memset(&hints, 0, sizeof(hints));
                   1608:        hints.ai_family = IPv4or6;
                   1609:        hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
                   1610:        hints.ai_socktype = SOCK_STREAM;
1.73      markus   1611:        snprintf(strport, sizeof strport, "%d", listen_port);
1.35      markus   1612:        if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
                   1613:                packet_disconnect("getaddrinfo: fatal error");
                   1614:
                   1615:        for (ai = aitop; ai; ai = ai->ai_next) {
                   1616:                if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   1617:                        continue;
                   1618:                if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
                   1619:                    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1.73      markus   1620:                        error("channel_request_forwarding: getnameinfo failed");
1.35      markus   1621:                        continue;
                   1622:                }
                   1623:                /* Create a port to listen for the host. */
                   1624:                sock = socket(ai->ai_family, SOCK_STREAM, 0);
                   1625:                if (sock < 0) {
                   1626:                        /* this is no error since kernel may not support ipv6 */
                   1627:                        verbose("socket: %.100s", strerror(errno));
                   1628:                        continue;
                   1629:                }
                   1630:                /*
                   1631:                 * Set socket options.  We would like the socket to disappear
                   1632:                 * as soon as it has been closed for whatever reason.
                   1633:                 */
                   1634:                setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
                   1635:                linger.l_onoff = 1;
                   1636:                linger.l_linger = 5;
                   1637:                setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
                   1638:                debug("Local forwarding listening on %s port %s.", ntop, strport);
                   1639:
                   1640:                /* Bind the socket to the address. */
                   1641:                if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   1642:                        /* address can be in use ipv6 address is already bound */
                   1643:                        verbose("bind: %.100s", strerror(errno));
                   1644:                        close(sock);
                   1645:                        continue;
                   1646:                }
                   1647:                /* Start listening for connections on the socket. */
                   1648:                if (listen(sock, 5) < 0) {
                   1649:                        error("listen: %.100s", strerror(errno));
                   1650:                        close(sock);
                   1651:                        continue;
                   1652:                }
                   1653:                /* Allocate a channel number for the socket. */
1.73      markus   1654:                ch = channel_new("port listener", ctype, sock, sock, -1,
1.51      markus   1655:                    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1.71      markus   1656:                    0, xstrdup("port listener"), 1);
1.35      markus   1657:                strlcpy(channels[ch].path, host, sizeof(channels[ch].path));
1.73      markus   1658:                channels[ch].host_port = port_to_connect;
                   1659:                channels[ch].listening_port = listen_port;
1.35      markus   1660:                success = 1;
                   1661:        }
                   1662:        if (success == 0)
1.87      markus   1663:                error("channel_request_forwarding: cannot listen to port: %d",
                   1664:                    listen_port);
1.35      markus   1665:        freeaddrinfo(aitop);
1.87      markus   1666:        return success;
1.25      markus   1667: }
1.1       deraadt  1668:
1.27      markus   1669: /*
                   1670:  * Initiate forwarding of connections to port "port" on remote host through
                   1671:  * the secure channel to host:port from local side.
                   1672:  */
1.1       deraadt  1673:
1.49      markus   1674: void
1.73      markus   1675: channel_request_remote_forwarding(u_short listen_port,
                   1676:     const char *host_to_connect, u_short port_to_connect)
1.25      markus   1677: {
1.73      markus   1678:        int payload_len, type, success = 0;
                   1679:
1.25      markus   1680:        /* Record locally that connection to this host/port is permitted. */
                   1681:        if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
                   1682:                fatal("channel_request_remote_forwarding: too many forwards");
                   1683:
                   1684:        /* Send the forward request to the remote side. */
1.44      markus   1685:        if (compat20) {
                   1686:                const char *address_to_bind = "0.0.0.0";
                   1687:                packet_start(SSH2_MSG_GLOBAL_REQUEST);
                   1688:                packet_put_cstring("tcpip-forward");
                   1689:                packet_put_char(0);                     /* boolean: want reply */
                   1690:                packet_put_cstring(address_to_bind);
                   1691:                packet_put_int(listen_port);
1.73      markus   1692:                packet_send();
                   1693:                packet_write_wait();
                   1694:                /* Assume that server accepts the request */
                   1695:                success = 1;
1.44      markus   1696:        } else {
                   1697:                packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1.50      markus   1698:                packet_put_int(listen_port);
                   1699:                packet_put_cstring(host_to_connect);
1.44      markus   1700:                packet_put_int(port_to_connect);
                   1701:                packet_send();
                   1702:                packet_write_wait();
1.73      markus   1703:
                   1704:                /* Wait for response from the remote side. */
                   1705:                type = packet_read(&payload_len);
                   1706:                switch (type) {
                   1707:                case SSH_SMSG_SUCCESS:
                   1708:                        success = 1;
                   1709:                        break;
                   1710:                case SSH_SMSG_FAILURE:
                   1711:                        log("Warning: Server denied remote port forwarding.");
                   1712:                        break;
                   1713:                default:
                   1714:                        /* Unknown packet */
                   1715:                        packet_disconnect("Protocol error for port forward request:"
                   1716:                            "received packet type %d.", type);
                   1717:                }
                   1718:        }
                   1719:        if (success) {
                   1720:                permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
                   1721:                permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
                   1722:                permitted_opens[num_permitted_opens].listen_port = listen_port;
                   1723:                num_permitted_opens++;
1.44      markus   1724:        }
1.1       deraadt  1725: }
                   1726:
1.27      markus   1727: /*
                   1728:  * This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
                   1729:  * listening for the port, and sends back a success reply (or disconnect
                   1730:  * message if there was an error).  This never returns if there was an error.
                   1731:  */
1.1       deraadt  1732:
1.49      markus   1733: void
1.56      markus   1734: channel_input_port_forward_request(int is_root, int gateway_ports)
1.1       deraadt  1735: {
1.31      markus   1736:        u_short port, host_port;
1.25      markus   1737:        char *hostname;
1.1       deraadt  1738:
1.25      markus   1739:        /* Get arguments from the packet. */
                   1740:        port = packet_get_int();
                   1741:        hostname = packet_get_string(NULL);
                   1742:        host_port = packet_get_int();
                   1743:
1.27      markus   1744:        /*
                   1745:         * Check that an unprivileged user is not trying to forward a
                   1746:         * privileged port.
                   1747:         */
1.25      markus   1748:        if (port < IPPORT_RESERVED && !is_root)
                   1749:                packet_disconnect("Requested forwarding of port %d but user is not root.",
                   1750:                                  port);
1.73      markus   1751:        /* Initiate forwarding */
1.56      markus   1752:        channel_request_local_forwarding(port, hostname, host_port, gateway_ports);
1.25      markus   1753:
                   1754:        /* Free the argument string. */
                   1755:        xfree(hostname);
1.1       deraadt  1756: }
                   1757:
1.41      markus   1758: /* XXX move to aux.c */
                   1759: int
                   1760: channel_connect_to(const char *host, u_short host_port)
                   1761: {
                   1762:        struct addrinfo hints, *ai, *aitop;
                   1763:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
                   1764:        int gaierr;
                   1765:        int sock = -1;
                   1766:
                   1767:        memset(&hints, 0, sizeof(hints));
                   1768:        hints.ai_family = IPv4or6;
                   1769:        hints.ai_socktype = SOCK_STREAM;
                   1770:        snprintf(strport, sizeof strport, "%d", host_port);
                   1771:        if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
                   1772:                error("%.100s: unknown host (%s)", host, gai_strerror(gaierr));
                   1773:                return -1;
                   1774:        }
                   1775:        for (ai = aitop; ai; ai = ai->ai_next) {
                   1776:                if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   1777:                        continue;
                   1778:                if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
                   1779:                    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
                   1780:                        error("channel_connect_to: getnameinfo failed");
                   1781:                        continue;
                   1782:                }
                   1783:                /* Create the socket. */
                   1784:                sock = socket(ai->ai_family, SOCK_STREAM, 0);
                   1785:                if (sock < 0) {
                   1786:                        error("socket: %.100s", strerror(errno));
                   1787:                        continue;
                   1788:                }
1.80      markus   1789:                if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0)
1.75      markus   1790:                        fatal("connect_to: F_SETFL: %s", strerror(errno));
1.41      markus   1791:                /* Connect to the host/port. */
1.75      markus   1792:                if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
                   1793:                    errno != EINPROGRESS) {
1.41      markus   1794:                        error("connect %.100s port %s: %.100s", ntop, strport,
                   1795:                            strerror(errno));
                   1796:                        close(sock);
1.89      stevesk  1797:                        continue;       /* fail -- try next */
1.41      markus   1798:                }
                   1799:                break; /* success */
                   1800:
                   1801:        }
                   1802:        freeaddrinfo(aitop);
                   1803:        if (!ai) {
1.89      stevesk  1804:                error("connect %.100s port %d: failed.", host, host_port);
1.41      markus   1805:                return -1;
                   1806:        }
                   1807:        /* success */
                   1808:        return sock;
                   1809: }
1.73      markus   1810: int
                   1811: channel_connect_by_listen_adress(u_short listen_port)
                   1812: {
                   1813:        int i;
                   1814:        for (i = 0; i < num_permitted_opens; i++)
                   1815:                if (permitted_opens[i].listen_port == listen_port)
                   1816:                        return channel_connect_to(
                   1817:                            permitted_opens[i].host_to_connect,
                   1818:                            permitted_opens[i].port_to_connect);
1.74      markus   1819:        error("WARNING: Server requests forwarding for unknown listen_port %d",
                   1820:            listen_port);
1.73      markus   1821:        return -1;
                   1822: }
                   1823:
1.27      markus   1824: /*
                   1825:  * This is called after receiving PORT_OPEN message.  This attempts to
                   1826:  * connect to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION
                   1827:  * or CHANNEL_OPEN_FAILURE.
                   1828:  */
1.1       deraadt  1829:
1.49      markus   1830: void
1.69      markus   1831: channel_input_port_open(int type, int plen, void *ctxt)
1.1       deraadt  1832: {
1.31      markus   1833:        u_short host_port;
1.25      markus   1834:        char *host, *originator_string;
1.41      markus   1835:        int remote_channel, sock = -1, newch, i, denied;
1.77      markus   1836:        u_int host_len, originator_len;
1.25      markus   1837:
                   1838:        /* Get remote channel number. */
                   1839:        remote_channel = packet_get_int();
                   1840:
                   1841:        /* Get host name to connect to. */
                   1842:        host = packet_get_string(&host_len);
                   1843:
                   1844:        /* Get port to connect to. */
                   1845:        host_port = packet_get_int();
                   1846:
                   1847:        /* Get remote originator name. */
1.29      markus   1848:        if (have_hostname_in_open) {
1.25      markus   1849:                originator_string = packet_get_string(&originator_len);
1.29      markus   1850:                originator_len += 4;    /* size of packet_int */
                   1851:        } else {
1.25      markus   1852:                originator_string = xstrdup("unknown (remote did not supply name)");
1.29      markus   1853:                originator_len = 0;     /* no originator supplied */
                   1854:        }
1.25      markus   1855:
1.41      markus   1856:        packet_integrity_check(plen,
                   1857:            4 + 4 + host_len + 4 + originator_len, SSH_MSG_PORT_OPEN);
1.25      markus   1858:
                   1859:        /* Check if opening that port is permitted. */
1.41      markus   1860:        denied = 0;
1.25      markus   1861:        if (!all_opens_permitted) {
                   1862:                /* Go trough all permitted ports. */
                   1863:                for (i = 0; i < num_permitted_opens; i++)
1.41      markus   1864:                        if (permitted_opens[i].port_to_connect == host_port &&
                   1865:                            strcmp(permitted_opens[i].host_to_connect, host) == 0)
1.25      markus   1866:                                break;
                   1867:
                   1868:                /* Check if we found the requested port among those permitted. */
                   1869:                if (i >= num_permitted_opens) {
                   1870:                        /* The port is not permitted. */
                   1871:                        log("Received request to connect to %.100s:%d, but the request was denied.",
                   1872:                            host, host_port);
1.41      markus   1873:                        denied = 1;
1.25      markus   1874:                }
                   1875:        }
1.41      markus   1876:        sock = denied ? -1 : channel_connect_to(host, host_port);
                   1877:        if (sock > 0) {
                   1878:                /* Allocate a channel for this connection. */
1.75      markus   1879:                newch = channel_allocate(SSH_CHANNEL_CONNECTING,
                   1880:                    sock, originator_string);
                   1881: /*XXX delay answer? */
1.41      markus   1882:                channels[newch].remote_id = remote_channel;
                   1883:
                   1884:                packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1885:                packet_put_int(remote_channel);
                   1886:                packet_put_int(newch);
                   1887:                packet_send();
                   1888:        } else {
                   1889:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   1890:                packet_put_int(remote_channel);
                   1891:                packet_send();
1.25      markus   1892:        }
                   1893:        xfree(host);
1.1       deraadt  1894: }
                   1895:
1.27      markus   1896: /*
                   1897:  * Creates an internet domain socket for listening for X11 connections.
                   1898:  * Returns a suitable value for the DISPLAY variable, or NULL if an error
                   1899:  * occurs.
                   1900:  */
1.1       deraadt  1901:
1.35      markus   1902: #define        NUM_SOCKS       10
                   1903:
1.25      markus   1904: char *
1.33      markus   1905: x11_create_display_inet(int screen_number, int x11_display_offset)
1.1       deraadt  1906: {
1.31      markus   1907:        int display_number, sock;
                   1908:        u_short port;
1.35      markus   1909:        struct addrinfo hints, *ai, *aitop;
                   1910:        char strport[NI_MAXSERV];
                   1911:        int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
                   1912:        char display[512];
1.25      markus   1913:        char hostname[MAXHOSTNAMELEN];
                   1914:
1.33      markus   1915:        for (display_number = x11_display_offset;
1.25      markus   1916:             display_number < MAX_DISPLAYS;
                   1917:             display_number++) {
                   1918:                port = 6000 + display_number;
1.35      markus   1919:                memset(&hints, 0, sizeof(hints));
                   1920:                hints.ai_family = IPv4or6;
1.36      markus   1921:                hints.ai_flags = AI_PASSIVE;            /* XXX loopback only ? */
1.35      markus   1922:                hints.ai_socktype = SOCK_STREAM;
                   1923:                snprintf(strport, sizeof strport, "%d", port);
                   1924:                if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
                   1925:                        error("getaddrinfo: %.100s", gai_strerror(gaierr));
1.25      markus   1926:                        return NULL;
                   1927:                }
1.35      markus   1928:                for (ai = aitop; ai; ai = ai->ai_next) {
                   1929:                        if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   1930:                                continue;
                   1931:                        sock = socket(ai->ai_family, SOCK_STREAM, 0);
                   1932:                        if (sock < 0) {
                   1933:                                error("socket: %.100s", strerror(errno));
                   1934:                                return NULL;
                   1935:                        }
                   1936:                        if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   1937:                                debug("bind port %d: %.100s", port, strerror(errno));
                   1938:                                shutdown(sock, SHUT_RDWR);
                   1939:                                close(sock);
                   1940:                                for (n = 0; n < num_socks; n++) {
                   1941:                                        shutdown(socks[n], SHUT_RDWR);
                   1942:                                        close(socks[n]);
                   1943:                                }
                   1944:                                num_socks = 0;
                   1945:                                break;
                   1946:                        }
                   1947:                        socks[num_socks++] = sock;
                   1948:                        if (num_socks == NUM_SOCKS)
                   1949:                                break;
1.25      markus   1950:                }
1.83      stevesk  1951:                freeaddrinfo(aitop);
1.35      markus   1952:                if (num_socks > 0)
                   1953:                        break;
1.25      markus   1954:        }
                   1955:        if (display_number >= MAX_DISPLAYS) {
                   1956:                error("Failed to allocate internet-domain X11 display socket.");
                   1957:                return NULL;
                   1958:        }
                   1959:        /* Start listening for connections on the socket. */
1.35      markus   1960:        for (n = 0; n < num_socks; n++) {
                   1961:                sock = socks[n];
                   1962:                if (listen(sock, 5) < 0) {
                   1963:                        error("listen: %.100s", strerror(errno));
                   1964:                        shutdown(sock, SHUT_RDWR);
                   1965:                        close(sock);
                   1966:                        return NULL;
                   1967:                }
1.25      markus   1968:        }
1.35      markus   1969:
1.25      markus   1970:        /* Set up a suitable value for the DISPLAY variable. */
                   1971:        if (gethostname(hostname, sizeof(hostname)) < 0)
                   1972:                fatal("gethostname: %.100s", strerror(errno));
1.35      markus   1973:        snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
1.25      markus   1974:                 display_number, screen_number);
                   1975:
1.35      markus   1976:        /* Allocate a channel for each socket. */
                   1977:        for (n = 0; n < num_socks; n++) {
                   1978:                sock = socks[n];
1.51      markus   1979:                (void) channel_new("x11 listener",
                   1980:                    SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
                   1981:                    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
1.71      markus   1982:                    0, xstrdup("X11 inet listener"), 1);
1.35      markus   1983:        }
1.1       deraadt  1984:
1.25      markus   1985:        /* Return a suitable value for the DISPLAY environment variable. */
1.35      markus   1986:        return xstrdup(display);
1.1       deraadt  1987: }
                   1988:
                   1989: #ifndef X_UNIX_PATH
                   1990: #define X_UNIX_PATH "/tmp/.X11-unix/X"
                   1991: #endif
                   1992:
                   1993: static
                   1994: int
1.77      markus   1995: connect_local_xsocket(u_int dnr)
1.1       deraadt  1996: {
1.25      markus   1997:        static const char *const x_sockets[] = {
                   1998:                X_UNIX_PATH "%u",
                   1999:                "/var/X/.X11-unix/X" "%u",
                   2000:                "/usr/spool/sockets/X11/" "%u",
                   2001:                NULL
                   2002:        };
                   2003:        int sock;
                   2004:        struct sockaddr_un addr;
                   2005:        const char *const * path;
                   2006:
                   2007:        for (path = x_sockets; *path; ++path) {
                   2008:                sock = socket(AF_UNIX, SOCK_STREAM, 0);
                   2009:                if (sock < 0)
                   2010:                        error("socket: %.100s", strerror(errno));
                   2011:                memset(&addr, 0, sizeof(addr));
                   2012:                addr.sun_family = AF_UNIX;
                   2013:                snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
                   2014:                if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
                   2015:                        return sock;
                   2016:                close(sock);
                   2017:        }
                   2018:        error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
                   2019:        return -1;
1.1       deraadt  2020: }
                   2021:
1.51      markus   2022: int
                   2023: x11_connect_display(void)
1.1       deraadt  2024: {
1.51      markus   2025:        int display_number, sock = 0;
1.25      markus   2026:        const char *display;
1.51      markus   2027:        char buf[1024], *cp;
1.35      markus   2028:        struct addrinfo hints, *ai, *aitop;
                   2029:        char strport[NI_MAXSERV];
                   2030:        int gaierr;
1.25      markus   2031:
                   2032:        /* Try to open a socket for the local X server. */
                   2033:        display = getenv("DISPLAY");
                   2034:        if (!display) {
                   2035:                error("DISPLAY not set.");
1.51      markus   2036:                return -1;
1.25      markus   2037:        }
1.27      markus   2038:        /*
                   2039:         * Now we decode the value of the DISPLAY variable and make a
                   2040:         * connection to the real X server.
                   2041:         */
                   2042:
                   2043:        /*
                   2044:         * Check if it is a unix domain socket.  Unix domain displays are in
                   2045:         * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
                   2046:         */
1.25      markus   2047:        if (strncmp(display, "unix:", 5) == 0 ||
                   2048:            display[0] == ':') {
                   2049:                /* Connect to the unix domain socket. */
                   2050:                if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
                   2051:                        error("Could not parse display number from DISPLAY: %.100s",
                   2052:                              display);
1.51      markus   2053:                        return -1;
1.25      markus   2054:                }
                   2055:                /* Create a socket. */
                   2056:                sock = connect_local_xsocket(display_number);
                   2057:                if (sock < 0)
1.51      markus   2058:                        return -1;
1.25      markus   2059:
                   2060:                /* OK, we now have a connection to the display. */
1.51      markus   2061:                return sock;
1.25      markus   2062:        }
1.27      markus   2063:        /*
                   2064:         * Connect to an inet socket.  The DISPLAY value is supposedly
                   2065:         * hostname:d[.s], where hostname may also be numeric IP address.
                   2066:         */
1.25      markus   2067:        strncpy(buf, display, sizeof(buf));
                   2068:        buf[sizeof(buf) - 1] = 0;
                   2069:        cp = strchr(buf, ':');
                   2070:        if (!cp) {
                   2071:                error("Could not find ':' in DISPLAY: %.100s", display);
1.51      markus   2072:                return -1;
1.25      markus   2073:        }
                   2074:        *cp = 0;
1.27      markus   2075:        /* buf now contains the host name.  But first we parse the display number. */
1.25      markus   2076:        if (sscanf(cp + 1, "%d", &display_number) != 1) {
                   2077:                error("Could not parse display number from DISPLAY: %.100s",
                   2078:                      display);
1.51      markus   2079:                return -1;
1.25      markus   2080:        }
1.35      markus   2081:
                   2082:        /* Look up the host address */
                   2083:        memset(&hints, 0, sizeof(hints));
                   2084:        hints.ai_family = IPv4or6;
                   2085:        hints.ai_socktype = SOCK_STREAM;
                   2086:        snprintf(strport, sizeof strport, "%d", 6000 + display_number);
                   2087:        if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
                   2088:                error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
1.51      markus   2089:                return -1;
1.25      markus   2090:        }
1.35      markus   2091:        for (ai = aitop; ai; ai = ai->ai_next) {
                   2092:                /* Create a socket. */
                   2093:                sock = socket(ai->ai_family, SOCK_STREAM, 0);
                   2094:                if (sock < 0) {
                   2095:                        debug("socket: %.100s", strerror(errno));
1.41      markus   2096:                        continue;
                   2097:                }
                   2098:                /* Connect it to the display. */
                   2099:                if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   2100:                        debug("connect %.100s port %d: %.100s", buf,
                   2101:                            6000 + display_number, strerror(errno));
                   2102:                        close(sock);
                   2103:                        continue;
                   2104:                }
                   2105:                /* Success */
                   2106:                break;
1.35      markus   2107:        }
                   2108:        freeaddrinfo(aitop);
                   2109:        if (!ai) {
1.49      markus   2110:                error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
1.35      markus   2111:                    strerror(errno));
1.51      markus   2112:                return -1;
1.25      markus   2113:        }
1.51      markus   2114:        return sock;
                   2115: }
                   2116:
                   2117: /*
                   2118:  * This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
                   2119:  * the remote channel number.  We should do whatever we want, and respond
                   2120:  * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
                   2121:  */
                   2122:
                   2123: void
1.69      markus   2124: x11_input_open(int type, int plen, void *ctxt)
1.51      markus   2125: {
                   2126:        int remote_channel, sock = 0, newch;
                   2127:        char *remote_host;
1.77      markus   2128:        u_int remote_len;
1.25      markus   2129:
1.51      markus   2130:        /* Get remote channel number. */
                   2131:        remote_channel = packet_get_int();
                   2132:
                   2133:        /* Get remote originator name. */
                   2134:        if (have_hostname_in_open) {
                   2135:                remote_host = packet_get_string(&remote_len);
                   2136:                remote_len += 4;
                   2137:        } else {
                   2138:                remote_host = xstrdup("unknown (remote did not supply name)");
                   2139:                remote_len = 0;
                   2140:        }
1.25      markus   2141:
1.51      markus   2142:        debug("Received X11 open request.");
                   2143:        packet_integrity_check(plen, 4 + remote_len, SSH_SMSG_X11_OPEN);
1.25      markus   2144:
1.51      markus   2145:        /* Obtain a connection to the real X display. */
                   2146:        sock = x11_connect_display();
                   2147:        if (sock == -1) {
                   2148:                /* Send refusal to the remote host. */
                   2149:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   2150:                packet_put_int(remote_channel);
                   2151:                packet_send();
                   2152:        } else {
                   2153:                /* Allocate a channel for this connection. */
                   2154:                newch = channel_allocate(
                   2155:                     (x11_saved_proto == NULL) ?
                   2156:                     SSH_CHANNEL_OPEN : SSH_CHANNEL_X11_OPEN,
                   2157:                     sock, remote_host);
                   2158:                channels[newch].remote_id = remote_channel;
1.25      markus   2159:
1.51      markus   2160:                /* Send a confirmation to the remote host. */
                   2161:                packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
                   2162:                packet_put_int(remote_channel);
                   2163:                packet_put_int(newch);
                   2164:                packet_send();
                   2165:        }
1.72      markus   2166: }
                   2167:
                   2168: /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
                   2169: void
                   2170: deny_input_open(int type, int plen, void *ctxt)
                   2171: {
                   2172:        int rchan = packet_get_int();
                   2173:        switch(type){
                   2174:        case SSH_SMSG_AGENT_OPEN:
                   2175:                error("Warning: ssh server tried agent forwarding.");
                   2176:                break;
                   2177:        case SSH_SMSG_X11_OPEN:
                   2178:                error("Warning: ssh server tried X11 forwarding.");
                   2179:                break;
                   2180:        default:
                   2181:                error("deny_input_open: type %d plen %d", type, plen);
                   2182:                break;
                   2183:        }
                   2184:        error("Warning: this is probably a break in attempt by a malicious server.");
                   2185:        packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   2186:        packet_put_int(rchan);
                   2187:        packet_send();
1.1       deraadt  2188: }
                   2189:
1.27      markus   2190: /*
                   2191:  * Requests forwarding of X11 connections, generates fake authentication
                   2192:  * data, and enables authentication spoofing.
                   2193:  */
1.1       deraadt  2194:
1.49      markus   2195: void
1.51      markus   2196: x11_request_forwarding_with_spoofing(int client_session_id,
                   2197:     const char *proto, const char *data)
1.1       deraadt  2198: {
1.77      markus   2199:        u_int data_len = (u_int) strlen(data) / 2;
1.90      markus   2200:        u_int i, value, len;
1.25      markus   2201:        char *new_data;
                   2202:        int screen_number;
                   2203:        const char *cp;
                   2204:        u_int32_t rand = 0;
                   2205:
                   2206:        cp = getenv("DISPLAY");
                   2207:        if (cp)
                   2208:                cp = strchr(cp, ':');
                   2209:        if (cp)
                   2210:                cp = strchr(cp, '.');
                   2211:        if (cp)
                   2212:                screen_number = atoi(cp + 1);
                   2213:        else
                   2214:                screen_number = 0;
                   2215:
                   2216:        /* Save protocol name. */
                   2217:        x11_saved_proto = xstrdup(proto);
                   2218:
1.27      markus   2219:        /*
                   2220:         * Extract real authentication data and generate fake data of the
                   2221:         * same length.
                   2222:         */
1.25      markus   2223:        x11_saved_data = xmalloc(data_len);
                   2224:        x11_fake_data = xmalloc(data_len);
                   2225:        for (i = 0; i < data_len; i++) {
                   2226:                if (sscanf(data + 2 * i, "%2x", &value) != 1)
                   2227:                        fatal("x11_request_forwarding: bad authentication data: %.100s", data);
                   2228:                if (i % 4 == 0)
                   2229:                        rand = arc4random();
                   2230:                x11_saved_data[i] = value;
                   2231:                x11_fake_data[i] = rand & 0xff;
                   2232:                rand >>= 8;
                   2233:        }
                   2234:        x11_saved_data_len = data_len;
                   2235:        x11_fake_data_len = data_len;
                   2236:
                   2237:        /* Convert the fake data into hex. */
1.90      markus   2238:        len = 2 * data_len + 1;
                   2239:        new_data = xmalloc(len);
1.25      markus   2240:        for (i = 0; i < data_len; i++)
1.90      markus   2241:                snprintf(new_data + 2 * i, len - 2 * i,
                   2242:                    "%02x", (u_char) x11_fake_data[i]);
1.25      markus   2243:
                   2244:        /* Send the request packet. */
1.51      markus   2245:        if (compat20) {
                   2246:                channel_request_start(client_session_id, "x11-req", 0);
                   2247:                packet_put_char(0);     /* XXX bool single connection */
                   2248:        } else {
                   2249:                packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
                   2250:        }
                   2251:        packet_put_cstring(proto);
                   2252:        packet_put_cstring(new_data);
1.25      markus   2253:        packet_put_int(screen_number);
                   2254:        packet_send();
                   2255:        packet_write_wait();
                   2256:        xfree(new_data);
1.1       deraadt  2257: }
                   2258:
                   2259: /* Sends a message to the server to request authentication fd forwarding. */
                   2260:
1.49      markus   2261: void
1.25      markus   2262: auth_request_forwarding()
1.1       deraadt  2263: {
1.25      markus   2264:        packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
                   2265:        packet_send();
                   2266:        packet_write_wait();
1.1       deraadt  2267: }
                   2268:
1.27      markus   2269: /*
                   2270:  * Returns the name of the forwarded authentication socket.  Returns NULL if
                   2271:  * there is no forwarded authentication socket.  The returned value points to
                   2272:  * a static buffer.
                   2273:  */
1.1       deraadt  2274:
1.25      markus   2275: char *
                   2276: auth_get_socket_name()
1.1       deraadt  2277: {
1.25      markus   2278:        return channel_forwarded_auth_socket_name;
1.1       deraadt  2279: }
                   2280:
1.12      markus   2281: /* removes the agent forwarding socket */
                   2282:
1.49      markus   2283: void
1.25      markus   2284: cleanup_socket(void)
                   2285: {
1.78      markus   2286:        unlink(channel_forwarded_auth_socket_name);
1.25      markus   2287:        rmdir(channel_forwarded_auth_socket_dir);
1.12      markus   2288: }
                   2289:
1.27      markus   2290: /*
1.59      markus   2291:  * This is called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
1.27      markus   2292:  * This starts forwarding authentication requests.
                   2293:  */
1.1       deraadt  2294:
1.59      markus   2295: int
1.25      markus   2296: auth_input_request_forwarding(struct passwd * pw)
1.1       deraadt  2297: {
1.25      markus   2298:        int sock, newch;
                   2299:        struct sockaddr_un sunaddr;
                   2300:
                   2301:        if (auth_get_socket_name() != NULL)
                   2302:                fatal("Protocol error: authentication forwarding requested twice.");
                   2303:
                   2304:        /* Temporarily drop privileged uid for mkdir/bind. */
                   2305:        temporarily_use_uid(pw->pw_uid);
                   2306:
                   2307:        /* Allocate a buffer for the socket name, and format the name. */
                   2308:        channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
                   2309:        channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
                   2310:        strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
                   2311:
                   2312:        /* Create private directory for socket */
1.59      markus   2313:        if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL) {
                   2314:                packet_send_debug("Agent forwarding disabled: mkdtemp() failed: %.100s",
                   2315:                    strerror(errno));
                   2316:                restore_uid();
                   2317:                xfree(channel_forwarded_auth_socket_name);
                   2318:                xfree(channel_forwarded_auth_socket_dir);
                   2319:                channel_forwarded_auth_socket_name = NULL;
                   2320:                channel_forwarded_auth_socket_dir = NULL;
                   2321:                return 0;
                   2322:        }
1.25      markus   2323:        snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME, "%s/agent.%d",
                   2324:                 channel_forwarded_auth_socket_dir, (int) getpid());
                   2325:
                   2326:        if (atexit(cleanup_socket) < 0) {
                   2327:                int saved = errno;
                   2328:                cleanup_socket();
                   2329:                packet_disconnect("socket: %.100s", strerror(saved));
                   2330:        }
                   2331:        /* Create the socket. */
                   2332:        sock = socket(AF_UNIX, SOCK_STREAM, 0);
                   2333:        if (sock < 0)
                   2334:                packet_disconnect("socket: %.100s", strerror(errno));
                   2335:
                   2336:        /* Bind it to the name. */
                   2337:        memset(&sunaddr, 0, sizeof(sunaddr));
                   2338:        sunaddr.sun_family = AF_UNIX;
                   2339:        strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
                   2340:                sizeof(sunaddr.sun_path));
                   2341:
                   2342:        if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
                   2343:                packet_disconnect("bind: %.100s", strerror(errno));
                   2344:
                   2345:        /* Restore the privileged uid. */
                   2346:        restore_uid();
                   2347:
                   2348:        /* Start listening on the socket. */
                   2349:        if (listen(sock, 5) < 0)
                   2350:                packet_disconnect("listen: %.100s", strerror(errno));
                   2351:
                   2352:        /* Allocate a channel for the authentication agent socket. */
1.73      markus   2353:        newch = channel_new("auth socket",
                   2354:            SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
                   2355:            CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
                   2356:            0, xstrdup("auth socket"), 1);
                   2357:
1.32      deraadt  2358:        strlcpy(channels[newch].path, channel_forwarded_auth_socket_name,
                   2359:            sizeof(channels[newch].path));
1.59      markus   2360:        return 1;
1.1       deraadt  2361: }
                   2362:
                   2363: /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
                   2364:
1.49      markus   2365: void
1.69      markus   2366: auth_input_open_request(int type, int plen, void *ctxt)
1.1       deraadt  2367: {
1.25      markus   2368:        int remch, sock, newch;
                   2369:        char *dummyname;
1.41      markus   2370:
                   2371:        packet_integrity_check(plen, 4, type);
1.25      markus   2372:
                   2373:        /* Read the remote channel number from the message. */
                   2374:        remch = packet_get_int();
                   2375:
1.27      markus   2376:        /*
                   2377:         * Get a connection to the local authentication agent (this may again
                   2378:         * get forwarded).
                   2379:         */
1.25      markus   2380:        sock = ssh_get_authentication_socket();
                   2381:
1.27      markus   2382:        /*
                   2383:         * If we could not connect the agent, send an error message back to
                   2384:         * the server. This should never happen unless the agent dies,
                   2385:         * because authentication forwarding is only enabled if we have an
                   2386:         * agent.
                   2387:         */
1.25      markus   2388:        if (sock < 0) {
                   2389:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   2390:                packet_put_int(remch);
                   2391:                packet_send();
                   2392:                return;
                   2393:        }
                   2394:        debug("Forwarding authentication connection.");
1.1       deraadt  2395:
1.27      markus   2396:        /*
                   2397:         * Dummy host name.  This will be freed when the channel is freed; it
                   2398:         * will still be valid in the packet_put_string below since the
                   2399:         * channel cannot yet be freed at that point.
                   2400:         */
1.25      markus   2401:        dummyname = xstrdup("authentication agent connection");
                   2402:
                   2403:        newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
                   2404:        channels[newch].remote_id = remch;
                   2405:
                   2406:        /* Send a confirmation to the remote host. */
                   2407:        packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
                   2408:        packet_put_int(remch);
                   2409:        packet_put_int(newch);
1.44      markus   2410:        packet_send();
                   2411: }
                   2412:
                   2413: void
1.51      markus   2414: channel_start_open(int id)
1.44      markus   2415: {
                   2416:        Channel *c = channel_lookup(id);
                   2417:        if (c == NULL) {
                   2418:                log("channel_open: %d: bad id", id);
                   2419:                return;
                   2420:        }
1.51      markus   2421:        debug("send channel open %d", id);
1.44      markus   2422:        packet_start(SSH2_MSG_CHANNEL_OPEN);
                   2423:        packet_put_cstring(c->ctype);
                   2424:        packet_put_int(c->self);
                   2425:        packet_put_int(c->local_window);
                   2426:        packet_put_int(c->local_maxpacket);
1.51      markus   2427: }
                   2428: void
                   2429: channel_open(int id)
                   2430: {
                   2431:        /* XXX REMOVE ME */
                   2432:        channel_start_open(id);
1.44      markus   2433:        packet_send();
                   2434: }
                   2435: void
                   2436: channel_request(int id, char *service, int wantconfirm)
                   2437: {
                   2438:        channel_request_start(id, service, wantconfirm);
                   2439:        packet_send();
                   2440:        debug("channel request %d: %s", id, service) ;
                   2441: }
                   2442: void
                   2443: channel_request_start(int id, char *service, int wantconfirm)
                   2444: {
                   2445:        Channel *c = channel_lookup(id);
                   2446:        if (c == NULL) {
                   2447:                log("channel_request: %d: bad id", id);
                   2448:                return;
                   2449:        }
                   2450:        packet_start(SSH2_MSG_CHANNEL_REQUEST);
                   2451:        packet_put_int(c->remote_id);
                   2452:        packet_put_cstring(service);
                   2453:        packet_put_char(wantconfirm);
                   2454: }
                   2455: void
                   2456: channel_register_callback(int id, int mtype, channel_callback_fn *fn, void *arg)
                   2457: {
                   2458:        Channel *c = channel_lookup(id);
                   2459:        if (c == NULL) {
                   2460:                log("channel_register_callback: %d: bad id", id);
                   2461:                return;
                   2462:        }
                   2463:        c->cb_event = mtype;
                   2464:        c->cb_fn = fn;
                   2465:        c->cb_arg = arg;
                   2466: }
                   2467: void
                   2468: channel_register_cleanup(int id, channel_callback_fn *fn)
                   2469: {
                   2470:        Channel *c = channel_lookup(id);
                   2471:        if (c == NULL) {
                   2472:                log("channel_register_cleanup: %d: bad id", id);
                   2473:                return;
                   2474:        }
                   2475:        c->dettach_user = fn;
                   2476: }
                   2477: void
                   2478: channel_cancel_cleanup(int id)
                   2479: {
                   2480:        Channel *c = channel_lookup(id);
                   2481:        if (c == NULL) {
                   2482:                log("channel_cancel_cleanup: %d: bad id", id);
                   2483:                return;
                   2484:        }
                   2485:        c->dettach_user = NULL;
1.65      markus   2486: }
1.89      stevesk  2487: void
1.65      markus   2488: channel_register_filter(int id, channel_filter_fn *fn)
                   2489: {
                   2490:        Channel *c = channel_lookup(id);
                   2491:        if (c == NULL) {
                   2492:                log("channel_register_filter: %d: bad id", id);
                   2493:                return;
                   2494:        }
                   2495:        c->input_filter = fn;
1.44      markus   2496: }
                   2497:
                   2498: void
1.71      markus   2499: channel_set_fds(int id, int rfd, int wfd, int efd,
                   2500:     int extusage, int nonblock)
1.44      markus   2501: {
                   2502:        Channel *c = channel_lookup(id);
                   2503:        if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
                   2504:                fatal("channel_activate for non-larval channel %d.", id);
1.71      markus   2505:        channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
1.44      markus   2506:        c->type = SSH_CHANNEL_OPEN;
                   2507:        /* XXX window size? */
1.68      markus   2508:        c->local_window = c->local_window_max = c->local_maxpacket * 2;
1.44      markus   2509:        packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
                   2510:        packet_put_int(c->remote_id);
                   2511:        packet_put_int(c->local_window);
1.25      markus   2512:        packet_send();
1.1       deraadt  2513: }