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

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.113   ! markus     43: RCSID("$OpenBSD: channels.c,v 1.112 2001/05/04 14:34:34 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: {
                    845:        if (FD_ISSET(c->sock, writeset)) {
                    846:                int err = 0;
                    847:                int sz = sizeof(err);
                    848:                c->type = SSH_CHANNEL_OPEN;
1.89      stevesk   849:                if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, (char *)&err, &sz) < 0) {
1.75      markus    850:                        debug("getsockopt SO_ERROR failed");
                    851:                } else {
                    852:                        if (err == 0) {
1.111     stevesk   853:                                debug("channel %d: connected", c->self);
1.75      markus    854:                        } else {
                    855:                                debug("channel %d: not connected: %s",
                    856:                                    c->self, strerror(err));
                    857:                                chan_read_failed(c);
                    858:                                chan_write_failed(c);
                    859:                        }
                    860:                }
                    861:        }
                    862: }
                    863:
1.41      markus    864: int
                    865: channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
                    866: {
                    867:        char buf[16*1024];
                    868:        int len;
1.25      markus    869:
1.41      markus    870:        if (c->rfd != -1 &&
                    871:            FD_ISSET(c->rfd, readset)) {
                    872:                len = read(c->rfd, buf, sizeof(buf));
1.53      markus    873:                if (len < 0 && (errno == EINTR || errno == EAGAIN))
                    874:                        return 1;
1.41      markus    875:                if (len <= 0) {
1.51      markus    876:                        debug("channel %d: read<=0 rfd %d len %d",
1.41      markus    877:                            c->self, c->rfd, len);
1.104     markus    878:                        if (c->type != SSH_CHANNEL_OPEN) {
                    879:                                debug("channel %d: not open", c->self);
1.113   ! markus    880:                                chan_mark_dead(c);
1.103     markus    881:                                return -1;
1.104     markus    882:                        } else if (compat13) {
1.41      markus    883:                                buffer_consume(&c->output, buffer_len(&c->output));
                    884:                                c->type = SSH_CHANNEL_INPUT_DRAINING;
1.105     markus    885:                                debug("channel %d: status set to input draining.", c->self);
1.25      markus    886:                        } else {
1.41      markus    887:                                chan_read_failed(c);
1.25      markus    888:                        }
1.41      markus    889:                        return -1;
                    890:                }
1.65      markus    891:                if(c->input_filter != NULL) {
1.66      markus    892:                        if (c->input_filter(c, buf, len) == -1) {
1.105     markus    893:                                debug("channel %d: filter stops", c->self);
1.65      markus    894:                                chan_read_failed(c);
                    895:                        }
                    896:                } else {
                    897:                        buffer_append(&c->input, buf, len);
                    898:                }
1.41      markus    899:        }
                    900:        return 1;
                    901: }
                    902: int
                    903: channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
                    904: {
1.95      markus    905:        struct termios tio;
1.41      markus    906:        int len;
1.25      markus    907:
1.41      markus    908:        /* Send buffered output data to the socket. */
                    909:        if (c->wfd != -1 &&
                    910:            FD_ISSET(c->wfd, writeset) &&
                    911:            buffer_len(&c->output) > 0) {
                    912:                len = write(c->wfd, buffer_ptr(&c->output),
1.53      markus    913:                    buffer_len(&c->output));
                    914:                if (len < 0 && (errno == EINTR || errno == EAGAIN))
                    915:                        return 1;
1.41      markus    916:                if (len <= 0) {
1.104     markus    917:                        if (c->type != SSH_CHANNEL_OPEN) {
                    918:                                debug("channel %d: not open", c->self);
1.113   ! markus    919:                                chan_mark_dead(c);
1.104     markus    920:                                return -1;
                    921:                        } else if (compat13) {
1.41      markus    922:                                buffer_consume(&c->output, buffer_len(&c->output));
1.105     markus    923:                                debug("channel %d: status set to input draining.", c->self);
1.41      markus    924:                                c->type = SSH_CHANNEL_INPUT_DRAINING;
                    925:                        } else {
                    926:                                chan_write_failed(c);
                    927:                        }
                    928:                        return -1;
1.91      markus    929:                }
                    930:                if (compat20 && c->isatty) {
                    931:                        if (tcgetattr(c->wfd, &tio) == 0 &&
                    932:                            !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
                    933:                                /*
                    934:                                 * Simulate echo to reduce the impact of
1.96      markus    935:                                 * traffic analysis. We need to match the
1.95      markus    936:                                 * size of a SSH2_MSG_CHANNEL_DATA message
                    937:                                 * (4 byte channel id + data)
1.91      markus    938:                                 */
1.95      markus    939:                                packet_send_ignore(4 + len);
1.91      markus    940:                                packet_send();
                    941:                        }
1.25      markus    942:                }
1.41      markus    943:                buffer_consume(&c->output, len);
1.44      markus    944:                if (compat20 && len > 0) {
                    945:                        c->local_consumed += len;
                    946:                }
                    947:        }
                    948:        return 1;
                    949: }
                    950: int
                    951: channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
                    952: {
                    953:        char buf[16*1024];
                    954:        int len;
                    955:
1.45      markus    956: /** XXX handle drain efd, too */
1.44      markus    957:        if (c->efd != -1) {
                    958:                if (c->extended_usage == CHAN_EXTENDED_WRITE &&
                    959:                    FD_ISSET(c->efd, writeset) &&
                    960:                    buffer_len(&c->extended) > 0) {
                    961:                        len = write(c->efd, buffer_ptr(&c->extended),
                    962:                            buffer_len(&c->extended));
1.70      markus    963:                        debug2("channel %d: written %d to efd %d",
1.44      markus    964:                            c->self, len, c->efd);
1.93      markus    965:                        if (len < 0 && (errno == EINTR || errno == EAGAIN))
                    966:                                return 1;
                    967:                        if (len <= 0) {
                    968:                                debug2("channel %d: closing write-efd %d",
                    969:                                    c->self, c->efd);
                    970:                                close(c->efd);
                    971:                                c->efd = -1;
                    972:                        } else {
1.44      markus    973:                                buffer_consume(&c->extended, len);
                    974:                                c->local_consumed += len;
                    975:                        }
                    976:                } else if (c->extended_usage == CHAN_EXTENDED_READ &&
                    977:                    FD_ISSET(c->efd, readset)) {
                    978:                        len = read(c->efd, buf, sizeof(buf));
1.70      markus    979:                        debug2("channel %d: read %d from efd %d",
1.44      markus    980:                             c->self, len, c->efd);
1.93      markus    981:                        if (len < 0 && (errno == EINTR || errno == EAGAIN))
                    982:                                return 1;
                    983:                        if (len <= 0) {
                    984:                                debug2("channel %d: closing read-efd %d",
1.45      markus    985:                                    c->self, c->efd);
                    986:                                close(c->efd);
                    987:                                c->efd = -1;
1.93      markus    988:                        } else {
1.44      markus    989:                                buffer_append(&c->extended, buf, len);
1.93      markus    990:                        }
1.44      markus    991:                }
                    992:        }
                    993:        return 1;
                    994: }
                    995: int
1.93      markus    996: channel_check_window(Channel *c)
1.44      markus    997: {
1.104     markus    998:        if (c->type == SSH_CHANNEL_OPEN &&
                    999:            !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1.44      markus   1000:            c->local_window < c->local_window_max/2 &&
                   1001:            c->local_consumed > 0) {
                   1002:                packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
                   1003:                packet_put_int(c->remote_id);
                   1004:                packet_put_int(c->local_consumed);
                   1005:                packet_send();
1.70      markus   1006:                debug2("channel %d: window %d sent adjust %d",
1.44      markus   1007:                    c->self, c->local_window,
                   1008:                    c->local_consumed);
                   1009:                c->local_window += c->local_consumed;
                   1010:                c->local_consumed = 0;
1.1       deraadt  1011:        }
1.41      markus   1012:        return 1;
1.1       deraadt  1013: }
                   1014:
1.41      markus   1015: void
                   1016: channel_post_open_1(Channel *c, fd_set * readset, fd_set * writeset)
                   1017: {
                   1018:        channel_handle_rfd(c, readset, writeset);
                   1019:        channel_handle_wfd(c, readset, writeset);
                   1020: }
1.1       deraadt  1021:
1.41      markus   1022: void
1.44      markus   1023: channel_post_open_2(Channel *c, fd_set * readset, fd_set * writeset)
                   1024: {
                   1025:        channel_handle_rfd(c, readset, writeset);
                   1026:        channel_handle_wfd(c, readset, writeset);
                   1027:        channel_handle_efd(c, readset, writeset);
1.93      markus   1028:
                   1029:        channel_check_window(c);
1.44      markus   1030: }
                   1031:
                   1032: void
1.41      markus   1033: channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
1.1       deraadt  1034: {
1.41      markus   1035:        int len;
                   1036:        /* Send buffered output data to the socket. */
                   1037:        if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
                   1038:                len = write(c->sock, buffer_ptr(&c->output),
                   1039:                            buffer_len(&c->output));
                   1040:                if (len <= 0)
                   1041:                        buffer_consume(&c->output, buffer_len(&c->output));
                   1042:                else
                   1043:                        buffer_consume(&c->output, len);
                   1044:        }
                   1045: }
1.25      markus   1046:
1.41      markus   1047: void
1.44      markus   1048: channel_handler_init_20(void)
                   1049: {
                   1050:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_20;
1.51      markus   1051:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
1.44      markus   1052:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
1.73      markus   1053:        channel_pre[SSH_CHANNEL_RPORT_LISTENER] =       &channel_pre_listener;
1.51      markus   1054:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
1.73      markus   1055:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1.75      markus   1056:        channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1.103     markus   1057:        channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1.44      markus   1058:
                   1059:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_2;
                   1060:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
1.73      markus   1061:        channel_post[SSH_CHANNEL_RPORT_LISTENER] =      &channel_post_port_listener;
1.51      markus   1062:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
1.73      markus   1063:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1.75      markus   1064:        channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1.104     markus   1065:        channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open_2;
1.44      markus   1066: }
                   1067:
                   1068: void
1.41      markus   1069: channel_handler_init_13(void)
                   1070: {
                   1071:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_13;
                   1072:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open_13;
                   1073:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
                   1074:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
                   1075:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
                   1076:        channel_pre[SSH_CHANNEL_INPUT_DRAINING] =       &channel_pre_input_draining;
                   1077:        channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] =      &channel_pre_output_draining;
1.75      markus   1078:        channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1.103     markus   1079:        channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1.25      markus   1080:
1.41      markus   1081:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_1;
                   1082:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
                   1083:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
                   1084:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
                   1085:        channel_post[SSH_CHANNEL_OUTPUT_DRAINING] =     &channel_post_output_drain_13;
