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

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