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

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