1.75      markus   1086:        channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1.104     markus   1087:        channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open_1;
1.41      markus   1088: }
1.25      markus   1089:
1.41      markus   1090: void
                   1091: channel_handler_init_15(void)
                   1092: {
                   1093:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_15;
1.51      markus   1094:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
1.41      markus   1095:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
                   1096:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
                   1097:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1.75      markus   1098:        channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1.103     markus   1099:        channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1.25      markus   1100:
1.41      markus   1101:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
                   1102:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
                   1103:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
                   1104:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_1;
1.75      markus   1105:        channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1.104     markus   1106:        channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open_1;
1.41      markus   1107: }
1.27      markus   1108:
1.41      markus   1109: void
                   1110: channel_handler_init(void)
                   1111: {
                   1112:        int i;
                   1113:        for(i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
                   1114:                channel_pre[i] = NULL;
                   1115:                channel_post[i] = NULL;
                   1116:        }
1.44      markus   1117:        if (compat20)
                   1118:                channel_handler_init_20();
                   1119:        else if (compat13)
1.41      markus   1120:                channel_handler_init_13();
                   1121:        else
                   1122:                channel_handler_init_15();
                   1123: }
1.25      markus   1124:
1.49      markus   1125: void
1.41      markus   1126: channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
                   1127: {
                   1128:        static int did_init = 0;
                   1129:        int i;
                   1130:        Channel *c;
1.25      markus   1131:
1.41      markus   1132:        if (!did_init) {
                   1133:                channel_handler_init();
                   1134:                did_init = 1;
                   1135:        }
                   1136:        for (i = 0; i < channels_alloc; i++) {
1.113   ! markus   1137:                c = channels[i];
        !          1138:                if (c == NULL)
1.41      markus   1139:                        continue;
                   1140:                if (ftab[c->type] == NULL)
1.25      markus   1141:                        continue;
1.41      markus   1142:                (*ftab[c->type])(c, readset, writeset);
1.93      markus   1143:                if (chan_is_dead(c)) {
                   1144:                        /*
                   1145:                         * we have to remove the fd's from the select mask
                   1146:                         * before the channels are free'd and the fd's are
                   1147:                         * closed
                   1148:                         */
                   1149:                        if (c->wfd != -1)
                   1150:                                FD_CLR(c->wfd, writeset);
                   1151:                        if (c->rfd != -1)
                   1152:                                FD_CLR(c->rfd, readset);
                   1153:                        if (c->efd != -1) {
                   1154:                                if (c->extended_usage == CHAN_EXTENDED_READ)
                   1155:                                        FD_CLR(c->efd, readset);
                   1156:                                if (c->extended_usage == CHAN_EXTENDED_WRITE)
                   1157:                                        FD_CLR(c->efd, writeset);
                   1158:                        }
1.113   ! markus   1159:                        channel_free(c);
1.93      markus   1160:                }
1.1       deraadt  1161:        }
                   1162: }
                   1163:
1.49      markus   1164: void
1.100     markus   1165: channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
                   1166:     int rekeying)
1.41      markus   1167: {
1.84      markus   1168:        int n;
                   1169:        u_int sz;
                   1170:
                   1171:        n = MAX(*maxfdp, channel_max_fd);
                   1172:
                   1173:        sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
                   1174:        if (*readsetp == NULL || n > *maxfdp) {
                   1175:                if (*readsetp)
                   1176:                        xfree(*readsetp);
                   1177:                if (*writesetp)
                   1178:                        xfree(*writesetp);
                   1179:                *readsetp = xmalloc(sz);
                   1180:                *writesetp = xmalloc(sz);
                   1181:                *maxfdp = n;
                   1182:        }
                   1183:        memset(*readsetp, 0, sz);
                   1184:        memset(*writesetp, 0, sz);
                   1185:
1.100     markus   1186:        if (!rekeying)
                   1187:                channel_handler(channel_pre, *readsetp, *writesetp);
1.41      markus   1188: }
                   1189:
1.49      markus   1190: void
1.41      markus   1191: channel_after_select(fd_set * readset, fd_set * writeset)
                   1192: {
                   1193:        channel_handler(channel_post, readset, writeset);
                   1194: }
                   1195:
1.84      markus   1196: /* If there is data to send to the connection, enqueue some of it now. */
1.1       deraadt  1197:
1.49      markus   1198: void
1.25      markus   1199: channel_output_poll()
1.1       deraadt  1200: {
1.25      markus   1201:        int len, i;
1.41      markus   1202:        Channel *c;
1.1       deraadt  1203:
1.25      markus   1204:        for (i = 0; i < channels_alloc; i++) {
1.113   ! markus   1205:
        !          1206:                c = channels[i];
        !          1207:                if (c == NULL)
        !          1208:                        continue;
1.37      markus   1209:
1.27      markus   1210:                /* We are only interested in channels that can have buffered incoming data. */
1.37      markus   1211:                if (compat13) {
1.41      markus   1212:                        if (c->type != SSH_CHANNEL_OPEN &&
                   1213:                            c->type != SSH_CHANNEL_INPUT_DRAINING)
1.37      markus   1214:                                continue;
                   1215:                } else {
1.41      markus   1216:                        if (c->type != SSH_CHANNEL_OPEN)
1.37      markus   1217:                                continue;
                   1218:                }
1.46      markus   1219:                if (compat20 &&
                   1220:                    (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1.93      markus   1221:                        /* XXX is this true? */
1.97      markus   1222:                        debug2("channel %d: no data after CLOSE", c->self);
1.44      markus   1223:                        continue;
                   1224:                }
1.25      markus   1225:
                   1226:                /* Get the amount of buffered data for this channel. */
1.93      markus   1227:                if ((c->istate == CHAN_INPUT_OPEN ||
                   1228:                    c->istate == CHAN_INPUT_WAIT_DRAIN) &&
                   1229:                    (len = buffer_len(&c->input)) > 0) {
1.27      markus   1230:                        /* Send some data for the other side over the secure connection. */
1.44      markus   1231:                        if (compat20) {
                   1232:                                if (len > c->remote_window)
                   1233:                                        len = c->remote_window;
                   1234:                                if (len > c->remote_maxpacket)
                   1235:                                        len = c->remote_maxpacket;
1.25      markus   1236:                        } else {
1.44      markus   1237:                                if (packet_is_interactive()) {
                   1238:                                        if (len > 1024)
                   1239:                                                len = 512;
                   1240:                                } else {
                   1241:                                        /* Keep the packets at reasonable size. */
                   1242:                                        if (len > packet_get_maxsize()/2)
                   1243:                                                len = packet_get_maxsize()/2;
                   1244:                                }
1.25      markus   1245:                        }
1.41      markus   1246:                        if (len > 0) {
1.44      markus   1247:                                packet_start(compat20 ?
                   1248:                                    SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1.41      markus   1249:                                packet_put_int(c->remote_id);
                   1250:                                packet_put_string(buffer_ptr(&c->input), len);
                   1251:                                packet_send();
                   1252:                                buffer_consume(&c->input, len);
                   1253:                                c->remote_window -= len;
                   1254:                        }
                   1255:                } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1.25      markus   1256:                        if (compat13)
                   1257:                                fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1.27      markus   1258:                        /*
                   1259:                         * input-buffer is empty and read-socket shutdown:
                   1260:                         * tell peer, that we will not send more data: send IEOF
                   1261:                         */
1.41      markus   1262:                        chan_ibuf_empty(c);
1.25      markus   1263:                }
1.44      markus   1264:                /* Send extended data, i.e. stderr */
                   1265:                if (compat20 &&
                   1266:                    c->remote_window > 0 &&
                   1267:                    (len = buffer_len(&c->extended)) > 0 &&
                   1268:                    c->extended_usage == CHAN_EXTENDED_READ) {
1.93      markus   1269:                        debug2("channel %d: rwin %d elen %d euse %d",
                   1270:                            c->self, c->remote_window, buffer_len(&c->extended),
                   1271:                            c->extended_usage);
1.44      markus   1272:                        if (len > c->remote_window)
                   1273:                                len = c->remote_window;
                   1274:                        if (len > c->remote_maxpacket)
                   1275:                                len = c->remote_maxpacket;
                   1276:                        packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
                   1277:                        packet_put_int(c->remote_id);
                   1278:                        packet_put_int(SSH2_EXTENDED_DATA_STDERR);
                   1279:                        packet_put_string(buffer_ptr(&c->extended), len);
                   1280:                        packet_send();
                   1281:                        buffer_consume(&c->extended, len);
                   1282:                        c->remote_window -= len;
1.93      markus   1283:                        debug2("channel %d: sent ext data %d", c->self, len);
1.44      markus   1284:                }
1.25      markus   1285:        }
1.1       deraadt  1286: }
                   1287:
1.27      markus   1288: /*
                   1289:  * This is called when a packet of type CHANNEL_DATA has just been received.
                   1290:  * The message type has already been consumed, but channel number and data is
                   1291:  * still there.
                   1292:  */
1.1       deraadt  1293:
1.49      markus   1294: void
1.69      markus   1295: channel_input_data(int type, int plen, void *ctxt)
1.1       deraadt  1296: {
1.37      markus   1297:        int id;
1.25      markus   1298:        char *data;
1.77      markus   1299:        u_int data_len;
1.41      markus   1300:        Channel *c;
1.25      markus   1301:
                   1302:        /* Get the channel number and verify it. */
1.37      markus   1303:        id = packet_get_int();
1.41      markus   1304:        c = channel_lookup(id);
                   1305:        if (c == NULL)
1.37      markus   1306:                packet_disconnect("Received data for nonexistent channel %d.", id);
1.25      markus   1307:
                   1308:        /* Ignore any data for non-open channels (might happen on close) */
1.41      markus   1309:        if (c->type != SSH_CHANNEL_OPEN &&
                   1310:            c->type != SSH_CHANNEL_X11_OPEN)
1.37      markus   1311:                return;
                   1312:
                   1313:        /* same for protocol 1.5 if output end is no longer open */
1.41      markus   1314:        if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
1.25      markus   1315:                return;
                   1316:
                   1317:        /* Get the data. */
                   1318:        data = packet_get_string(&data_len);
1.48      markus   1319:        packet_done();
1.41      markus   1320:
1.44      markus   1321:        if (compat20){
                   1322:                if (data_len > c->local_maxpacket) {
                   1323:                        log("channel %d: rcvd big packet %d, maxpack %d",
                   1324:                            c->self, data_len, c->local_maxpacket);
                   1325:                }
                   1326:                if (data_len > c->local_window) {
                   1327:                        log("channel %d: rcvd too much data %d, win %d",
                   1328:                            c->self, data_len, c->local_window);
                   1329:                        xfree(data);
                   1330:                        return;
                   1331:                }
                   1332:                c->local_window -= data_len;
                   1333:        }else{
                   1334:                packet_integrity_check(plen, 4 + 4 + data_len, type);
                   1335:        }
1.41      markus   1336:        buffer_append(&c->output, data, data_len);
1.25      markus   1337:        xfree(data);
1.1       deraadt  1338: }
1.49      markus   1339: void
1.69      markus   1340: channel_input_extended_data(int type, int plen, void *ctxt)
1.44      markus   1341: {
                   1342:        int id;
                   1343:        int tcode;
                   1344:        char *data;
1.77      markus   1345:        u_int data_len;
1.44      markus   1346:        Channel *c;
                   1347:
                   1348:        /* Get the channel number and verify it. */
                   1349:        id = packet_get_int();
                   1350:        c = channel_lookup(id);
                   1351:
                   1352:        if (c == NULL)
                   1353:                packet_disconnect("Received extended_data for bad channel %d.", id);
                   1354:        if (c->type != SSH_CHANNEL_OPEN) {
                   1355:                log("channel %d: ext data for non open", id);
                   1356:                return;
                   1357:        }
                   1358:        tcode = packet_get_int();
                   1359:        if (c->efd == -1 ||
                   1360:            c->extended_usage != CHAN_EXTENDED_WRITE ||
                   1361:            tcode != SSH2_EXTENDED_DATA_STDERR) {
                   1362:                log("channel %d: bad ext data", c->self);
                   1363:                return;
                   1364:        }
                   1365:        data = packet_get_string(&data_len);
1.48      markus   1366:        packet_done();
1.44      markus   1367:        if (data_len > c->local_window) {
                   1368:                log("channel %d: rcvd too much extended_data %d, win %d",
                   1369:                    c->self, data_len, c->local_window);
                   1370:                xfree(data);
                   1371:                return;
                   1372:        }
1.70      markus   1373:        debug2("channel %d: rcvd ext data %d", c->self, data_len);
1.44      markus   1374:        c->local_window -= data_len;
                   1375:        buffer_append(&c->extended, data, data_len);
                   1376:        xfree(data);
                   1377: }
                   1378:
1.1       deraadt  1379:
1.27      markus   1380: /*
                   1381:  * Returns true if no channel has too much buffered data, and false if one or
                   1382:  * more channel is overfull.
                   1383:  */
1.1       deraadt  1384:
1.49      markus   1385: int
1.25      markus   1386: channel_not_very_much_buffered_data()
1.1       deraadt  1387: {
1.77      markus   1388:        u_int i;
1.41      markus   1389:        Channel *c;
1.25      markus   1390:
                   1391:        for (i = 0; i < channels_alloc; i++) {
1.113   ! markus   1392:                c = channels[i];
        !          1393:                if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
1.44      markus   1394:                        if (!compat20 && buffer_len(&c->input) > packet_get_maxsize()) {
1.41      markus   1395:                                debug("channel %d: big input buffer %d",
                   1396:                                    c->self, buffer_len(&c->input));
1.25      markus   1397:                                return 0;
1.41      markus   1398:                        }
                   1399:                        if (buffer_len(&c->output) > packet_get_maxsize()) {
                   1400:                                debug("channel %d: big output buffer %d",
                   1401:                                    c->self, buffer_len(&c->output));
1.25      markus   1402:                                return 0;
1.41      markus   1403:                        }
1.25      markus   1404:                }
1.1       deraadt  1405:        }
1.25      markus   1406:        return 1;
1.1       deraadt  1407: }
                   1408:
