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

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