1.49      markus   1409: void
1.69      markus   1410: channel_input_ieof(int type, int plen, void *ctxt)
1.41      markus   1411: {
                   1412:        int id;
                   1413:        Channel *c;
                   1414:
                   1415:        packet_integrity_check(plen, 4, type);
                   1416:
                   1417:        id = packet_get_int();
                   1418:        c = channel_lookup(id);
                   1419:        if (c == NULL)
                   1420:                packet_disconnect("Received ieof for nonexistent channel %d.", id);
                   1421:        chan_rcvd_ieof(c);
                   1422: }
1.1       deraadt  1423:
1.49      markus   1424: void
1.69      markus   1425: channel_input_close(int type, int plen, void *ctxt)
1.1       deraadt  1426: {
1.41      markus   1427:        int id;
                   1428:        Channel *c;
1.1       deraadt  1429:
1.41      markus   1430:        packet_integrity_check(plen, 4, type);
                   1431:
                   1432:        id = packet_get_int();
                   1433:        c = channel_lookup(id);
                   1434:        if (c == NULL)
                   1435:                packet_disconnect("Received close for nonexistent channel %d.", id);
1.27      markus   1436:
                   1437:        /*
                   1438:         * Send a confirmation that we have closed the channel and no more
                   1439:         * data is coming for it.
                   1440:         */
1.25      markus   1441:        packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1.41      markus   1442:        packet_put_int(c->remote_id);
1.25      markus   1443:        packet_send();
                   1444:
1.27      markus   1445:        /*
                   1446:         * If the channel is in closed state, we have sent a close request,
                   1447:         * and the other side will eventually respond with a confirmation.
                   1448:         * Thus, we cannot free the channel here, because then there would be
                   1449:         * no-one to receive the confirmation.  The channel gets freed when
                   1450:         * the confirmation arrives.
                   1451:         */
1.41      markus   1452:        if (c->type != SSH_CHANNEL_CLOSED) {
1.27      markus   1453:                /*
                   1454:                 * Not a closed channel - mark it as draining, which will
                   1455:                 * cause it to be freed later.
                   1456:                 */
1.41      markus   1457:                buffer_consume(&c->input, buffer_len(&c->input));
                   1458:                c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1.25      markus   1459:        }
1.1       deraadt  1460: }
                   1461:
1.41      markus   1462: /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1.49      markus   1463: void
1.69      markus   1464: channel_input_oclose(int type, int plen, void *ctxt)
1.41      markus   1465: {
                   1466:        int id = packet_get_int();
                   1467:        Channel *c = channel_lookup(id);
                   1468:        packet_integrity_check(plen, 4, type);
                   1469:        if (c == NULL)
                   1470:                packet_disconnect("Received oclose for nonexistent channel %d.", id);
                   1471:        chan_rcvd_oclose(c);
                   1472: }
1.1       deraadt  1473:
1.49      markus   1474: void
1.69      markus   1475: channel_input_close_confirmation(int type, int plen, void *ctxt)
1.1       deraadt  1476: {
1.41      markus   1477:        int id = packet_get_int();
                   1478:        Channel *c = channel_lookup(id);
1.1       deraadt  1479:
1.48      markus   1480:        packet_done();
1.41      markus   1481:        if (c == NULL)
                   1482:                packet_disconnect("Received close confirmation for "
                   1483:                    "out-of-range channel %d.", id);
                   1484:        if (c->type != SSH_CHANNEL_CLOSED)
                   1485:                packet_disconnect("Received close confirmation for "
                   1486:                    "non-closed channel %d (type %d).", id, c->type);
1.113   ! markus   1487:        channel_free(c);
1.1       deraadt  1488: }
                   1489:
1.49      markus   1490: void
1.69      markus   1491: channel_input_open_confirmation(int type, int plen, void *ctxt)
1.1       deraadt  1492: {
1.41      markus   1493:        int id, remote_id;
                   1494:        Channel *c;
1.1       deraadt  1495:
1.44      markus   1496:        if (!compat20)
                   1497:                packet_integrity_check(plen, 4 + 4, type);
1.25      markus   1498:
1.41      markus   1499:        id = packet_get_int();
                   1500:        c = channel_lookup(id);
1.25      markus   1501:
1.41      markus   1502:        if (c==NULL || c->type != SSH_CHANNEL_OPENING)
                   1503:                packet_disconnect("Received open confirmation for "
                   1504:                    "non-opening channel %d.", id);
                   1505:        remote_id = packet_get_int();
1.27      markus   1506:        /* Record the remote channel number and mark that the channel is now open. */
1.41      markus   1507:        c->remote_id = remote_id;
                   1508:        c->type = SSH_CHANNEL_OPEN;
1.44      markus   1509:
                   1510:        if (compat20) {
                   1511:                c->remote_window = packet_get_int();
                   1512:                c->remote_maxpacket = packet_get_int();
1.48      markus   1513:                packet_done();
1.44      markus   1514:                if (c->cb_fn != NULL && c->cb_event == type) {
1.70      markus   1515:                        debug2("callback start");
1.44      markus   1516:                        c->cb_fn(c->self, c->cb_arg);
1.70      markus   1517:                        debug2("callback done");
1.44      markus   1518:                }
                   1519:                debug("channel %d: open confirm rwindow %d rmax %d", c->self,
                   1520:                    c->remote_window, c->remote_maxpacket);
                   1521:        }
1.1       deraadt  1522: }
                   1523:
1.49      markus   1524: void
1.69      markus   1525: channel_input_open_failure(int type, int plen, void *ctxt)
1.1       deraadt  1526: {
1.86      markus   1527:        int id, reason;
                   1528:        char *msg = NULL, *lang = NULL;
1.41      markus   1529:        Channel *c;
                   1530:
1.44      markus   1531:        if (!compat20)
                   1532:                packet_integrity_check(plen, 4, type);
1.41      markus   1533:
                   1534:        id = packet_get_int();
                   1535:        c = channel_lookup(id);
1.25      markus   1536:
1.41      markus   1537:        if (c==NULL || c->type != SSH_CHANNEL_OPENING)
                   1538:                packet_disconnect("Received open failure for "
                   1539:                    "non-opening channel %d.", id);
1.44      markus   1540:        if (compat20) {
1.86      markus   1541:                reason = packet_get_int();
1.110     markus   1542:                if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1.86      markus   1543:                        msg  = packet_get_string(NULL);
                   1544:                        lang = packet_get_string(NULL);
                   1545:                }
1.48      markus   1546:                packet_done();
1.86      markus   1547:                log("channel_open_failure: %d: reason %d %s", id,
                   1548:                    reason, msg ? msg : "<no additional info>");
                   1549:                if (msg != NULL)
                   1550:                        xfree(msg);
                   1551:                if (lang != NULL)
                   1552:                        xfree(lang);
1.44      markus   1553:        }
1.25      markus   1554:        /* Free the channel.  This will also close the socket. */
1.113   ! markus   1555:        channel_free(c);
1.1       deraadt  1556: }
                   1557:
1.44      markus   1558: void
1.69      markus   1559: channel_input_channel_request(int type, int plen, void *ctxt)
1.44      markus   1560: {
                   1561:        int id;
                   1562:        Channel *c;
                   1563:
                   1564:        id = packet_get_int();
                   1565:        c = channel_lookup(id);
                   1566:
                   1567:        if (c == NULL ||
                   1568:            (c->type != SSH_CHANNEL_OPEN && c->type != SSH_CHANNEL_LARVAL))
                   1569:                packet_disconnect("Received request for "
                   1570:                    "non-open channel %d.", id);
                   1571:        if (c->cb_fn != NULL && c->cb_event == type) {
1.70      markus   1572:                debug2("callback start");
1.44      markus   1573:                c->cb_fn(c->self, c->cb_arg);
1.70      markus   1574:                debug2("callback done");
1.44      markus   1575:        } else {
                   1576:                char *service = packet_get_string(NULL);
1.94      markus   1577:                debug("channel %d: rcvd request for %s", c->self, service);
1.70      markus   1578:                debug("cb_fn %p cb_event %d", c->cb_fn , c->cb_event);
1.44      markus   1579:                xfree(service);
                   1580:        }
                   1581: }
                   1582:
1.49      markus   1583: void
1.69      markus   1584: channel_input_window_adjust(int type, int plen, void *ctxt)
1.44      markus   1585: {
                   1586:        Channel *c;
                   1587:        int id, adjust;
                   1588:
                   1589:        if (!compat20)
                   1590:                return;
                   1591:
                   1592:        /* Get the channel number and verify it. */
                   1593:        id = packet_get_int();
                   1594:        c = channel_lookup(id);
                   1595:
                   1596:        if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
                   1597:                log("Received window adjust for "
                   1598:                    "non-open channel %d.", id);
                   1599:                return;
                   1600:        }
                   1601:        adjust = packet_get_int();
1.48      markus   1602:        packet_done();
1.70      markus   1603:        debug2("channel %d: rcvd adjust %d", id, adjust);
1.44      markus   1604:        c->remote_window += adjust;
                   1605: }
                   1606:
1.27      markus   1607: /*
                   1608:  * Stops listening for channels, and removes any unix domain sockets that we
                   1609:  * might have.
                   1610:  */
1.1       deraadt  1611:
1.49      markus   1612: void
1.25      markus   1613: channel_stop_listening()
1.1       deraadt  1614: {
1.25      markus   1615:        int i;
1.113   ! markus   1616:        Channel *c;
        !          1617:
1.25      markus   1618:        for (i = 0; i < channels_alloc; i++) {
1.113   ! markus   1619:                c = channels[i];
        !          1620:                if (c != NULL) {
        !          1621:                        switch (c->type) {
        !          1622:                        case SSH_CHANNEL_AUTH_SOCKET:
        !          1623:                                close(c->sock);
        !          1624:                                unlink(c->path);
        !          1625:                                channel_free(c);
        !          1626:                                break;
        !          1627:                        case SSH_CHANNEL_PORT_LISTENER:
        !          1628:                        case SSH_CHANNEL_RPORT_LISTENER:
        !          1629:                        case SSH_CHANNEL_X11_LISTENER:
        !          1630:                                close(c->sock);
        !          1631:                                channel_free(c);
        !          1632:                                break;
        !          1633:                        default:
        !          1634:                                break;
        !          1635:                        }
1.25      markus   1636:                }
1.1       deraadt  1637:        }
                   1638: }
                   1639:
1.27      markus   1640: /*
1.52      markus   1641:  * Closes the sockets/fds of all channels.  This is used to close extra file
1.27      markus   1642:  * descriptors after a fork.
                   1643:  */
1.1       deraadt  1644:
1.49      markus   1645: void
1.25      markus   1646: channel_close_all()
1.1       deraadt  1647: {
1.25      markus   1648:        int i;
1.113   ! markus   1649:
1.52      markus   1650:        for (i = 0; i < channels_alloc; i++)
1.113   ! markus   1651:                if (channels[i] != NULL)
        !          1652:                        channel_close_fds(channels[i]);
1.1       deraadt  1653: }
                   1654:
                   1655: /* Returns true if any channel is still open. */
                   1656:
1.49      markus   1657: int
1.25      markus   1658: channel_still_open()
1.1       deraadt  1659: {
1.113   ! markus   1660:        int i;
        !          1661:        Channel *c;
        !          1662:
        !          1663:        for (i = 0; i < channels_alloc; i++) {
        !          1664:                c = channels[i];
        !          1665:                if (c == NULL)
        !          1666:                        continue;
        !          1667:                switch (c->type) {
1.25      markus   1668:                case SSH_CHANNEL_X11_LISTENER:
                   1669:                case SSH_CHANNEL_PORT_LISTENER:
1.73      markus   1670:                case SSH_CHANNEL_RPORT_LISTENER:
1.25      markus   1671:                case SSH_CHANNEL_CLOSED:
                   1672:                case SSH_CHANNEL_AUTH_SOCKET:
1.103     markus   1673:                case SSH_CHANNEL_DYNAMIC:
1.75      markus   1674:                case SSH_CHANNEL_CONNECTING:    /* XXX ??? */
1.25      markus   1675:                        continue;
1.44      markus   1676:                case SSH_CHANNEL_LARVAL:
                   1677:                        if (!compat20)
                   1678:                                fatal("cannot happen: SSH_CHANNEL_LARVAL");
                   1679:                        continue;
1.25      markus   1680:                case SSH_CHANNEL_OPENING:
                   1681:                case SSH_CHANNEL_OPEN:
                   1682:                case SSH_CHANNEL_X11_OPEN:
                   1683:                        return 1;
                   1684:                case SSH_CHANNEL_INPUT_DRAINING:
                   1685:                case SSH_CHANNEL_OUTPUT_DRAINING:
                   1686:                        if (!compat13)
                   1687:                                fatal("cannot happen: OUT_DRAIN");
                   1688:                        return 1;
                   1689:                default:
1.113   ! markus   1690:                        fatal("channel_still_open: bad channel type %d", c->type);
1.25      markus   1691:                        /* NOTREACHED */
                   1692:                }
1.113   ! markus   1693:        }
1.25      markus   1694:        return 0;
1.1       deraadt  1695: }
1.107     beck     1696:
                   1697: /* Returns the id of an open channel suitable for keepaliving */
                   1698:
                   1699: int
                   1700: channel_find_open()
                   1701: {
1.113   ! markus   1702:        int i;
        !          1703:        Channel *c;
        !          1704:
        !          1705:        for (i = 0; i < channels_alloc; i++) {
        !          1706:                c = channels[i];
        !          1707:                if (c == NULL)
        !          1708:                        continue;
        !          1709:                switch (c->type) {
1.107     beck     1710:                case SSH_CHANNEL_CLOSED:
                   1711:                case SSH_CHANNEL_DYNAMIC:
                   1712:                case SSH_CHANNEL_X11_LISTENER:
                   1713:                case SSH_CHANNEL_PORT_LISTENER:
                   1714:                case SSH_CHANNEL_RPORT_LISTENER:
                   1715:                case SSH_CHANNEL_OPENING:
1.108     markus   1716:                        continue;
                   1717:                case SSH_CHANNEL_LARVAL:
                   1718:                case SSH_CHANNEL_AUTH_SOCKET:
                   1719:                case SSH_CHANNEL_CONNECTING:    /* XXX ??? */
1.107     beck     1720:                case SSH_CHANNEL_OPEN:
                   1721:                case SSH_CHANNEL_X11_OPEN:
                   1722:                        return i;
                   1723:                case SSH_CHANNEL_INPUT_DRAINING:
                   1724:                case SSH_CHANNEL_OUTPUT_DRAINING:
                   1725:                        if (!compat13)
                   1726:                                fatal("cannot happen: OUT_DRAIN");
                   1727:                        return i;
                   1728:                default:
1.113   ! markus   1729:                        fatal("channel_find_open: bad channel type %d", c->type);
1.107     beck     1730:                        /* NOTREACHED */
                   1731:                }
1.113   ! markus   1732:        }
1.107     beck     1733:        return -1;
                   1734: }
                   1735:
1.1       deraadt  1736:
1.27      markus   1737: /*
                   1738:  * Returns a message describing the currently open forwarded connections,
                   1739:  * suitable for sending to the client.  The message contains crlf pairs for
                   1740:  * newlines.
                   1741:  */
1.1       deraadt  1742:
1.25      markus   1743: char *
                   1744: channel_open_message()
1.1       deraadt  1745: {
1.25      markus   1746:        Buffer buffer;
1.113   ! markus   1747:        Channel *c;
        !          1748:        char buf[1024], *cp;
1.25      markus   1749:        int i;
                   1750:
                   1751:        buffer_init(&buffer);
                   1752:        snprintf(buf, sizeof buf, "The following connections are open:\r\n");
1.1       deraadt  1753:        buffer_append(&buffer, buf, strlen(buf));
1.25      markus   1754:        for (i = 0; i < channels_alloc; i++) {
1.113   ! markus   1755:                c = channels[i];
        !          1756:                if (c == NULL)
        !          1757:                        continue;
1.25      markus   1758:                switch (c->type) {
                   1759:                case SSH_CHANNEL_X11_LISTENER:
                   1760:                case SSH_CHANNEL_PORT_LISTENER:
1.73      markus   1761:                case SSH_CHANNEL_RPORT_LISTENER:
1.25      markus   1762:                case SSH_CHANNEL_CLOSED:
                   1763:                case SSH_CHANNEL_AUTH_SOCKET:
                   1764:                        continue;
1.44      markus   1765:                case SSH_CHANNEL_LARVAL:
1.25      markus   1766:                case SSH_CHANNEL_OPENING:
1.75      markus   1767:                case SSH_CHANNEL_CONNECTING:
1.103     markus   1768:                case SSH_CHANNEL_DYNAMIC:
1.25      markus   1769:                case SSH_CHANNEL_OPEN:
                   1770:                case SSH_CHANNEL_X11_OPEN:
                   1771:                case SSH_CHANNEL_INPUT_DRAINING:
                   1772:                case SSH_CHANNEL_OUTPUT_DRAINING:
1.41      markus   1773:                        snprintf(buf, sizeof buf, "  #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
1.37      markus   1774:                            c->self, c->remote_name,
                   1775:                            c->type, c->remote_id,
                   1776:                            c->istate, buffer_len(&c->input),
1.41      markus   1777:                            c->ostate, buffer_len(&c->output),
                   1778:                            c->rfd, c->wfd);
1.25      markus   1779:                        buffer_append(&buffer, buf, strlen(buf));
                   1780:                        continue;
                   1781:                default:
1.41      markus   1782:                        fatal("channel_open_message: bad channel type %d", c->type);
1.25      markus   1783:                        /* NOTREACHED */
                   1784:                }
                   1785:        }
                   1786:        buffer_append(&buffer, "\0", 1);
                   1787:        cp = xstrdup(buffer_ptr(&buffer));
                   1788:        buffer_free(&buffer);
                   1789:        return cp;
1.1       deraadt  1790: }
                   1791:
1.27      markus   1792: /*
                   1793:  * Initiate forwarding of connections to local port "port" through the secure
                   1794:  * channel to host:port from remote side.
                   1795:  */
1.87      markus   1796: int
1.73      markus   1797: channel_request_local_forwarding(u_short listen_port, const char *host_to_connect,
                   1798:     u_short port_to_connect, int gateway_ports)
                   1799: {
1.87      markus   1800:        return channel_request_forwarding(
1.73      markus   1801:            NULL, listen_port,
                   1802:            host_to_connect, port_to_connect,
                   1803:            gateway_ports, /*remote_fwd*/ 0);
                   1804: }
1.1       deraadt  1805:
1.73      markus   1806: /*
                   1807:  * If 'remote_fwd' is true we have a '-R style' listener for protocol 2
                   1808:  * (SSH_CHANNEL_RPORT_LISTENER).
                   1809:  */
1.87      markus   1810: int
1.73      markus   1811: channel_request_forwarding(
                   1812:     const char *listen_address, u_short listen_port,
                   1813:     const char *host_to_connect, u_short port_to_connect,
                   1814:     int gateway_ports, int remote_fwd)
1.25      markus   1815: {
1.113   ! markus   1816:        Channel *c;
        !          1817:        int success, sock, on = 1, ctype;
1.35      markus   1818:        struct addrinfo hints, *ai, *aitop;
                   1819:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1.73      markus   1820:        const char *host;
1.28      markus   1821:        struct linger linger;
1.25      markus   1822:
1.87      markus   1823:        success = 0;
                   1824:
1.73      markus   1825:        if (remote_fwd) {
                   1826:                host = listen_address;
1.89      stevesk  1827:                ctype = SSH_CHANNEL_RPORT_LISTENER;
1.73      markus   1828:        } else {
                   1829:                host = host_to_connect;
                   1830:                ctype  =SSH_CHANNEL_PORT_LISTENER;
                   1831:        }
                   1832:
1.113   ! markus   1833:        if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
1.87      markus   1834:                error("Forward host name too long.");
                   1835:                return success;
                   1836:        }
1.25      markus   1837:
1.73      markus   1838:        /* XXX listen_address is currently ignored */
1.28      markus   1839:        /*
1.35      markus   1840:         * getaddrinfo returns a loopback address if the hostname is
                   1841:         * set to NULL and hints.ai_flags is not AI_PASSIVE
1.28      markus   1842:         */
1.35      markus   1843:        memset(&hints, 0, sizeof(hints));
                   1844:        hints.ai_family = IPv4or6;
                   1845:        hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
                   1846:        hints.ai_socktype = SOCK_STREAM;
1.73      markus   1847:        snprintf(strport, sizeof strport, "%d", listen_port);
1.35      markus   1848:        if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
                   1849:                packet_disconnect("getaddrinfo: fatal error");
                   1850:
                   1851:        for (ai = aitop; ai; ai = ai->ai_next) {
                   1852:                if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   1853:                        continue;
                   1854:                if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
                   1855:                    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1.73      markus   1856:                        error("channel_request_forwarding: getnameinfo failed");
1.35      markus   1857:                        continue;
                   1858:                }
                   1859:                /* Create a port to listen for the host. */
                   1860:                sock = socket(ai->ai_family, SOCK_STREAM, 0);
                   1861:                if (sock < 0) {
                   1862:                        /* this is no error since kernel may not support ipv6 */
                   1863:                        verbose("socket: %.100s", strerror(errno));
                   1864:                        continue;
                   1865:                }
                   1866:                /*
                   1867:                 * Set socket options.  We would like the socket to disappear
                   1868:                 * as soon as it has been closed for whatever reason.
                   1869:                 */
                   1870:                setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
                   1871:                linger.l_onoff = 1;
                   1872:                linger.l_linger = 5;
                   1873:                setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
                   1874:                debug("Local forwarding listening on %s port %s.", ntop, strport);
                   1875:
                   1876:                /* Bind the socket to the address. */
                   1877:                if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   1878:                        /* address can be in use ipv6 address is already bound */
                   1879:                        verbose("bind: %.100s", strerror(errno));
                   1880:                        close(sock);
                   1881:                        continue;
                   1882:                }
                   1883:                /* Start listening for connections on the socket. */
                   1884:                if (listen(sock, 5) < 0) {
                   1885:                        error("listen: %.100s", strerror(errno));
                   1886:                        close(sock);
                   1887:                        continue;
                   1888:                }
                   1889:                /* Allocate a channel number for the socket. */
1.113   ! markus   1890:                c = channel_new("port listener", ctype, sock, sock, -1,
1.51      markus   1891:                    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1.71      markus   1892:                    0, xstrdup("port listener"), 1);
1.113   ! markus   1893:                if (c == NULL) {
        !          1894:                        error("channel_request_forwarding: channel_new failed");
        !          1895:                        close(sock);
        !          1896:                        continue;
        !          1897:                }
        !          1898:                strlcpy(c->path, host, sizeof(c->path));
        !          1899:                c->host_port = port_to_connect;
        !          1900:                c->listening_port = listen_port;
1.35      markus   1901:                success = 1;
                   1902:        }
                   1903:        if (success == 0)
1.87      markus   1904:                error("channel_request_forwarding: cannot listen to port: %d",
                   1905:                    listen_port);
1.35      markus   1906:        freeaddrinfo(aitop);
1.87      markus   1907:        return success;
1.25      markus   1908: }
1.1       deraadt  1909:
1.27      markus   1910: /*
                   1911:  * Initiate forwarding of connections to port "port" on remote host through
                   1912:  * the secure channel to host:port from local side.
                   1913:  */
1.1       deraadt  1914:
1.49      markus   1915: void
1.73      markus   1916: channel_request_remote_forwarding(u_short listen_port,
                   1917:     const char *host_to_connect, u_short port_to_connect)
1.25      markus   1918: {
1.73      markus   1919:        int payload_len, type, success = 0;
                   1920:
1.25      markus   1921:        /* Record locally that connection to this host/port is permitted. */
                   1922:        if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
                   1923:                fatal("channel_request_remote_forwarding: too many forwards");
                   1924:
                   1925:        /* Send the forward request to the remote side. */
1.44      markus   1926:        if (compat20) {
                   1927:                const char *address_to_bind = "0.0.0.0";
                   1928:                packet_start(SSH2_MSG_GLOBAL_REQUEST);
                   1929:                packet_put_cstring("tcpip-forward");
                   1930:                packet_put_char(0);                     /* boolean: want reply */
                   1931:                packet_put_cstring(address_to_bind);
                   1932:                packet_put_int(listen_port);
1.73      markus   1933:                packet_send();
                   1934:                packet_write_wait();
                   1935:                /* Assume that server accepts the request */
                   1936:                success = 1;
1.44      markus   1937:        } else {
                   1938:                packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1.50      markus   1939:                packet_put_int(listen_port);
                   1940:                packet_put_cstring(host_to_connect);
1.44      markus   1941:                packet_put_int(port_to_connect);
                   1942:                packet_send();
                   1943:                packet_write_wait();
1.73      markus   1944:
                   1945:                /* Wait for response from the remote side. */
                   1946:                type = packet_read(&payload_len);
                   1947:                switch (type) {
                   1948:                case SSH_SMSG_SUCCESS:
                   1949:                        success = 1;
                   1950:                        break;
                   1951:                case SSH_SMSG_FAILURE:
                   1952:                        log("Warning: Server denied remote port forwarding.");
                   1953:                        break;
                   1954:                default:
                   1955:                        /* Unknown packet */
                   1956:                        packet_disconnect("Protocol error for port forward request:"
                   1957:                            "received packet type %d.", type);
                   1958:                }
                   1959:        }
                   1960:        if (success) {
                   1961:                permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
                   1962:                permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
                   1963:                permitted_opens[num_permitted_opens].listen_port = listen_port;
                   1964:                num_permitted_opens++;
1.44      markus   1965:        }
1.1       deraadt  1966: }
                   1967:
1.27      markus   1968: /*
                   1969:  * This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
                   1970:  * listening for the port, and sends back a success reply (or disconnect
                   1971:  * message if there was an error).  This never returns if there was an error.
                   1972:  */
1.1       deraadt  1973:
1.49      markus   1974: void
1.56      markus   1975: channel_input_port_forward_request(int is_root, int gateway_ports)
1.1       deraadt  1976: {
1.31      markus   1977:        u_short port, host_port;
1.25      markus   1978:        char *hostname;
1.1       deraadt  1979:
1.25      markus   1980:        /* Get arguments from the packet. */
                   1981:        port = packet_get_int();
                   1982:        hostname = packet_get_string(NULL);
                   1983:        host_port = packet_get_int();
                   1984:
1.27      markus   1985:        /*
                   1986:         * Check that an unprivileged user is not trying to forward a
                   1987:         * privileged port.
                   1988:         */
1.25      markus   1989:        if (port < IPPORT_RESERVED && !is_root)
                   1990:                packet_disconnect("Requested forwarding of port %d but user is not root.",
                   1991:                                  port);
1.73      markus   1992:        /* Initiate forwarding */
1.56      markus   1993:        channel_request_local_forwarding(port, hostname, host_port, gateway_ports);
1.25      markus   1994:
                   1995:        /* Free the argument string. */
                   1996:        xfree(hostname);
1.1       deraadt  1997: }
                   1998:
1.99      markus   1999: /*
                   2000:  * Permits opening to any host/port if permitted_opens[] is empty.  This is
                   2001:  * usually called by the server, because the user could connect to any port
                   2002:  * anyway, and the server has no way to know but to trust the client anyway.
                   2003:  */
                   2004: void
                   2005: channel_permit_all_opens()
                   2006: {
                   2007:        if (num_permitted_opens == 0)
                   2008:                all_opens_permitted = 1;
                   2009: }
                   2010:
1.101     markus   2011: void
1.99      markus   2012: channel_add_permitted_opens(char *host, int port)
                   2013: {
                   2014:        if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
                   2015:                fatal("channel_request_remote_forwarding: too many forwards");
                   2016:        debug("allow port forwarding to host %s port %d", host, port);
                   2017:
                   2018:        permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
                   2019:        permitted_opens[num_permitted_opens].port_to_connect = port;
                   2020:        num_permitted_opens++;
                   2021:
                   2022:        all_opens_permitted = 0;
                   2023: }
                   2024:
1.101     markus   2025: void
1.99      markus   2026: channel_clear_permitted_opens(void)
                   2027: {
                   2028:        int i;
                   2029:
                   2030:        for (i = 0; i < num_permitted_opens; i++)
                   2031:                xfree(permitted_opens[i].host_to_connect);
                   2032:        num_permitted_opens = 0;
                   2033:
                   2034: }
                   2035:
                   2036:
                   2037: /* return socket to remote host, port */
1.41      markus   2038: int
1.99      markus   2039: connect_to(const char *host, u_short port)
1.41      markus   2040: {
                   2041:        struct addrinfo hints, *ai, *aitop;
                   2042:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
                   2043:        int gaierr;
                   2044:        int sock = -1;
                   2045:
                   2046:        memset(&hints, 0, sizeof(hints));
                   2047:        hints.ai_family = IPv4or6;
                   2048:        hints.ai_socktype = SOCK_STREAM;
1.99      markus   2049:        snprintf(strport, sizeof strport, "%d", port);
1.41      markus   2050:        if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
1.99      markus   2051:                error("connect_to %.100s: unknown host (%s)", host,
                   2052:                    gai_strerror(gaierr));
1.41      markus   2053:                return -1;
                   2054:        }
                   2055:        for (ai = aitop; ai; ai = ai->ai_next) {
                   2056:                if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   2057:                        continue;
                   2058:                if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
                   2059:                    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1.99      markus   2060:                        error("connect_to: getnameinfo failed");
1.41      markus   2061:                        continue;
                   2062:                }
                   2063:                sock = socket(ai->ai_family, SOCK_STREAM, 0);
                   2064:                if (sock < 0) {
                   2065:                        error("socket: %.100s", strerror(errno));
                   2066:                        continue;
                   2067:                }
1.80      markus   2068:                if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0)
1.75      markus   2069:                        fatal("connect_to: F_SETFL: %s", strerror(errno));
                   2070:                if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
                   2071:                    errno != EINPROGRESS) {
1.99      markus   2072:                        error("connect_to %.100s port %s: %.100s", ntop, strport,
1.41      markus   2073:                            strerror(errno));
                   2074:                        close(sock);
1.89      stevesk  2075:                        continue;       /* fail -- try next */
1.41      markus   2076:                }
                   2077:                break; /* success */
                   2078:
                   2079:        }
                   2080:        freeaddrinfo(aitop);
                   2081:        if (!ai) {
1.99      markus   2082:                error("connect_to %.100s port %d: failed.", host, port);
1.41      markus   2083:                return -1;
                   2084:        }
                   2085:        /* success */
                   2086:        return sock;
                   2087: }
1.99      markus   2088:
1.73      markus   2089: int
                   2090: channel_connect_by_listen_adress(u_short listen_port)
                   2091: {
                   2092:        int i;
1.99      markus   2093:
1.73      markus   2094:        for (i = 0; i < num_permitted_opens; i++)
                   2095:                if (permitted_opens[i].listen_port == listen_port)
1.99      markus   2096:                        return connect_to(
1.73      markus   2097:                            permitted_opens[i].host_to_connect,
                   2098:                            permitted_opens[i].port_to_connect);
1.74      markus   2099:        error("WARNING: Server requests forwarding for unknown listen_port %d",
                   2100:            listen_port);
1.73      markus   2101:        return -1;
                   2102: }
                   2103:
1.99      markus   2104: /* Check if connecting to that port is permitted and connect. */
                   2105: int
                   2106: channel_connect_to(const char *host, u_short port)
                   2107: {
                   2108:        int i, permit;
                   2109:
                   2110:        permit = all_opens_permitted;
                   2111:        if (!permit) {
                   2112:                for (i = 0; i < num_permitted_opens; i++)
                   2113:                        if (permitted_opens[i].port_to_connect == port &&
                   2114:                            strcmp(permitted_opens[i].host_to_connect, host) == 0)
                   2115:                                permit = 1;
                   2116:
                   2117:        }
                   2118:        if (!permit) {
                   2119:                log("Received request to connect to host %.100s port %d, "
                   2120:                    "but the request was denied.", host, port);
                   2121:                return -1;
                   2122:        }
                   2123:        return connect_to(host, port);
                   2124: }
                   2125:
1.27      markus   2126: /*
                   2127:  * This is called after receiving PORT_OPEN message.  This attempts to
                   2128:  * connect to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION
                   2129:  * or CHANNEL_OPEN_FAILURE.
                   2130:  */
1.1       deraadt  2131:
1.49      markus   2132: void
1.69      markus   2133: channel_input_port_open(int type, int plen, void *ctxt)
1.1       deraadt  2134: {
1.113   ! markus   2135:        Channel *c = NULL;
1.31      markus   2136:        u_short host_port;
1.25      markus   2137:        char *host, *originator_string;
1.113   ! markus   2138:        int remote_id, sock = -1;
1.25      markus   2139:
1.113   ! markus   2140:        remote_id = packet_get_int();
1.99      markus   2141:        host = packet_get_string(NULL);
1.25      markus   2142:        host_port = packet_get_int();
                   2143:
1.29      markus   2144:        if (have_hostname_in_open) {
1.99      markus   2145:                originator_string = packet_get_string(NULL);
1.29      markus   2146:        } else {
1.25      markus   2147:                originator_string = xstrdup("unknown (remote did not supply name)");
1.29      markus   2148:        }
1.99      markus   2149:        packet_done();
                   2150:        sock = channel_connect_to(host, host_port);
                   2151:        if (sock != -1) {
1.113   ! markus   2152:                c = channel_new("connected socket",
        !          2153:                    SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
        !          2154:                    originator_string, 1);
        !          2155:                if (c == NULL) {
        !          2156:                        error("channel_input_port_open: channel_new failed");
        !          2157:                        close(sock);
        !          2158:                } else {
        !          2159:                        c->remote_id = remote_id;
        !          2160:                }
        !          2161:        }
        !          2162:        if (c == NULL) {
        !          2163:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
        !          2164:                packet_put_int(remote_id);
        !          2165:        } else {
1.99      markus   2166:                /*XXX delay answer? */
1.41      markus   2167:                packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1.113   ! markus   2168:                packet_put_int(remote_id);
        !          2169:                packet_put_int(c->self);
1.25      markus   2170:        }
1.113   ! markus   2171:        packet_send();
1.25      markus   2172:        xfree(host);
1.1       deraadt  2173: }
                   2174:
1.27      markus   2175: /*
                   2176:  * Creates an internet domain socket for listening for X11 connections.
                   2177:  * Returns a suitable value for the DISPLAY variable, or NULL if an error
                   2178:  * occurs.
                   2179:  */
1.1       deraadt  2180:
1.35      markus   2181: #define        NUM_SOCKS       10
                   2182:
1.25      markus   2183: char *
1.33      markus   2184: x11_create_display_inet(int screen_number, int x11_display_offset)
1.1       deraadt  2185: {
1.31      markus   2186:        int display_number, sock;
                   2187:        u_short port;
1.35      markus   2188:        struct addrinfo hints, *ai, *aitop;
                   2189:        char strport[NI_MAXSERV];
                   2190:        int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
                   2191:        char display[512];
1.25      markus   2192:        char hostname[MAXHOSTNAMELEN];
                   2193:
1.33      markus   2194:        for (display_number = x11_display_offset;
1.25      markus   2195:             display_number < MAX_DISPLAYS;
                   2196:             display_number++) {
                   2197:                port = 6000 + display_number;
1.35      markus   2198:                memset(&hints, 0, sizeof(hints));
                   2199:                hints.ai_family = IPv4or6;
1.36      markus   2200:                hints.ai_flags = AI_PASSIVE;            /* XXX loopback only ? */
1.35      markus   2201:                hints.ai_socktype = SOCK_STREAM;
                   2202:                snprintf(strport, sizeof strport, "%d", port);
                   2203:                if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
                   2204:                        error("getaddrinfo: %.100s", gai_strerror(gaierr));
1.25      markus   2205:                        return NULL;
                   2206:                }
1.35      markus   2207:                for (ai = aitop; ai; ai = ai->ai_next) {
                   2208:                        if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   2209:                                continue;
                   2210:                        sock = socket(ai->ai_family, SOCK_STREAM, 0);
                   2211:                        if (sock < 0) {
                   2212:                                error("socket: %.100s", strerror(errno));
                   2213:                                return NULL;
                   2214:                        }
                   2215:                        if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   2216:                                debug("bind port %d: %.100s", port, strerror(errno));
                   2217:                                shutdown(sock, SHUT_RDWR);
                   2218:                                close(sock);
                   2219:                                for (n = 0; n < num_socks; n++) {
                   2220:                                        shutdown(socks[n], SHUT_RDWR);
                   2221:                                        close(socks[n]);
                   2222:                                }
                   2223:                                num_socks = 0;
                   2224:                                break;
                   2225:                        }
                   2226:                        socks[num_socks++] = sock;
                   2227:                        if (num_socks == NUM_SOCKS)
                   2228:                                break;
1.25      markus   2229:                }
1.83      stevesk  2230:                freeaddrinfo(aitop);
1.35      markus   2231:                if (num_socks > 0)
                   2232:                        break;
1.25      markus   2233:        }
                   2234:        if (display_number >= MAX_DISPLAYS) {
                   2235:                error("Failed to allocate internet-domain X11 display socket.");
                   2236:                return NULL;
                   2237:        }
                   2238:        /* Start listening for connections on the socket. */
1.35      markus   2239:        for (n = 0; n < num_socks; n++) {
                   2240:                sock = socks[n];
                   2241:                if (listen(sock, 5) < 0) {
                   2242:                        error("listen: %.100s", strerror(errno));
                   2243:                        shutdown(sock, SHUT_RDWR);
                   2244:                        close(sock);
                   2245:                        return NULL;
                   2246:                }
1.25      markus   2247:        }
1.35      markus   2248:
1.25      markus   2249:        /* Set up a suitable value for the DISPLAY variable. */
                   2250:        if (gethostname(hostname, sizeof(hostname)) < 0)
                   2251:                fatal("gethostname: %.100s", strerror(errno));
1.35      markus   2252:        snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
1.25      markus   2253:                 display_number, screen_number);
                   2254:
1.35      markus   2255:        /* Allocate a channel for each socket. */
                   2256:        for (n = 0; n < num_socks; n++) {
                   2257:                sock = socks[n];
1.51      markus   2258:                (void) channel_new("x11 listener",
                   2259:                    SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
                   2260:                    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
1.71      markus   2261:                    0, xstrdup("X11 inet listener"), 1);
1.35      markus   2262:        }
1.1       deraadt  2263:
1.25      markus   2264:        /* Return a suitable value for the DISPLAY environment variable. */
1.35      markus   2265:        return xstrdup(display);
1.1       deraadt  2266: }
                   2267:
                   2268: #ifndef X_UNIX_PATH
                   2269: #define X_UNIX_PATH "/tmp/.X11-unix/X"
                   2270: #endif
                   2271:
                   2272: static
                   2273: int
1.77      markus   2274: connect_local_xsocket(u_int dnr)
1.1       deraadt  2275: {
1.25      markus   2276:        static const char *const x_sockets[] = {
                   2277:                X_UNIX_PATH "%u",
                   2278:                "/var/X/.X11-unix/X" "%u",
                   2279:                "/usr/spool/sockets/X11/" "%u",
                   2280:                NULL
                   2281:        };
                   2282:        int sock;
                   2283:        struct sockaddr_un addr;
                   2284:        const char *const * path;
                   2285:
                   2286:        for (path = x_sockets; *path; ++path) {
                   2287:                sock = socket(AF_UNIX, SOCK_STREAM, 0);
                   2288:                if (sock < 0)
                   2289:                        error("socket: %.100s", strerror(errno));
                   2290:                memset(&addr, 0, sizeof(addr));
                   2291:                addr.sun_family = AF_UNIX;
                   2292:                snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
                   2293:                if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
                   2294:                        return sock;
                   2295:                close(sock);
                   2296:        }
                   2297:        error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
                   2298:        return -1;
1.1       deraadt  2299: }
                   2300:
1.51      markus   2301: int
                   2302: x11_connect_display(void)
1.1       deraadt  2303: {
1.51      markus   2304:        int display_number, sock = 0;
1.25      markus   2305:        const char *display;
1.51      markus   2306:        char buf[1024], *cp;
1.35      markus   2307:        struct addrinfo hints, *ai, *aitop;
                   2308:        char strport[NI_MAXSERV];
                   2309:        int gaierr;
1.25      markus   2310:
                   2311:        /* Try to open a socket for the local X server. */
                   2312:        display = getenv("DISPLAY");
                   2313:        if (!display) {
                   2314:                error("DISPLAY not set.");
1.51      markus   2315:                return -1;
1.25      markus   2316:        }
1.27      markus   2317:        /*
                   2318:         * Now we decode the value of the DISPLAY variable and make a
                   2319:         * connection to the real X server.
                   2320:         */
                   2321:
                   2322:        /*
                   2323:         * Check if it is a unix domain socket.  Unix domain displays are in
                   2324:         * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
                   2325:         */
1.25      markus   2326:        if (strncmp(display, "unix:", 5) == 0 ||
                   2327:            display[0] == ':') {
                   2328:                /* Connect to the unix domain socket. */
                   2329:                if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
                   2330:                        error("Could not parse display number from DISPLAY: %.100s",
                   2331:                              display);
1.51      markus   2332:                        return -1;
1.25      markus   2333:                }
                   2334:                /* Create a socket. */
                   2335:                sock = connect_local_xsocket(display_number);
                   2336:                if (sock < 0)
1.51      markus   2337:                        return -1;
1.25      markus   2338:
                   2339:                /* OK, we now have a connection to the display. */
1.51      markus   2340:                return sock;
1.25      markus   2341:        }
1.27      markus   2342:        /*
                   2343:         * Connect to an inet socket.  The DISPLAY value is supposedly
                   2344:         * hostname:d[.s], where hostname may also be numeric IP address.
                   2345:         */
1.25      markus   2346:        strncpy(buf, display, sizeof(buf));
                   2347:        buf[sizeof(buf) - 1] = 0;
                   2348:        cp = strchr(buf, ':');
                   2349:        if (!cp) {
                   2350:                error("Could not find ':' in DISPLAY: %.100s", display);
1.51      markus   2351:                return -1;
1.25      markus   2352:        }
                   2353:        *cp = 0;
1.27      markus   2354:        /* buf now contains the host name.  But first we parse the display number. */
1.25      markus   2355:        if (sscanf(cp + 1, "%d", &display_number) != 1) {
                   2356:                error("Could not parse display number from DISPLAY: %.100s",
                   2357:                      display);
1.51      markus   2358:                return -1;
1.25      markus   2359:        }
1.35      markus   2360:
                   2361:        /* Look up the host address */
                   2362:        memset(&hints, 0, sizeof(hints));
                   2363:        hints.ai_family = IPv4or6;
                   2364:        hints.ai_socktype = SOCK_STREAM;
                   2365:        snprintf(strport, sizeof strport, "%d", 6000 + display_number);
                   2366:        if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
                   2367:                error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
1.51      markus   2368:                return -1;
1.25      markus   2369:        }
1.35      markus   2370:        for (ai = aitop; ai; ai = ai->ai_next) {
                   2371:                /* Create a socket. */
                   2372:                sock = socket(ai->ai_family, SOCK_STREAM, 0);
                   2373:                if (sock < 0) {
                   2374:                        debug("socket: %.100s", strerror(errno));
1.41      markus   2375:                        continue;
                   2376:                }
                   2377:                /* Connect it to the display. */
                   2378:                if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   2379:                        debug("connect %.100s port %d: %.100s", buf,
                   2380:                            6000 + display_number, strerror(errno));
                   2381:                        close(sock);
                   2382:                        continue;
                   2383:                }
                   2384:                /* Success */
                   2385:                break;
1.35      markus   2386:        }
                   2387:        freeaddrinfo(aitop);
                   2388:        if (!ai) {
1.49      markus   2389:                error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
1.35      markus   2390:                    strerror(errno));
1.51      markus   2391:                return -1;
1.25      markus   2392:        }
1.51      markus   2393:        return sock;
                   2394: }
                   2395:
                   2396: /*
                   2397:  * This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
                   2398:  * the remote channel number.  We should do whatever we want, and respond
                   2399:  * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
                   2400:  */
                   2401:
                   2402: void
1.69      markus   2403: x11_input_open(int type, int plen, void *ctxt)
1.51      markus   2404: {
1.113   ! markus   2405:        Channel *c = NULL;
        !          2406:        int remote_id, sock = 0;
1.51      markus   2407:        char *remote_host;
1.25      markus   2408:
1.113   ! markus   2409:        debug("Received X11 open request.");
1.51      markus   2410:
1.113   ! markus   2411:        remote_id = packet_get_int();
1.51      markus   2412:        if (have_hostname_in_open) {
1.113   ! markus   2413:                remote_host = packet_get_string(NULL);
1.51      markus   2414:        } else {
                   2415:                remote_host = xstrdup("unknown (remote did not supply name)");
                   2416:        }
1.113   ! markus   2417:        packet_done();
1.25      markus   2418:
1.51      markus   2419:        /* Obtain a connection to the real X display. */
                   2420:        sock = x11_connect_display();
1.113   ! markus   2421:        if (sock != -1) {
        !          2422:                /* Allocate a channel for this connection. */
        !          2423:                c = channel_new("connected x11 socket",
        !          2424:                    SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
        !          2425:                    remote_host, 1);
        !          2426:                if (c == NULL) {
        !          2427:                        error("x11_input_open: channel_new failed");
        !          2428:                        close(sock);
        !          2429:                } else {
        !          2430:                        c->remote_id = remote_id;
        !          2431:                }
        !          2432:        }
        !          2433:        if (c == NULL) {
1.51      markus   2434:                /* Send refusal to the remote host. */
                   2435:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1.113   ! markus   2436:                packet_put_int(remote_id);
1.51      markus   2437:        } else {
                   2438:                /* Send a confirmation to the remote host. */
                   2439:                packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1.113   ! markus   2440:                packet_put_int(remote_id);
        !          2441:                packet_put_int(c->self);
1.51      markus   2442:        }
1.113   ! markus   2443:        packet_send();
1.72      markus   2444: }
                   2445:
                   2446: /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
                   2447: void
                   2448: deny_input_open(int type, int plen, void *ctxt)
                   2449: {
                   2450:        int rchan = packet_get_int();
                   2451:        switch(type){
                   2452:        case SSH_SMSG_AGENT_OPEN:
                   2453:                error("Warning: ssh server tried agent forwarding.");
                   2454:                break;
                   2455:        case SSH_SMSG_X11_OPEN:
                   2456:                error("Warning: ssh server tried X11 forwarding.");
                   2457:                break;
                   2458:        default:
                   2459:                error("deny_input_open: type %d plen %d", type, plen);
                   2460:                break;
                   2461:        }
                   2462:        error("Warning: this is probably a break in attempt by a malicious server.");
                   2463:        packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   2464:        packet_put_int(rchan);
                   2465:        packet_send();
1.1       deraadt  2466: }
                   2467:
1.27      markus   2468: /*
                   2469:  * Requests forwarding of X11 connections, generates fake authentication
                   2470:  * data, and enables authentication spoofing.
                   2471:  */
1.1       deraadt  2472:
1.49      markus   2473: void
1.51      markus   2474: x11_request_forwarding_with_spoofing(int client_session_id,
                   2475:     const char *proto, const char *data)
1.1       deraadt  2476: {
1.77      markus   2477:        u_int data_len = (u_int) strlen(data) / 2;
1.90      markus   2478:        u_int i, value, len;
1.25      markus   2479:        char *new_data;
                   2480:        int screen_number;
                   2481:        const char *cp;
                   2482:        u_int32_t rand = 0;
                   2483:
                   2484:        cp = getenv("DISPLAY");
                   2485:        if (cp)
                   2486:                cp = strchr(cp, ':');
                   2487:        if (cp)
                   2488:                cp = strchr(cp, '.');
                   2489:        if (cp)
                   2490:                screen_number = atoi(cp + 1);
                   2491:        else
                   2492:                screen_number = 0;
                   2493:
                   2494:        /* Save protocol name. */
                   2495:        x11_saved_proto = xstrdup(proto);
                   2496:
1.27      markus   2497:        /*
                   2498:         * Extract real authentication data and generate fake data of the
                   2499:         * same length.
                   2500:         */
1.25      markus   2501:        x11_saved_data = xmalloc(data_len);
                   2502:        x11_fake_data = xmalloc(data_len);
                   2503:        for (i = 0; i < data_len; i++) {
                   2504:                if (sscanf(data + 2 * i, "%2x", &value) != 1)
                   2505:                        fatal("x11_request_forwarding: bad authentication data: %.100s", data);
                   2506:                if (i % 4 == 0)
                   2507:                        rand = arc4random();
                   2508:                x11_saved_data[i] = value;
                   2509:                x11_fake_data[i] = rand & 0xff;
                   2510:                rand >>= 8;
                   2511:        }
                   2512:        x11_saved_data_len = data_len;
                   2513:        x11_fake_data_len = data_len;
                   2514:
                   2515:        /* Convert the fake data into hex. */
1.90      markus   2516:        len = 2 * data_len + 1;
                   2517:        new_data = xmalloc(len);
1.25      markus   2518:        for (i = 0; i < data_len; i++)
1.90      markus   2519:                snprintf(new_data + 2 * i, len - 2 * i,
                   2520:                    "%02x", (u_char) x11_fake_data[i]);
1.25      markus   2521:
                   2522:        /* Send the request packet. */
1.51      markus   2523:        if (compat20) {
                   2524:                channel_request_start(client_session_id, "x11-req", 0);
                   2525:                packet_put_char(0);     /* XXX bool single connection */
                   2526:        } else {
                   2527:                packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
                   2528:        }
                   2529:        packet_put_cstring(proto);
                   2530:        packet_put_cstring(new_data);
1.25      markus   2531:        packet_put_int(screen_number);
                   2532:        packet_send();
                   2533:        packet_write_wait();
                   2534:        xfree(new_data);
1.1       deraadt  2535: }
                   2536:
                   2537: /* Sends a message to the server to request authentication fd forwarding. */
                   2538:
1.49      markus   2539: void
1.25      markus   2540: auth_request_forwarding()
1.1       deraadt  2541: {
1.25      markus   2542:        packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
                   2543:        packet_send();
                   2544:        packet_write_wait();
1.1       deraadt  2545: }
                   2546:
1.27      markus   2547: /*
                   2548:  * Returns the name of the forwarded authentication socket.  Returns NULL if
                   2549:  * there is no forwarded authentication socket.  The returned value points to
                   2550:  * a static buffer.
                   2551:  */
1.1       deraadt  2552:
1.25      markus   2553: char *
                   2554: auth_get_socket_name()
1.1       deraadt  2555: {
1.25      markus   2556:        return channel_forwarded_auth_socket_name;
1.1       deraadt  2557: }
                   2558:
1.12      markus   2559: /* removes the agent forwarding socket */
                   2560:
1.49      markus   2561: void
1.25      markus   2562: cleanup_socket(void)
                   2563: {
1.78      markus   2564:        unlink(channel_forwarded_auth_socket_name);
1.25      markus   2565:        rmdir(channel_forwarded_auth_socket_dir);
1.12      markus   2566: }
                   2567:
1.27      markus   2568: /*
1.59      markus   2569:  * This is called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
1.27      markus   2570:  * This starts forwarding authentication requests.
                   2571:  */
1.1       deraadt  2572:
1.59      markus   2573: int
1.25      markus   2574: auth_input_request_forwarding(struct passwd * pw)
1.1       deraadt  2575: {
1.113   ! markus   2576:        Channel *nc;
        !          2577:        int sock;
1.25      markus   2578:        struct sockaddr_un sunaddr;
                   2579:
                   2580:        if (auth_get_socket_name() != NULL)
                   2581:                fatal("Protocol error: authentication forwarding requested twice.");
                   2582:
                   2583:        /* Temporarily drop privileged uid for mkdir/bind. */
1.102     markus   2584:        temporarily_use_uid(pw);
1.25      markus   2585:
                   2586:        /* Allocate a buffer for the socket name, and format the name. */
                   2587:        channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
                   2588:        channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
                   2589:        strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
                   2590:
                   2591:        /* Create private directory for socket */
1.59      markus   2592:        if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL) {
                   2593:                packet_send_debug("Agent forwarding disabled: mkdtemp() failed: %.100s",
                   2594:                    strerror(errno));
                   2595:                restore_uid();
                   2596:                xfree(channel_forwarded_auth_socket_name);
                   2597:                xfree(channel_forwarded_auth_socket_dir);
                   2598:                channel_forwarded_auth_socket_name = NULL;
                   2599:                channel_forwarded_auth_socket_dir = NULL;
                   2600:                return 0;
                   2601:        }
1.25      markus   2602:        snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME, "%s/agent.%d",
                   2603:                 channel_forwarded_auth_socket_dir, (int) getpid());
                   2604:
                   2605:        if (atexit(cleanup_socket) < 0) {
                   2606:                int saved = errno;
                   2607:                cleanup_socket();
                   2608:                packet_disconnect("socket: %.100s", strerror(saved));
                   2609:        }
                   2610:        /* Create the socket. */
                   2611:        sock = socket(AF_UNIX, SOCK_STREAM, 0);
                   2612:        if (sock < 0)
                   2613:                packet_disconnect("socket: %.100s", strerror(errno));
                   2614:
                   2615:        /* Bind it to the name. */
                   2616:        memset(&sunaddr, 0, sizeof(sunaddr));
                   2617:        sunaddr.sun_family = AF_UNIX;
                   2618:        strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
                   2619:                sizeof(sunaddr.sun_path));
                   2620:
                   2621:        if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
                   2622:                packet_disconnect("bind: %.100s", strerror(errno));
                   2623:
                   2624:        /* Restore the privileged uid. */
                   2625:        restore_uid();
                   2626:
                   2627:        /* Start listening on the socket. */
                   2628:        if (listen(sock, 5) < 0)
                   2629:                packet_disconnect("listen: %.100s", strerror(errno));
                   2630:
                   2631:        /* Allocate a channel for the authentication agent socket. */
1.113   ! markus   2632:        nc = channel_new("auth socket",
1.73      markus   2633:            SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
                   2634:            CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
                   2635:            0, xstrdup("auth socket"), 1);
1.113   ! markus   2636:        if (nc == NULL) {
        !          2637:                error("auth_input_request_forwarding: channel_new failed");
        !          2638:                close(sock);
        !          2639:                return 0;
        !          2640:        }
        !          2641:        strlcpy(nc->path, channel_forwarded_auth_socket_name, sizeof(nc->path));
1.59      markus   2642:        return 1;
1.1       deraadt  2643: }
                   2644:
                   2645: /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
                   2646:
1.49      markus   2647: void
1.69      markus   2648: auth_input_open_request(int type, int plen, void *ctxt)
1.1       deraadt  2649: {
1.113   ! markus   2650:        Channel *c = NULL;
        !          2651:        int remote_id, sock;
1.25      markus   2652:        char *dummyname;
1.41      markus   2653:
                   2654:        packet_integrity_check(plen, 4, type);
1.25      markus   2655:
                   2656:        /* Read the remote channel number from the message. */
1.113   ! markus   2657:        remote_id = packet_get_int();
1.25      markus   2658:
1.27      markus   2659:        /*
                   2660:         * Get a connection to the local authentication agent (this may again
                   2661:         * get forwarded).
                   2662:         */
1.25      markus   2663:        sock = ssh_get_authentication_socket();
                   2664:
1.27      markus   2665:        /*
                   2666:         * If we could not connect the agent, send an error message back to
                   2667:         * the server. This should never happen unless the agent dies,
                   2668:         * because authentication forwarding is only enabled if we have an
                   2669:         * agent.
                   2670:         */
1.113   ! markus   2671:        if (sock >= 0) {
        !          2672:                dummyname = xstrdup("authentication agent connection");
        !          2673:                c = channel_new("", SSH_CHANNEL_OPEN, sock, sock, -1, 0, 0, 0, dummyname, 1);
        !          2674:                if (c == NULL) {
        !          2675:                        error("auth_input_open_request: channel_new failed");
        !          2676:                        close(sock);
        !          2677:                } else {
        !          2678:                        c->remote_id = remote_id;
        !          2679:                }
        !          2680:        }
        !          2681:        if (c == NULL) {
1.25      markus   2682:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1.113   ! markus   2683:                packet_put_int(remote_id);
        !          2684:        } else {
        !          2685:                /* Send a confirmation to the remote host. */
        !          2686:                debug("Forwarding authentication connection.");
        !          2687:                packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
        !          2688:                packet_put_int(remote_id);
        !          2689:                packet_put_int(c->self);
1.25      markus   2690:        }
1.44      markus   2691:        packet_send();
                   2692: }
                   2693:
                   2694: void
1.51      markus   2695: channel_start_open(int id)
1.44      markus   2696: {
                   2697:        Channel *c = channel_lookup(id);
                   2698:        if (c == NULL) {
                   2699:                log("channel_open: %d: bad id", id);
                   2700:                return;
                   2701:        }
1.51      markus   2702:        debug("send channel open %d", id);
1.44      markus   2703:        packet_start(SSH2_MSG_CHANNEL_OPEN);
                   2704:        packet_put_cstring(c->ctype);
                   2705:        packet_put_int(c->self);
                   2706:        packet_put_int(c->local_window);
                   2707:        packet_put_int(c->local_maxpacket);
1.51      markus   2708: }
                   2709: void
                   2710: channel_open(int id)
                   2711: {
                   2712:        /* XXX REMOVE ME */
                   2713:        channel_start_open(id);
1.44      markus   2714:        packet_send();
                   2715: }
                   2716: void
                   2717: channel_request(int id, char *service, int wantconfirm)
                   2718: {
                   2719:        channel_request_start(id, service, wantconfirm);
                   2720:        packet_send();
                   2721:        debug("channel request %d: %s", id, service) ;
                   2722: }
                   2723: void
                   2724: channel_request_start(int id, char *service, int wantconfirm)
                   2725: {
                   2726:        Channel *c = channel_lookup(id);
                   2727:        if (c == NULL) {
                   2728:                log("channel_request: %d: bad id", id);
                   2729:                return;
                   2730:        }
                   2731:        packet_start(SSH2_MSG_CHANNEL_REQUEST);
                   2732:        packet_put_int(c->remote_id);
                   2733:        packet_put_cstring(service);
                   2734:        packet_put_char(wantconfirm);
                   2735: }
                   2736: void
                   2737: channel_register_callback(int id, int mtype, channel_callback_fn *fn, void *arg)
                   2738: {
                   2739:        Channel *c = channel_lookup(id);
                   2740:        if (c == NULL) {
                   2741:                log("channel_register_callback: %d: bad id", id);
                   2742:                return;
                   2743:        }
                   2744:        c->cb_event = mtype;
                   2745:        c->cb_fn = fn;
                   2746:        c->cb_arg = arg;
                   2747: }
                   2748: void
                   2749: channel_register_cleanup(int id, channel_callback_fn *fn)
                   2750: {
                   2751:        Channel *c = channel_lookup(id);
                   2752:        if (c == NULL) {
                   2753:                log("channel_register_cleanup: %d: bad id", id);
                   2754:                return;
                   2755:        }
                   2756:        c->dettach_user = fn;
                   2757: }
                   2758: void
                   2759: channel_cancel_cleanup(int id)
                   2760: {
                   2761:        Channel *c = channel_lookup(id);
                   2762:        if (c == NULL) {
                   2763:                log("channel_cancel_cleanup: %d: bad id", id);
                   2764:                return;
                   2765:        }
                   2766:        c->dettach_user = NULL;
1.65      markus   2767: }
1.89      stevesk  2768: void
1.65      markus   2769: channel_register_filter(int id, channel_filter_fn *fn)
                   2770: {
                   2771:        Channel *c = channel_lookup(id);
                   2772:        if (c == NULL) {
                   2773:                log("channel_register_filter: %d: bad id", id);
                   2774:                return;
                   2775:        }
                   2776:        c->input_filter = fn;
1.44      markus   2777: }
                   2778:
                   2779: void
1.71      markus   2780: channel_set_fds(int id, int rfd, int wfd, int efd,
                   2781:     int extusage, int nonblock)
1.44      markus   2782: {
                   2783:        Channel *c = channel_lookup(id);
                   2784:        if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
                   2785:                fatal("channel_activate for non-larval channel %d.", id);
1.71      markus   2786:        channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
1.44      markus   2787:        c->type = SSH_CHANNEL_OPEN;
                   2788:        /* XXX window size? */
1.68      markus   2789:        c->local_window = c->local_window_max = c->local_maxpacket * 2;
1.44      markus   2790:        packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
                   2791:        packet_put_int(c->remote_id);
                   2792:        packet_put_int(c->local_window);
1.25      markus   2793:        packet_send();
1.1       deraadt  2794: }