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

1.311   ! djm         1: /* $OpenBSD: channels.c,v 1.310 2010/11/24 01:24:14 djm Exp $ */
1.1       deraadt     2: /*
1.26      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
                      6:  * This file contains functions for generic socket connection forwarding.
                      7:  * There is also code for initiating connection forwarding for X11 connections,
                      8:  * arbitrary tcp/ip connections, and the authentication agent connection.
1.49      markus      9:  *
1.67      deraadt    10:  * As far as I am concerned, the code I have written for this software
                     11:  * can be used freely for any purpose.  Any derived versions of this
                     12:  * software must be clearly marked as such, and if the derived work is
                     13:  * incompatible with the protocol description in the RFC file, it must be
                     14:  * called by a name other than "ssh" or "Secure Shell".
                     15:  *
1.44      markus     16:  * SSH2 support added by Markus Friedl.
1.156     markus     17:  * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl.  All rights reserved.
1.67      deraadt    18:  * Copyright (c) 1999 Dug Song.  All rights reserved.
                     19:  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
                     20:  *
                     21:  * Redistribution and use in source and binary forms, with or without
                     22:  * modification, are permitted provided that the following conditions
                     23:  * are met:
                     24:  * 1. Redistributions of source code must retain the above copyright
                     25:  *    notice, this list of conditions and the following disclaimer.
                     26:  * 2. Redistributions in binary form must reproduce the above copyright
                     27:  *    notice, this list of conditions and the following disclaimer in the
                     28:  *    documentation and/or other materials provided with the distribution.
                     29:  *
                     30:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     31:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     32:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     33:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     34:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     35:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     36:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     37:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     38:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     39:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.26      deraadt    40:  */
1.1       deraadt    41:
1.265     deraadt    42: #include <sys/types.h>
1.234     stevesk    43: #include <sys/ioctl.h>
1.235     stevesk    44: #include <sys/un.h>
1.251     stevesk    45: #include <sys/socket.h>
1.261     stevesk    46: #include <sys/time.h>
1.275     djm        47: #include <sys/queue.h>
1.251     stevesk    48:
                     49: #include <netinet/in.h>
                     50: #include <arpa/inet.h>
1.233     stevesk    51:
1.254     stevesk    52: #include <errno.h>
1.298     dtucker    53: #include <fcntl.h>
1.255     stevesk    54: #include <netdb.h>
1.263     stevesk    55: #include <stdio.h>
1.262     stevesk    56: #include <stdlib.h>
1.260     stevesk    57: #include <string.h>
1.233     stevesk    58: #include <termios.h>
1.256     stevesk    59: #include <unistd.h>
1.265     deraadt    60: #include <stdarg.h>
1.1       deraadt    61:
1.265     deraadt    62: #include "xmalloc.h"
1.1       deraadt    63: #include "ssh.h"
1.82      markus     64: #include "ssh1.h"
                     65: #include "ssh2.h"
1.1       deraadt    66: #include "packet.h"
1.82      markus     67: #include "log.h"
                     68: #include "misc.h"
1.265     deraadt    69: #include "buffer.h"
1.14      markus     70: #include "channels.h"
                     71: #include "compat.h"
1.82      markus     72: #include "canohost.h"
1.64      markus     73: #include "key.h"
                     74: #include "authfd.h"
1.147     stevesk    75: #include "pathnames.h"
1.1       deraadt    76:
1.121     markus     77: /* -- channel core */
1.12      markus     78:
1.27      markus     79: /*
                     80:  * Pointer to an array containing all allocated channels.  The array is
                     81:  * dynamically extended as needed.
                     82:  */
1.113     markus     83: static Channel **channels = NULL;
1.1       deraadt    84:
1.27      markus     85: /*
                     86:  * Size of the channel array.  All slots of the array must always be
1.113     markus     87:  * initialized (at least the type field); unused slots set to NULL
1.27      markus     88:  */
1.209     avsm       89: static u_int channels_alloc = 0;
1.1       deraadt    90:
1.27      markus     91: /*
                     92:  * Maximum file descriptor value used in any of the channels.  This is
1.113     markus     93:  * updated in channel_new.
1.27      markus     94:  */
1.84      markus     95: static int channel_max_fd = 0;
1.1       deraadt    96:
                     97:
1.121     markus     98: /* -- tcp forwarding */
1.1       deraadt    99:
1.27      markus    100: /*
                    101:  * Data structure for storing which hosts are permitted for forward requests.
                    102:  * The local sides of any remote forwards are stored in this array to prevent
                    103:  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
                    104:  * network (which might be behind a firewall).
                    105:  */
1.25      markus    106: typedef struct {
1.41      markus    107:        char *host_to_connect;          /* Connect to 'host'. */
                    108:        u_short port_to_connect;        /* Connect to 'port'. */
                    109:        u_short listen_port;            /* Remote side should listen port number. */
1.1       deraadt   110: } ForwardPermission;
                    111:
1.257     dtucker   112: /* List of all permitted host/port pairs to connect by the user. */
1.305     djm       113: static ForwardPermission *permitted_opens = NULL;
1.121     markus    114:
1.257     dtucker   115: /* List of all permitted host/port pairs to connect by the admin. */
1.305     djm       116: static ForwardPermission *permitted_adm_opens = NULL;
1.257     dtucker   117:
                    118: /* Number of permitted host/port pairs in the array permitted by the user. */
1.1       deraadt   119: static int num_permitted_opens = 0;
1.257     dtucker   120:
                    121: /* Number of permitted host/port pair in the array permitted by the admin. */
                    122: static int num_adm_permitted_opens = 0;
                    123:
1.27      markus    124: /*
                    125:  * If this is true, all opens are permitted.  This is the case on the server
                    126:  * on which we have to trust the client anyway, and the user could do
                    127:  * anything after logging in anyway.
                    128:  */
1.1       deraadt   129: static int all_opens_permitted = 0;
                    130:
1.121     markus    131:
                    132: /* -- X11 forwarding */
                    133:
                    134: /* Maximum number of fake X11 displays to try. */
                    135: #define MAX_DISPLAYS  1000
                    136:
1.219     djm       137: /* Saved X11 local (client) display. */
                    138: static char *x11_saved_display = NULL;
                    139:
1.121     markus    140: /* Saved X11 authentication protocol name. */
                    141: static char *x11_saved_proto = NULL;
                    142:
                    143: /* Saved X11 authentication data.  This is the real data. */
                    144: static char *x11_saved_data = NULL;
                    145: static u_int x11_saved_data_len = 0;
                    146:
                    147: /*
                    148:  * Fake X11 authentication data.  This is what the server will be sending us;
                    149:  * we should replace any occurrences of this by the real data.
                    150:  */
1.240     deraadt   151: static u_char *x11_fake_data = NULL;
1.121     markus    152: static u_int x11_fake_data_len;
                    153:
                    154:
                    155: /* -- agent forwarding */
                    156:
                    157: #define        NUM_SOCKS       10
                    158:
1.82      markus    159: /* AF_UNSPEC or AF_INET or AF_INET6 */
1.135     markus    160: static int IPv4or6 = AF_UNSPEC;
1.1       deraadt   161:
1.121     markus    162: /* helper */
1.127     itojun    163: static void port_open_helper(Channel *c, char *rtype);
1.103     markus    164:
1.276     djm       165: /* non-blocking connect helpers */
                    166: static int connect_next(struct channel_connect *);
                    167: static void channel_connect_ctx_free(struct channel_connect *);
                    168:
1.121     markus    169: /* -- channel core */
1.41      markus    170:
                    171: Channel *
1.229     markus    172: channel_by_id(int id)
1.41      markus    173: {
                    174:        Channel *c;
1.113     markus    175:
1.209     avsm      176:        if (id < 0 || (u_int)id >= channels_alloc) {
1.229     markus    177:                logit("channel_by_id: %d: bad id", id);
1.41      markus    178:                return NULL;
                    179:        }
1.113     markus    180:        c = channels[id];
                    181:        if (c == NULL) {
1.229     markus    182:                logit("channel_by_id: %d: bad id: channel free", id);
1.41      markus    183:                return NULL;
                    184:        }
                    185:        return c;
1.55      markus    186: }
                    187:
1.27      markus    188: /*
1.229     markus    189:  * Returns the channel if it is allowed to receive protocol messages.
                    190:  * Private channels, like listening sockets, may not receive messages.
                    191:  */
                    192: Channel *
                    193: channel_lookup(int id)
                    194: {
                    195:        Channel *c;
                    196:
                    197:        if ((c = channel_by_id(id)) == NULL)
                    198:                return (NULL);
                    199:
1.237     deraadt   200:        switch (c->type) {
1.229     markus    201:        case SSH_CHANNEL_X11_OPEN:
                    202:        case SSH_CHANNEL_LARVAL:
                    203:        case SSH_CHANNEL_CONNECTING:
                    204:        case SSH_CHANNEL_DYNAMIC:
                    205:        case SSH_CHANNEL_OPENING:
                    206:        case SSH_CHANNEL_OPEN:
                    207:        case SSH_CHANNEL_INPUT_DRAINING:
                    208:        case SSH_CHANNEL_OUTPUT_DRAINING:
                    209:                return (c);
                    210:        }
                    211:        logit("Non-public channel %d, type %d.", id, c->type);
                    212:        return (NULL);
                    213: }
                    214:
                    215: /*
1.55      markus    216:  * Register filedescriptors for a channel, used when allocating a channel or
1.52      markus    217:  * when the channel consumer/producer is ready, e.g. shell exec'd
1.27      markus    218:  */
1.127     itojun    219: static void
1.71      markus    220: channel_register_fds(Channel *c, int rfd, int wfd, int efd,
1.282     dtucker   221:     int extusage, int nonblock, int is_tty)
1.1       deraadt   222: {
1.25      markus    223:        /* Update the maximum file descriptor value. */
1.84      markus    224:        channel_max_fd = MAX(channel_max_fd, rfd);
                    225:        channel_max_fd = MAX(channel_max_fd, wfd);
                    226:        channel_max_fd = MAX(channel_max_fd, efd);
                    227:
1.298     dtucker   228:        if (rfd != -1)
                    229:                fcntl(rfd, F_SETFD, FD_CLOEXEC);
                    230:        if (wfd != -1 && wfd != rfd)
                    231:                fcntl(wfd, F_SETFD, FD_CLOEXEC);
                    232:        if (efd != -1 && efd != rfd && efd != wfd)
                    233:                fcntl(efd, F_SETFD, FD_CLOEXEC);
1.55      markus    234:
1.52      markus    235:        c->rfd = rfd;
                    236:        c->wfd = wfd;
                    237:        c->sock = (rfd == wfd) ? rfd : -1;
                    238:        c->efd = efd;
                    239:        c->extended_usage = extusage;
1.71      markus    240:
1.282     dtucker   241:        if ((c->isatty = is_tty) != 0)
1.194     markus    242:                debug2("channel %d: rfd %d isatty", c->self, c->rfd);
1.91      markus    243:
1.71      markus    244:        /* enable nonblocking mode */
                    245:        if (nonblock) {
                    246:                if (rfd != -1)
                    247:                        set_nonblock(rfd);
                    248:                if (wfd != -1)
                    249:                        set_nonblock(wfd);
                    250:                if (efd != -1)
                    251:                        set_nonblock(efd);
                    252:        }
1.52      markus    253: }
                    254:
                    255: /*
                    256:  * Allocate a new channel object and set its type and socket. This will cause
                    257:  * remote_name to be freed.
                    258:  */
1.113     markus    259: Channel *
1.52      markus    260: channel_new(char *ctype, int type, int rfd, int wfd, int efd,
1.178     markus    261:     u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
1.52      markus    262: {
1.209     avsm      263:        int found;
                    264:        u_int i;
1.52      markus    265:        Channel *c;
1.25      markus    266:
                    267:        /* Do initial allocation if this is the first call. */
                    268:        if (channels_alloc == 0) {
                    269:                channels_alloc = 10;
1.242     djm       270:                channels = xcalloc(channels_alloc, sizeof(Channel *));
1.25      markus    271:                for (i = 0; i < channels_alloc; i++)
1.113     markus    272:                        channels[i] = NULL;
1.25      markus    273:        }
                    274:        /* Try to find a free slot where to put the new channel. */
                    275:        for (found = -1, i = 0; i < channels_alloc; i++)
1.113     markus    276:                if (channels[i] == NULL) {
1.25      markus    277:                        /* Found a free slot. */
1.209     avsm      278:                        found = (int)i;
1.25      markus    279:                        break;
                    280:                }
1.209     avsm      281:        if (found < 0) {
1.27      markus    282:                /* There are no free slots.  Take last+1 slot and expand the array.  */
1.25      markus    283:                found = channels_alloc;
1.179     markus    284:                if (channels_alloc > 10000)
                    285:                        fatal("channel_new: internal error: channels_alloc %d "
                    286:                            "too big.", channels_alloc);
1.243     djm       287:                channels = xrealloc(channels, channels_alloc + 10,
                    288:                    sizeof(Channel *));
1.195     markus    289:                channels_alloc += 10;
1.70      markus    290:                debug2("channel: expanding %d", channels_alloc);
1.25      markus    291:                for (i = found; i < channels_alloc; i++)
1.113     markus    292:                        channels[i] = NULL;
1.25      markus    293:        }
1.113     markus    294:        /* Initialize and return new channel. */
1.242     djm       295:        c = channels[found] = xcalloc(1, sizeof(Channel));
1.25      markus    296:        buffer_init(&c->input);
                    297:        buffer_init(&c->output);
1.41      markus    298:        buffer_init(&c->extended);
1.293     djm       299:        c->path = NULL;
1.159     markus    300:        c->ostate = CHAN_OUTPUT_OPEN;
                    301:        c->istate = CHAN_INPUT_OPEN;
                    302:        c->flags = 0;
1.281     djm       303:        channel_register_fds(c, rfd, wfd, efd, extusage, nonblock, 0);
1.25      markus    304:        c->self = found;
                    305:        c->type = type;
1.41      markus    306:        c->ctype = ctype;
1.51      markus    307:        c->local_window = window;
                    308:        c->local_window_max = window;
                    309:        c->local_consumed = 0;
                    310:        c->local_maxpacket = maxpack;
1.25      markus    311:        c->remote_id = -1;
1.190     markus    312:        c->remote_name = xstrdup(remote_name);
1.41      markus    313:        c->remote_window = 0;
                    314:        c->remote_maxpacket = 0;
1.133     markus    315:        c->force_drain = 0;
1.149     markus    316:        c->single_connection = 0;
1.131     markus    317:        c->detach_user = NULL;
1.225     djm       318:        c->detach_close = 0;
1.275     djm       319:        c->open_confirm = NULL;
                    320:        c->open_confirm_ctx = NULL;
1.65      markus    321:        c->input_filter = NULL;
1.231     reyk      322:        c->output_filter = NULL;
1.280     djm       323:        c->filter_ctx = NULL;
                    324:        c->filter_cleanup = NULL;
1.302     djm       325:        c->ctl_chan = -1;
                    326:        c->mux_rcb = NULL;
                    327:        c->mux_ctx = NULL;
1.304     djm       328:        c->mux_pause = 0;
1.299     markus    329:        c->delayed = 1;         /* prevent call to channel_post handler */
1.275     djm       330:        TAILQ_INIT(&c->status_confirms);
1.25      markus    331:        debug("channel %d: new [%s]", found, remote_name);
1.113     markus    332:        return c;
1.1       deraadt   333: }
1.52      markus    334:
1.132     markus    335: static int
                    336: channel_find_maxfd(void)
                    337: {
1.209     avsm      338:        u_int i;
                    339:        int max = 0;
1.132     markus    340:        Channel *c;
                    341:
                    342:        for (i = 0; i < channels_alloc; i++) {
                    343:                c = channels[i];
                    344:                if (c != NULL) {
                    345:                        max = MAX(max, c->rfd);
                    346:                        max = MAX(max, c->wfd);
                    347:                        max = MAX(max, c->efd);
                    348:                }
                    349:        }
                    350:        return max;
                    351: }
                    352:
                    353: int
                    354: channel_close_fd(int *fdp)
                    355: {
                    356:        int ret = 0, fd = *fdp;
                    357:
                    358:        if (fd != -1) {
                    359:                ret = close(fd);
                    360:                *fdp = -1;
                    361:                if (fd == channel_max_fd)
                    362:                        channel_max_fd = channel_find_maxfd();
                    363:        }
                    364:        return ret;
                    365: }
                    366:
1.52      markus    367: /* Close all channel fd/socket. */
1.127     itojun    368: static void
1.52      markus    369: channel_close_fds(Channel *c)
                    370: {
1.132     markus    371:        channel_close_fd(&c->sock);
                    372:        channel_close_fd(&c->rfd);
                    373:        channel_close_fd(&c->wfd);
                    374:        channel_close_fd(&c->efd);
1.121     markus    375: }
                    376:
                    377: /* Free the channel and close its fd/socket. */
                    378: void
                    379: channel_free(Channel *c)
                    380: {
                    381:        char *s;
1.209     avsm      382:        u_int i, n;
1.275     djm       383:        struct channel_confirm *cc;
1.121     markus    384:
                    385:        for (n = 0, i = 0; i < channels_alloc; i++)
                    386:                if (channels[i])
                    387:                        n++;
1.209     avsm      388:        debug("channel %d: free: %s, nchannels %u", c->self,
1.121     markus    389:            c->remote_name ? c->remote_name : "???", n);
                    390:
                    391:        s = channel_open_message();
1.194     markus    392:        debug3("channel %d: status: %s", c->self, s);
1.121     markus    393:        xfree(s);
                    394:
                    395:        if (c->sock != -1)
                    396:                shutdown(c->sock, SHUT_RDWR);
                    397:        channel_close_fds(c);
                    398:        buffer_free(&c->input);
                    399:        buffer_free(&c->output);
                    400:        buffer_free(&c->extended);
                    401:        if (c->remote_name) {
                    402:                xfree(c->remote_name);
                    403:                c->remote_name = NULL;
                    404:        }
1.293     djm       405:        if (c->path) {
                    406:                xfree(c->path);
                    407:                c->path = NULL;
                    408:        }
1.275     djm       409:        while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
                    410:                if (cc->abandon_cb != NULL)
                    411:                        cc->abandon_cb(c, cc->ctx);
                    412:                TAILQ_REMOVE(&c->status_confirms, cc, entry);
                    413:                bzero(cc, sizeof(*cc));
                    414:                xfree(cc);
                    415:        }
1.280     djm       416:        if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
                    417:                c->filter_cleanup(c->self, c->filter_ctx);
1.121     markus    418:        channels[c->self] = NULL;
                    419:        xfree(c);
                    420: }
                    421:
                    422: void
1.126     markus    423: channel_free_all(void)
1.121     markus    424: {
1.209     avsm      425:        u_int i;
1.121     markus    426:
1.126     markus    427:        for (i = 0; i < channels_alloc; i++)
                    428:                if (channels[i] != NULL)
                    429:                        channel_free(channels[i]);
1.131     markus    430: }
                    431:
1.121     markus    432: /*
                    433:  * Closes the sockets/fds of all channels.  This is used to close extra file
                    434:  * descriptors after a fork.
                    435:  */
                    436: void
1.142     itojun    437: channel_close_all(void)
1.121     markus    438: {
1.209     avsm      439:        u_int i;
1.121     markus    440:
                    441:        for (i = 0; i < channels_alloc; i++)
                    442:                if (channels[i] != NULL)
                    443:                        channel_close_fds(channels[i]);
                    444: }
                    445:
                    446: /*
1.131     markus    447:  * Stop listening to channels.
                    448:  */
                    449: void
                    450: channel_stop_listening(void)
                    451: {
1.209     avsm      452:        u_int i;
1.131     markus    453:        Channel *c;
                    454:
                    455:        for (i = 0; i < channels_alloc; i++) {
                    456:                c = channels[i];
                    457:                if (c != NULL) {
                    458:                        switch (c->type) {
                    459:                        case SSH_CHANNEL_AUTH_SOCKET:
                    460:                        case SSH_CHANNEL_PORT_LISTENER:
                    461:                        case SSH_CHANNEL_RPORT_LISTENER:
                    462:                        case SSH_CHANNEL_X11_LISTENER:
1.132     markus    463:                                channel_close_fd(&c->sock);
1.131     markus    464:                                channel_free(c);
                    465:                                break;
                    466:                        }
                    467:                }
                    468:        }
                    469: }
                    470:
                    471: /*
1.121     markus    472:  * Returns true if no channel has too much buffered data, and false if one or
                    473:  * more channel is overfull.
                    474:  */
                    475: int
1.142     itojun    476: channel_not_very_much_buffered_data(void)
1.121     markus    477: {
                    478:        u_int i;
                    479:        Channel *c;
                    480:
                    481:        for (i = 0; i < channels_alloc; i++) {
                    482:                c = channels[i];
                    483:                if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
1.136     markus    484: #if 0
                    485:                        if (!compat20 &&
                    486:                            buffer_len(&c->input) > packet_get_maxsize()) {
1.185     markus    487:                                debug2("channel %d: big input buffer %d",
1.121     markus    488:                                    c->self, buffer_len(&c->input));
                    489:                                return 0;
                    490:                        }
1.136     markus    491: #endif
1.121     markus    492:                        if (buffer_len(&c->output) > packet_get_maxsize()) {
1.191     markus    493:                                debug2("channel %d: big output buffer %u > %u",
1.136     markus    494:                                    c->self, buffer_len(&c->output),
                    495:                                    packet_get_maxsize());
1.121     markus    496:                                return 0;
                    497:                        }
                    498:                }
                    499:        }
                    500:        return 1;
                    501: }
                    502:
                    503: /* Returns true if any channel is still open. */
                    504: int
1.142     itojun    505: channel_still_open(void)
1.121     markus    506: {
1.209     avsm      507:        u_int i;
1.121     markus    508:        Channel *c;
                    509:
                    510:        for (i = 0; i < channels_alloc; i++) {
                    511:                c = channels[i];
                    512:                if (c == NULL)
                    513:                        continue;
                    514:                switch (c->type) {
                    515:                case SSH_CHANNEL_X11_LISTENER:
                    516:                case SSH_CHANNEL_PORT_LISTENER:
                    517:                case SSH_CHANNEL_RPORT_LISTENER:
1.302     djm       518:                case SSH_CHANNEL_MUX_LISTENER:
1.121     markus    519:                case SSH_CHANNEL_CLOSED:
                    520:                case SSH_CHANNEL_AUTH_SOCKET:
                    521:                case SSH_CHANNEL_DYNAMIC:
                    522:                case SSH_CHANNEL_CONNECTING:
                    523:                case SSH_CHANNEL_ZOMBIE:
                    524:                        continue;
                    525:                case SSH_CHANNEL_LARVAL:
                    526:                        if (!compat20)
                    527:                                fatal("cannot happen: SSH_CHANNEL_LARVAL");
                    528:                        continue;
                    529:                case SSH_CHANNEL_OPENING:
                    530:                case SSH_CHANNEL_OPEN:
                    531:                case SSH_CHANNEL_X11_OPEN:
1.302     djm       532:                case SSH_CHANNEL_MUX_CLIENT:
1.121     markus    533:                        return 1;
                    534:                case SSH_CHANNEL_INPUT_DRAINING:
                    535:                case SSH_CHANNEL_OUTPUT_DRAINING:
                    536:                        if (!compat13)
                    537:                                fatal("cannot happen: OUT_DRAIN");
                    538:                        return 1;
                    539:                default:
                    540:                        fatal("channel_still_open: bad channel type %d", c->type);
                    541:                        /* NOTREACHED */
                    542:                }
                    543:        }
                    544:        return 0;
                    545: }
                    546:
                    547: /* Returns the id of an open channel suitable for keepaliving */
                    548: int
1.142     itojun    549: channel_find_open(void)
1.121     markus    550: {
1.209     avsm      551:        u_int i;
1.121     markus    552:        Channel *c;
                    553:
                    554:        for (i = 0; i < channels_alloc; i++) {
                    555:                c = channels[i];
1.206     djm       556:                if (c == NULL || c->remote_id < 0)
1.121     markus    557:                        continue;
                    558:                switch (c->type) {
                    559:                case SSH_CHANNEL_CLOSED:
                    560:                case SSH_CHANNEL_DYNAMIC:
                    561:                case SSH_CHANNEL_X11_LISTENER:
                    562:                case SSH_CHANNEL_PORT_LISTENER:
                    563:                case SSH_CHANNEL_RPORT_LISTENER:
1.302     djm       564:                case SSH_CHANNEL_MUX_LISTENER:
                    565:                case SSH_CHANNEL_MUX_CLIENT:
1.121     markus    566:                case SSH_CHANNEL_OPENING:
                    567:                case SSH_CHANNEL_CONNECTING:
                    568:                case SSH_CHANNEL_ZOMBIE:
                    569:                        continue;
                    570:                case SSH_CHANNEL_LARVAL:
                    571:                case SSH_CHANNEL_AUTH_SOCKET:
                    572:                case SSH_CHANNEL_OPEN:
                    573:                case SSH_CHANNEL_X11_OPEN:
                    574:                        return i;
                    575:                case SSH_CHANNEL_INPUT_DRAINING:
                    576:                case SSH_CHANNEL_OUTPUT_DRAINING:
                    577:                        if (!compat13)
                    578:                                fatal("cannot happen: OUT_DRAIN");
                    579:                        return i;
                    580:                default:
                    581:                        fatal("channel_find_open: bad channel type %d", c->type);
                    582:                        /* NOTREACHED */
                    583:                }
                    584:        }
                    585:        return -1;
                    586: }
                    587:
                    588:
                    589: /*
                    590:  * Returns a message describing the currently open forwarded connections,
                    591:  * suitable for sending to the client.  The message contains crlf pairs for
                    592:  * newlines.
                    593:  */
                    594: char *
1.142     itojun    595: channel_open_message(void)
1.121     markus    596: {
                    597:        Buffer buffer;
                    598:        Channel *c;
                    599:        char buf[1024], *cp;
1.209     avsm      600:        u_int i;
1.121     markus    601:
                    602:        buffer_init(&buffer);
                    603:        snprintf(buf, sizeof buf, "The following connections are open:\r\n");
                    604:        buffer_append(&buffer, buf, strlen(buf));
                    605:        for (i = 0; i < channels_alloc; i++) {
                    606:                c = channels[i];
                    607:                if (c == NULL)
                    608:                        continue;
                    609:                switch (c->type) {
                    610:                case SSH_CHANNEL_X11_LISTENER:
                    611:                case SSH_CHANNEL_PORT_LISTENER:
                    612:                case SSH_CHANNEL_RPORT_LISTENER:
                    613:                case SSH_CHANNEL_CLOSED:
                    614:                case SSH_CHANNEL_AUTH_SOCKET:
                    615:                case SSH_CHANNEL_ZOMBIE:
1.302     djm       616:                case SSH_CHANNEL_MUX_CLIENT:
                    617:                case SSH_CHANNEL_MUX_LISTENER:
1.121     markus    618:                        continue;
                    619:                case SSH_CHANNEL_LARVAL:
                    620:                case SSH_CHANNEL_OPENING:
                    621:                case SSH_CHANNEL_CONNECTING:
                    622:                case SSH_CHANNEL_DYNAMIC:
                    623:                case SSH_CHANNEL_OPEN:
                    624:                case SSH_CHANNEL_X11_OPEN:
                    625:                case SSH_CHANNEL_INPUT_DRAINING:
                    626:                case SSH_CHANNEL_OUTPUT_DRAINING:
1.204     djm       627:                        snprintf(buf, sizeof buf,
1.302     djm       628:                            "  #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d cc %d)\r\n",
1.121     markus    629:                            c->self, c->remote_name,
                    630:                            c->type, c->remote_id,
                    631:                            c->istate, buffer_len(&c->input),
                    632:                            c->ostate, buffer_len(&c->output),
1.302     djm       633:                            c->rfd, c->wfd, c->ctl_chan);
1.121     markus    634:                        buffer_append(&buffer, buf, strlen(buf));
                    635:                        continue;
                    636:                default:
                    637:                        fatal("channel_open_message: bad channel type %d", c->type);
                    638:                        /* NOTREACHED */
                    639:                }
                    640:        }
                    641:        buffer_append(&buffer, "\0", 1);
                    642:        cp = xstrdup(buffer_ptr(&buffer));
                    643:        buffer_free(&buffer);
                    644:        return cp;
                    645: }
                    646:
                    647: void
                    648: channel_send_open(int id)
                    649: {
                    650:        Channel *c = channel_lookup(id);
1.180     deraadt   651:
1.121     markus    652:        if (c == NULL) {
1.188     itojun    653:                logit("channel_send_open: %d: bad id", id);
1.121     markus    654:                return;
                    655:        }
1.184     markus    656:        debug2("channel %d: send open", id);
1.121     markus    657:        packet_start(SSH2_MSG_CHANNEL_OPEN);
                    658:        packet_put_cstring(c->ctype);
                    659:        packet_put_int(c->self);
                    660:        packet_put_int(c->local_window);
                    661:        packet_put_int(c->local_maxpacket);
                    662:        packet_send();
                    663: }
                    664:
                    665: void
1.184     markus    666: channel_request_start(int id, char *service, int wantconfirm)
1.121     markus    667: {
1.184     markus    668:        Channel *c = channel_lookup(id);
1.180     deraadt   669:
1.121     markus    670:        if (c == NULL) {
1.188     itojun    671:                logit("channel_request_start: %d: unknown channel id", id);
1.121     markus    672:                return;
                    673:        }
1.204     djm       674:        debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
1.121     markus    675:        packet_start(SSH2_MSG_CHANNEL_REQUEST);
                    676:        packet_put_int(c->remote_id);
                    677:        packet_put_cstring(service);
                    678:        packet_put_char(wantconfirm);
                    679: }
1.241     deraadt   680:
1.121     markus    681: void
1.275     djm       682: channel_register_status_confirm(int id, channel_confirm_cb *cb,
                    683:     channel_confirm_abandon_cb *abandon_cb, void *ctx)
                    684: {
                    685:        struct channel_confirm *cc;
                    686:        Channel *c;
                    687:
                    688:        if ((c = channel_lookup(id)) == NULL)
                    689:                fatal("channel_register_expect: %d: bad id", id);
                    690:
                    691:        cc = xmalloc(sizeof(*cc));
                    692:        cc->cb = cb;
                    693:        cc->abandon_cb = abandon_cb;
                    694:        cc->ctx = ctx;
                    695:        TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
                    696: }
                    697:
                    698: void
1.304     djm       699: channel_register_open_confirm(int id, channel_open_fn *fn, void *ctx)
1.121     markus    700: {
                    701:        Channel *c = channel_lookup(id);
1.180     deraadt   702:
1.121     markus    703:        if (c == NULL) {
1.287     stevesk   704:                logit("channel_register_open_confirm: %d: bad id", id);
1.121     markus    705:                return;
                    706:        }
1.275     djm       707:        c->open_confirm = fn;
                    708:        c->open_confirm_ctx = ctx;
1.121     markus    709: }
1.241     deraadt   710:
1.121     markus    711: void
1.225     djm       712: channel_register_cleanup(int id, channel_callback_fn *fn, int do_close)
1.121     markus    713: {
1.229     markus    714:        Channel *c = channel_by_id(id);
1.180     deraadt   715:
1.121     markus    716:        if (c == NULL) {
1.188     itojun    717:                logit("channel_register_cleanup: %d: bad id", id);
1.121     markus    718:                return;
                    719:        }
1.131     markus    720:        c->detach_user = fn;
1.225     djm       721:        c->detach_close = do_close;
1.121     markus    722: }
1.241     deraadt   723:
1.121     markus    724: void
                    725: channel_cancel_cleanup(int id)
                    726: {
1.229     markus    727:        Channel *c = channel_by_id(id);
1.180     deraadt   728:
1.121     markus    729:        if (c == NULL) {
1.188     itojun    730:                logit("channel_cancel_cleanup: %d: bad id", id);
1.121     markus    731:                return;
1.52      markus    732:        }
1.131     markus    733:        c->detach_user = NULL;
1.225     djm       734:        c->detach_close = 0;
1.121     markus    735: }
1.241     deraadt   736:
1.121     markus    737: void
1.231     reyk      738: channel_register_filter(int id, channel_infilter_fn *ifn,
1.280     djm       739:     channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
1.121     markus    740: {
                    741:        Channel *c = channel_lookup(id);
1.180     deraadt   742:
1.121     markus    743:        if (c == NULL) {
1.188     itojun    744:                logit("channel_register_filter: %d: bad id", id);
1.121     markus    745:                return;
1.52      markus    746:        }
1.231     reyk      747:        c->input_filter = ifn;
                    748:        c->output_filter = ofn;
1.279     djm       749:        c->filter_ctx = ctx;
1.280     djm       750:        c->filter_cleanup = cfn;
1.52      markus    751: }
                    752:
1.49      markus    753: void
1.121     markus    754: channel_set_fds(int id, int rfd, int wfd, int efd,
1.282     dtucker   755:     int extusage, int nonblock, int is_tty, u_int window_max)
1.1       deraadt   756: {
1.121     markus    757:        Channel *c = channel_lookup(id);
1.180     deraadt   758:
1.121     markus    759:        if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
                    760:                fatal("channel_activate for non-larval channel %d.", id);
1.282     dtucker   761:        channel_register_fds(c, rfd, wfd, efd, extusage, nonblock, is_tty);
1.121     markus    762:        c->type = SSH_CHANNEL_OPEN;
1.168     markus    763:        c->local_window = c->local_window_max = window_max;
1.121     markus    764:        packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
                    765:        packet_put_int(c->remote_id);
                    766:        packet_put_int(c->local_window);
                    767:        packet_send();
1.1       deraadt   768: }
                    769:
1.27      markus    770: /*
1.41      markus    771:  * 'channel_pre*' are called just before select() to add any bits relevant to
                    772:  * channels in the select bitmasks.
                    773:  */
                    774: /*
                    775:  * 'channel_post*': perform any appropriate operations for channels which
                    776:  * have events pending.
1.27      markus    777:  */
1.237     deraadt   778: typedef void chan_fn(Channel *c, fd_set *readset, fd_set *writeset);
1.41      markus    779: chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
                    780: chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
                    781:
1.259     stevesk   782: /* ARGSUSED */
1.127     itojun    783: static void
1.237     deraadt   784: channel_pre_listener(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    785: {
                    786:        FD_SET(c->sock, readset);
                    787: }
                    788:
1.259     stevesk   789: /* ARGSUSED */
1.127     itojun    790: static void
1.237     deraadt   791: channel_pre_connecting(Channel *c, fd_set *readset, fd_set *writeset)
1.75      markus    792: {
                    793:        debug3("channel %d: waiting for connection", c->self);
                    794:        FD_SET(c->sock, writeset);
                    795: }
                    796:
1.127     itojun    797: static void
1.237     deraadt   798: channel_pre_open_13(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    799: {
                    800:        if (buffer_len(&c->input) < packet_get_maxsize())
                    801:                FD_SET(c->sock, readset);
                    802:        if (buffer_len(&c->output) > 0)
                    803:                FD_SET(c->sock, writeset);
                    804: }
1.1       deraadt   805:
1.127     itojun    806: static void
1.237     deraadt   807: channel_pre_open(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    808: {
1.157     markus    809:        u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
1.41      markus    810:
1.44      markus    811:        if (c->istate == CHAN_INPUT_OPEN &&
1.157     markus    812:            limit > 0 &&
1.250     djm       813:            buffer_len(&c->input) < limit &&
                    814:            buffer_check_alloc(&c->input, CHAN_RBUF))
1.44      markus    815:                FD_SET(c->rfd, readset);
                    816:        if (c->ostate == CHAN_OUTPUT_OPEN ||
                    817:            c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
                    818:                if (buffer_len(&c->output) > 0) {
                    819:                        FD_SET(c->wfd, writeset);
                    820:                } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1.172     markus    821:                        if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
1.223     djm       822:                                debug2("channel %d: obuf_empty delayed efd %d/(%d)",
                    823:                                    c->self, c->efd, buffer_len(&c->extended));
1.172     markus    824:                        else
                    825:                                chan_obuf_empty(c);
1.44      markus    826:                }
                    827:        }
                    828:        /** XXX check close conditions, too */
1.277     markus    829:        if (compat20 && c->efd != -1 &&
                    830:            !(c->istate == CHAN_INPUT_CLOSED && c->ostate == CHAN_OUTPUT_CLOSED)) {
1.44      markus    831:                if (c->extended_usage == CHAN_EXTENDED_WRITE &&
                    832:                    buffer_len(&c->extended) > 0)
                    833:                        FD_SET(c->efd, writeset);
1.306     djm       834:                else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
                    835:                    (c->extended_usage == CHAN_EXTENDED_READ ||
                    836:                    c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1.44      markus    837:                    buffer_len(&c->extended) < c->remote_window)
                    838:                        FD_SET(c->efd, readset);
                    839:        }
1.204     djm       840:        /* XXX: What about efd? races? */
1.44      markus    841: }
                    842:
1.259     stevesk   843: /* ARGSUSED */
1.127     itojun    844: static void
1.237     deraadt   845: channel_pre_input_draining(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    846: {
                    847:        if (buffer_len(&c->input) == 0) {
                    848:                packet_start(SSH_MSG_CHANNEL_CLOSE);
                    849:                packet_put_int(c->remote_id);
                    850:                packet_send();
                    851:                c->type = SSH_CHANNEL_CLOSED;
1.194     markus    852:                debug2("channel %d: closing after input drain.", c->self);
1.41      markus    853:        }
                    854: }
                    855:
1.259     stevesk   856: /* ARGSUSED */
1.127     itojun    857: static void
1.237     deraadt   858: channel_pre_output_draining(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    859: {
                    860:        if (buffer_len(&c->output) == 0)
1.113     markus    861:                chan_mark_dead(c);
1.49      markus    862:        else
1.41      markus    863:                FD_SET(c->sock, writeset);
                    864: }
                    865:
                    866: /*
                    867:  * This is a special state for X11 authentication spoofing.  An opened X11
                    868:  * connection (when authentication spoofing is being done) remains in this
                    869:  * state until the first packet has been completely read.  The authentication
                    870:  * data in that packet is then substituted by the real data if it matches the
                    871:  * fake data, and the channel is put into normal mode.
1.51      markus    872:  * XXX All this happens at the client side.
1.121     markus    873:  * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
1.41      markus    874:  */
1.127     itojun    875: static int
1.121     markus    876: x11_open_helper(Buffer *b)
1.1       deraadt   877: {
1.77      markus    878:        u_char *ucp;
                    879:        u_int proto_len, data_len;
1.25      markus    880:
1.41      markus    881:        /* Check if the fixed size part of the packet is in buffer. */
1.121     markus    882:        if (buffer_len(b) < 12)
1.41      markus    883:                return 0;
                    884:
                    885:        /* Parse the lengths of variable-length fields. */
1.155     stevesk   886:        ucp = buffer_ptr(b);
1.41      markus    887:        if (ucp[0] == 0x42) {   /* Byte order MSB first. */
                    888:                proto_len = 256 * ucp[6] + ucp[7];
                    889:                data_len = 256 * ucp[8] + ucp[9];
                    890:        } else if (ucp[0] == 0x6c) {    /* Byte order LSB first. */
                    891:                proto_len = ucp[6] + 256 * ucp[7];
                    892:                data_len = ucp[8] + 256 * ucp[9];
                    893:        } else {
1.194     markus    894:                debug2("Initial X11 packet contains bad byte order byte: 0x%x",
1.148     deraadt   895:                    ucp[0]);
1.41      markus    896:                return -1;
                    897:        }
                    898:
                    899:        /* Check if the whole packet is in buffer. */
1.121     markus    900:        if (buffer_len(b) <
1.41      markus    901:            12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
                    902:                return 0;
                    903:
                    904:        /* Check if authentication protocol matches. */
                    905:        if (proto_len != strlen(x11_saved_proto) ||
                    906:            memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
1.194     markus    907:                debug2("X11 connection uses different authentication protocol.");
1.41      markus    908:                return -1;
                    909:        }
                    910:        /* Check if authentication data matches our fake data. */
                    911:        if (data_len != x11_fake_data_len ||
1.308     djm       912:            timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
1.41      markus    913:                x11_fake_data, x11_fake_data_len) != 0) {
1.194     markus    914:                debug2("X11 auth data does not match fake data.");
1.41      markus    915:                return -1;
                    916:        }
                    917:        /* Check fake data length */
                    918:        if (x11_fake_data_len != x11_saved_data_len) {
                    919:                error("X11 fake_data_len %d != saved_data_len %d",
                    920:                    x11_fake_data_len, x11_saved_data_len);
                    921:                return -1;
                    922:        }
                    923:        /*
                    924:         * Received authentication protocol and data match
                    925:         * our fake data. Substitute the fake data with real
                    926:         * data.
                    927:         */
                    928:        memcpy(ucp + 12 + ((proto_len + 3) & ~3),
                    929:            x11_saved_data, x11_saved_data_len);
                    930:        return 1;
                    931: }
                    932:
1.127     itojun    933: static void
1.237     deraadt   934: channel_pre_x11_open_13(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    935: {
1.121     markus    936:        int ret = x11_open_helper(&c->output);
1.180     deraadt   937:
1.41      markus    938:        if (ret == 1) {
                    939:                /* Start normal processing for the channel. */
                    940:                c->type = SSH_CHANNEL_OPEN;
1.47      markus    941:                channel_pre_open_13(c, readset, writeset);
1.41      markus    942:        } else if (ret == -1) {
                    943:                /*
                    944:                 * We have received an X11 connection that has bad
                    945:                 * authentication information.
                    946:                 */
1.188     itojun    947:                logit("X11 connection rejected because of wrong authentication.");
1.41      markus    948:                buffer_clear(&c->input);
                    949:                buffer_clear(&c->output);
1.132     markus    950:                channel_close_fd(&c->sock);
1.41      markus    951:                c->sock = -1;
                    952:                c->type = SSH_CHANNEL_CLOSED;
                    953:                packet_start(SSH_MSG_CHANNEL_CLOSE);
                    954:                packet_put_int(c->remote_id);
                    955:                packet_send();
                    956:        }
                    957: }
1.25      markus    958:
1.127     itojun    959: static void
1.237     deraadt   960: channel_pre_x11_open(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    961: {
1.121     markus    962:        int ret = x11_open_helper(&c->output);
1.133     markus    963:
                    964:        /* c->force_drain = 1; */
                    965:
1.41      markus    966:        if (ret == 1) {
                    967:                c->type = SSH_CHANNEL_OPEN;
1.157     markus    968:                channel_pre_open(c, readset, writeset);
1.41      markus    969:        } else if (ret == -1) {
1.188     itojun    970:                logit("X11 connection rejected because of wrong authentication.");
1.194     markus    971:                debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
1.156     markus    972:                chan_read_failed(c);
                    973:                buffer_clear(&c->input);
                    974:                chan_ibuf_empty(c);
                    975:                buffer_clear(&c->output);
                    976:                /* for proto v1, the peer will send an IEOF */
                    977:                if (compat20)
                    978:                        chan_write_failed(c);
                    979:                else
                    980:                        c->type = SSH_CHANNEL_OPEN;
1.194     markus    981:                debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
1.41      markus    982:        }
                    983: }
1.25      markus    984:
1.302     djm       985: static void
                    986: channel_pre_mux_client(Channel *c, fd_set *readset, fd_set *writeset)
                    987: {
1.304     djm       988:        if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
1.302     djm       989:            buffer_check_alloc(&c->input, CHAN_RBUF))
                    990:                FD_SET(c->rfd, readset);
                    991:        if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
                    992:                /* clear buffer immediately (discard any partial packet) */
                    993:                buffer_clear(&c->input);
                    994:                chan_ibuf_empty(c);
                    995:                /* Start output drain. XXX just kill chan? */
                    996:                chan_rcvd_oclose(c);
                    997:        }
                    998:        if (c->ostate == CHAN_OUTPUT_OPEN ||
                    999:            c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
                   1000:                if (buffer_len(&c->output) > 0)
                   1001:                        FD_SET(c->wfd, writeset);
                   1002:                else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
                   1003:                        chan_obuf_empty(c);
                   1004:        }
                   1005: }
                   1006:
1.104     markus   1007: /* try to decode a socks4 header */
1.259     stevesk  1008: /* ARGSUSED */
1.127     itojun   1009: static int
1.237     deraadt  1010: channel_decode_socks4(Channel *c, fd_set *readset, fd_set *writeset)
1.103     markus   1011: {
1.181     markus   1012:        char *p, *host;
1.292     djm      1013:        u_int len, have, i, found, need;
1.148     deraadt  1014:        char username[256];
1.103     markus   1015:        struct {
                   1016:                u_int8_t version;
                   1017:                u_int8_t command;
                   1018:                u_int16_t dest_port;
1.104     markus   1019:                struct in_addr dest_addr;
1.103     markus   1020:        } s4_req, s4_rsp;
                   1021:
1.104     markus   1022:        debug2("channel %d: decode socks4", c->self);
1.109     markus   1023:
                   1024:        have = buffer_len(&c->input);
                   1025:        len = sizeof(s4_req);
                   1026:        if (have < len)
                   1027:                return 0;
                   1028:        p = buffer_ptr(&c->input);
1.292     djm      1029:
                   1030:        need = 1;
                   1031:        /* SOCKS4A uses an invalid IP address 0.0.0.x */
                   1032:        if (p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] != 0) {
                   1033:                debug2("channel %d: socks4a request", c->self);
                   1034:                /* ... and needs an extra string (the hostname) */
                   1035:                need = 2;
                   1036:        }
                   1037:        /* Check for terminating NUL on the string(s) */
1.109     markus   1038:        for (found = 0, i = len; i < have; i++) {
                   1039:                if (p[i] == '\0') {
1.292     djm      1040:                        found++;
                   1041:                        if (found == need)
                   1042:                                break;
1.109     markus   1043:                }
                   1044:                if (i > 1024) {
                   1045:                        /* the peer is probably sending garbage */
                   1046:                        debug("channel %d: decode socks4: too long",
                   1047:                            c->self);
                   1048:                        return -1;
                   1049:                }
                   1050:        }
1.292     djm      1051:        if (found < need)
1.109     markus   1052:                return 0;
1.103     markus   1053:        buffer_get(&c->input, (char *)&s4_req.version, 1);
                   1054:        buffer_get(&c->input, (char *)&s4_req.command, 1);
                   1055:        buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
1.104     markus   1056:        buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
1.109     markus   1057:        have = buffer_len(&c->input);
1.103     markus   1058:        p = buffer_ptr(&c->input);
                   1059:        len = strlen(p);
1.106     markus   1060:        debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1.292     djm      1061:        len++;                                  /* trailing '\0' */
1.103     markus   1062:        if (len > have)
1.104     markus   1063:                fatal("channel %d: decode socks4: len %d > have %d",
1.103     markus   1064:                    c->self, len, have);
                   1065:        strlcpy(username, p, sizeof(username));
                   1066:        buffer_consume(&c->input, len);
                   1067:
1.293     djm      1068:        if (c->path != NULL) {
                   1069:                xfree(c->path);
                   1070:                c->path = NULL;
                   1071:        }
1.292     djm      1072:        if (need == 1) {                        /* SOCKS4: one string */
                   1073:                host = inet_ntoa(s4_req.dest_addr);
1.293     djm      1074:                c->path = xstrdup(host);
1.292     djm      1075:        } else {                                /* SOCKS4A: two strings */
                   1076:                have = buffer_len(&c->input);
                   1077:                p = buffer_ptr(&c->input);
                   1078:                len = strlen(p);
                   1079:                debug2("channel %d: decode socks4a: host %s/%d",
                   1080:                    c->self, p, len);
                   1081:                len++;                          /* trailing '\0' */
                   1082:                if (len > have)
                   1083:                        fatal("channel %d: decode socks4a: len %d > have %d",
                   1084:                            c->self, len, have);
1.293     djm      1085:                if (len > NI_MAXHOST) {
1.292     djm      1086:                        error("channel %d: hostname \"%.100s\" too long",
                   1087:                            c->self, p);
                   1088:                        return -1;
                   1089:                }
1.293     djm      1090:                c->path = xstrdup(p);
1.292     djm      1091:                buffer_consume(&c->input, len);
                   1092:        }
1.103     markus   1093:        c->host_port = ntohs(s4_req.dest_port);
1.148     deraadt  1094:
1.194     markus   1095:        debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1.292     djm      1096:            c->self, c->path, c->host_port, s4_req.command);
1.103     markus   1097:
1.104     markus   1098:        if (s4_req.command != 1) {
1.292     djm      1099:                debug("channel %d: cannot handle: %s cn %d",
                   1100:                    c->self, need == 1 ? "SOCKS4" : "SOCKS4A", s4_req.command);
1.104     markus   1101:                return -1;
1.103     markus   1102:        }
1.104     markus   1103:        s4_rsp.version = 0;                     /* vn: 0 for reply */
                   1104:        s4_rsp.command = 90;                    /* cd: req granted */
1.103     markus   1105:        s4_rsp.dest_port = 0;                   /* ignored */
1.104     markus   1106:        s4_rsp.dest_addr.s_addr = INADDR_ANY;   /* ignored */
1.246     deraadt  1107:        buffer_append(&c->output, &s4_rsp, sizeof(s4_rsp));
1.104     markus   1108:        return 1;
                   1109: }
                   1110:
1.193     markus   1111: /* try to decode a socks5 header */
                   1112: #define SSH_SOCKS5_AUTHDONE    0x1000
                   1113: #define SSH_SOCKS5_NOAUTH      0x00
                   1114: #define SSH_SOCKS5_IPV4                0x01
                   1115: #define SSH_SOCKS5_DOMAIN      0x03
                   1116: #define SSH_SOCKS5_IPV6                0x04
                   1117: #define SSH_SOCKS5_CONNECT     0x01
                   1118: #define SSH_SOCKS5_SUCCESS     0x00
                   1119:
1.259     stevesk  1120: /* ARGSUSED */
1.193     markus   1121: static int
1.237     deraadt  1122: channel_decode_socks5(Channel *c, fd_set *readset, fd_set *writeset)
1.193     markus   1123: {
                   1124:        struct {
                   1125:                u_int8_t version;
                   1126:                u_int8_t command;
                   1127:                u_int8_t reserved;
                   1128:                u_int8_t atyp;
                   1129:        } s5_req, s5_rsp;
                   1130:        u_int16_t dest_port;
1.293     djm      1131:        u_char *p, dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
1.252     djm      1132:        u_int have, need, i, found, nmethods, addrlen, af;
1.193     markus   1133:
                   1134:        debug2("channel %d: decode socks5", c->self);
                   1135:        p = buffer_ptr(&c->input);
                   1136:        if (p[0] != 0x05)
                   1137:                return -1;
                   1138:        have = buffer_len(&c->input);
                   1139:        if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
                   1140:                /* format: ver | nmethods | methods */
1.198     djm      1141:                if (have < 2)
1.193     markus   1142:                        return 0;
                   1143:                nmethods = p[1];
                   1144:                if (have < nmethods + 2)
                   1145:                        return 0;
                   1146:                /* look for method: "NO AUTHENTICATION REQUIRED" */
1.268     stevesk  1147:                for (found = 0, i = 2; i < nmethods + 2; i++) {
1.264     stevesk  1148:                        if (p[i] == SSH_SOCKS5_NOAUTH) {
1.193     markus   1149:                                found = 1;
                   1150:                                break;
                   1151:                        }
                   1152:                }
                   1153:                if (!found) {
                   1154:                        debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
                   1155:                            c->self);
                   1156:                        return -1;
                   1157:                }
                   1158:                buffer_consume(&c->input, nmethods + 2);
                   1159:                buffer_put_char(&c->output, 0x05);              /* version */
                   1160:                buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
                   1161:                FD_SET(c->sock, writeset);
                   1162:                c->flags |= SSH_SOCKS5_AUTHDONE;
                   1163:                debug2("channel %d: socks5 auth done", c->self);
                   1164:                return 0;                               /* need more */
                   1165:        }
                   1166:        debug2("channel %d: socks5 post auth", c->self);
                   1167:        if (have < sizeof(s5_req)+1)
                   1168:                return 0;                       /* need more */
1.247     deraadt  1169:        memcpy(&s5_req, p, sizeof(s5_req));
1.193     markus   1170:        if (s5_req.version != 0x05 ||
                   1171:            s5_req.command != SSH_SOCKS5_CONNECT ||
                   1172:            s5_req.reserved != 0x00) {
1.194     markus   1173:                debug2("channel %d: only socks5 connect supported", c->self);
1.193     markus   1174:                return -1;
                   1175:        }
1.213     deraadt  1176:        switch (s5_req.atyp){
1.193     markus   1177:        case SSH_SOCKS5_IPV4:
                   1178:                addrlen = 4;
                   1179:                af = AF_INET;
                   1180:                break;
                   1181:        case SSH_SOCKS5_DOMAIN:
                   1182:                addrlen = p[sizeof(s5_req)];
                   1183:                af = -1;
                   1184:                break;
                   1185:        case SSH_SOCKS5_IPV6:
                   1186:                addrlen = 16;
                   1187:                af = AF_INET6;
                   1188:                break;
                   1189:        default:
1.194     markus   1190:                debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1.193     markus   1191:                return -1;
                   1192:        }
1.252     djm      1193:        need = sizeof(s5_req) + addrlen + 2;
                   1194:        if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
                   1195:                need++;
                   1196:        if (have < need)
1.193     markus   1197:                return 0;
                   1198:        buffer_consume(&c->input, sizeof(s5_req));
                   1199:        if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
                   1200:                buffer_consume(&c->input, 1);    /* host string length */
                   1201:        buffer_get(&c->input, (char *)&dest_addr, addrlen);
                   1202:        buffer_get(&c->input, (char *)&dest_port, 2);
                   1203:        dest_addr[addrlen] = '\0';
1.293     djm      1204:        if (c->path != NULL) {
                   1205:                xfree(c->path);
                   1206:                c->path = NULL;
                   1207:        }
                   1208:        if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1.294     djm      1209:                if (addrlen >= NI_MAXHOST) {
1.293     djm      1210:                        error("channel %d: dynamic request: socks5 hostname "
                   1211:                            "\"%.100s\" too long", c->self, dest_addr);
                   1212:                        return -1;
                   1213:                }
                   1214:                c->path = xstrdup(dest_addr);
                   1215:        } else {
                   1216:                if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
                   1217:                        return -1;
                   1218:                c->path = xstrdup(ntop);
                   1219:        }
1.193     markus   1220:        c->host_port = ntohs(dest_port);
1.198     djm      1221:
1.194     markus   1222:        debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1.193     markus   1223:            c->self, c->path, c->host_port, s5_req.command);
                   1224:
                   1225:        s5_rsp.version = 0x05;
                   1226:        s5_rsp.command = SSH_SOCKS5_SUCCESS;
                   1227:        s5_rsp.reserved = 0;                    /* ignored */
                   1228:        s5_rsp.atyp = SSH_SOCKS5_IPV4;
                   1229:        ((struct in_addr *)&dest_addr)->s_addr = INADDR_ANY;
                   1230:        dest_port = 0;                          /* ignored */
                   1231:
1.246     deraadt  1232:        buffer_append(&c->output, &s5_rsp, sizeof(s5_rsp));
                   1233:        buffer_append(&c->output, &dest_addr, sizeof(struct in_addr));
                   1234:        buffer_append(&c->output, &dest_port, sizeof(dest_port));
1.193     markus   1235:        return 1;
1.301     dtucker  1236: }
                   1237:
                   1238: Channel *
1.302     djm      1239: channel_connect_stdio_fwd(const char *host_to_connect, u_short port_to_connect,
                   1240:     int in, int out)
1.301     dtucker  1241: {
                   1242:        Channel *c;
                   1243:
                   1244:        debug("channel_connect_stdio_fwd %s:%d", host_to_connect,
                   1245:            port_to_connect);
                   1246:
                   1247:        c = channel_new("stdio-forward", SSH_CHANNEL_OPENING, in, out,
                   1248:            -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
                   1249:            0, "stdio-forward", /*nonblock*/0);
                   1250:
                   1251:        c->path = xstrdup(host_to_connect);
                   1252:        c->host_port = port_to_connect;
                   1253:        c->listening_port = 0;
                   1254:        c->force_drain = 1;
                   1255:
                   1256:        channel_register_fds(c, in, out, -1, 0, 1, 0);
                   1257:        port_open_helper(c, "direct-tcpip");
                   1258:
                   1259:        return c;
1.193     markus   1260: }
                   1261:
1.104     markus   1262: /* dynamic port forwarding */
1.127     itojun   1263: static void
1.237     deraadt  1264: channel_pre_dynamic(Channel *c, fd_set *readset, fd_set *writeset)
1.104     markus   1265: {
                   1266:        u_char *p;
1.217     djm      1267:        u_int have;
                   1268:        int ret;
1.103     markus   1269:
1.104     markus   1270:        have = buffer_len(&c->input);
                   1271:        debug2("channel %d: pre_dynamic: have %d", c->self, have);
1.105     markus   1272:        /* buffer_dump(&c->input); */
1.104     markus   1273:        /* check if the fixed size part of the packet is in buffer. */
1.193     markus   1274:        if (have < 3) {
1.104     markus   1275:                /* need more */
                   1276:                FD_SET(c->sock, readset);
                   1277:                return;
                   1278:        }
                   1279:        /* try to guess the protocol */
                   1280:        p = buffer_ptr(&c->input);
                   1281:        switch (p[0]) {
                   1282:        case 0x04:
                   1283:                ret = channel_decode_socks4(c, readset, writeset);
1.193     markus   1284:                break;
                   1285:        case 0x05:
                   1286:                ret = channel_decode_socks5(c, readset, writeset);
1.104     markus   1287:                break;
                   1288:        default:
                   1289:                ret = -1;
                   1290:                break;
                   1291:        }
                   1292:        if (ret < 0) {
1.113     markus   1293:                chan_mark_dead(c);
1.104     markus   1294:        } else if (ret == 0) {
                   1295:                debug2("channel %d: pre_dynamic: need more", c->self);
                   1296:                /* need more */
                   1297:                FD_SET(c->sock, readset);
                   1298:        } else {
                   1299:                /* switch to the next state */
                   1300:                c->type = SSH_CHANNEL_OPENING;
                   1301:                port_open_helper(c, "direct-tcpip");
                   1302:        }
1.103     markus   1303: }
                   1304:
1.41      markus   1305: /* This is our fake X11 server socket. */
1.259     stevesk  1306: /* ARGSUSED */
1.127     itojun   1307: static void
1.237     deraadt  1308: channel_post_x11_listener(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1309: {
1.113     markus   1310:        Channel *nc;
1.285     djm      1311:        struct sockaddr_storage addr;
1.162     stevesk  1312:        int newsock;
1.41      markus   1313:        socklen_t addrlen;
1.85      markus   1314:        char buf[16384], *remote_ipaddr;
1.51      markus   1315:        int remote_port;
1.25      markus   1316:
1.41      markus   1317:        if (FD_ISSET(c->sock, readset)) {
                   1318:                debug("X11 connection requested.");
                   1319:                addrlen = sizeof(addr);
1.285     djm      1320:                newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1.149     markus   1321:                if (c->single_connection) {
1.194     markus   1322:                        debug2("single_connection: closing X11 listener.");
1.149     markus   1323:                        channel_close_fd(&c->sock);
                   1324:                        chan_mark_dead(c);
                   1325:                }
1.41      markus   1326:                if (newsock < 0) {
                   1327:                        error("accept: %.100s", strerror(errno));
                   1328:                        return;
                   1329:                }
1.162     stevesk  1330:                set_nodelay(newsock);
1.85      markus   1331:                remote_ipaddr = get_peer_ipaddr(newsock);
1.51      markus   1332:                remote_port = get_peer_port(newsock);
1.41      markus   1333:                snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1.85      markus   1334:                    remote_ipaddr, remote_port);
1.51      markus   1335:
1.113     markus   1336:                nc = channel_new("accepted x11 socket",
1.51      markus   1337:                    SSH_CHANNEL_OPENING, newsock, newsock, -1,
1.190     markus   1338:                    c->local_window_max, c->local_maxpacket, 0, buf, 1);
1.51      markus   1339:                if (compat20) {
                   1340:                        packet_start(SSH2_MSG_CHANNEL_OPEN);
                   1341:                        packet_put_cstring("x11");
1.113     markus   1342:                        packet_put_int(nc->self);
1.149     markus   1343:                        packet_put_int(nc->local_window_max);
                   1344:                        packet_put_int(nc->local_maxpacket);
1.85      markus   1345:                        /* originator ipaddr and port */
                   1346:                        packet_put_cstring(remote_ipaddr);
1.57      markus   1347:                        if (datafellows & SSH_BUG_X11FWD) {
1.194     markus   1348:                                debug2("ssh2 x11 bug compat mode");
1.57      markus   1349:                        } else {
                   1350:                                packet_put_int(remote_port);
                   1351:                        }
1.51      markus   1352:                        packet_send();
                   1353:                } else {
                   1354:                        packet_start(SSH_SMSG_X11_OPEN);
1.113     markus   1355:                        packet_put_int(nc->self);
1.121     markus   1356:                        if (packet_get_protocol_flags() &
                   1357:                            SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1.125     markus   1358:                                packet_put_cstring(buf);
1.51      markus   1359:                        packet_send();
                   1360:                }
1.85      markus   1361:                xfree(remote_ipaddr);
1.41      markus   1362:        }
                   1363: }
1.25      markus   1364:
1.127     itojun   1365: static void
1.103     markus   1366: port_open_helper(Channel *c, char *rtype)
                   1367: {
                   1368:        int direct;
                   1369:        char buf[1024];
                   1370:        char *remote_ipaddr = get_peer_ipaddr(c->sock);
1.216     markus   1371:        int remote_port = get_peer_port(c->sock);
1.303     djm      1372:
                   1373:        if (remote_port == -1) {
                   1374:                /* Fake addr/port to appease peers that validate it (Tectia) */
                   1375:                xfree(remote_ipaddr);
                   1376:                remote_ipaddr = xstrdup("127.0.0.1");
                   1377:                remote_port = 65535;
                   1378:        }
1.103     markus   1379:
                   1380:        direct = (strcmp(rtype, "direct-tcpip") == 0);
                   1381:
                   1382:        snprintf(buf, sizeof buf,
                   1383:            "%s: listening port %d for %.100s port %d, "
                   1384:            "connect from %.200s port %d",
                   1385:            rtype, c->listening_port, c->path, c->host_port,
                   1386:            remote_ipaddr, remote_port);
                   1387:
                   1388:        xfree(c->remote_name);
                   1389:        c->remote_name = xstrdup(buf);
                   1390:
                   1391:        if (compat20) {
                   1392:                packet_start(SSH2_MSG_CHANNEL_OPEN);
                   1393:                packet_put_cstring(rtype);
                   1394:                packet_put_int(c->self);
                   1395:                packet_put_int(c->local_window_max);
                   1396:                packet_put_int(c->local_maxpacket);
                   1397:                if (direct) {
                   1398:                        /* target host, port */
                   1399:                        packet_put_cstring(c->path);
                   1400:                        packet_put_int(c->host_port);
                   1401:                } else {
                   1402:                        /* listen address, port */
                   1403:                        packet_put_cstring(c->path);
                   1404:                        packet_put_int(c->listening_port);
                   1405:                }
                   1406:                /* originator host and port */
                   1407:                packet_put_cstring(remote_ipaddr);
1.216     markus   1408:                packet_put_int((u_int)remote_port);
1.103     markus   1409:                packet_send();
                   1410:        } else {
                   1411:                packet_start(SSH_MSG_PORT_OPEN);
                   1412:                packet_put_int(c->self);
                   1413:                packet_put_cstring(c->path);
                   1414:                packet_put_int(c->host_port);
1.121     markus   1415:                if (packet_get_protocol_flags() &
                   1416:                    SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1.103     markus   1417:                        packet_put_cstring(c->remote_name);
                   1418:                packet_send();
                   1419:        }
                   1420:        xfree(remote_ipaddr);
                   1421: }
                   1422:
1.226     djm      1423: static void
                   1424: channel_set_reuseaddr(int fd)
                   1425: {
                   1426:        int on = 1;
                   1427:
                   1428:        /*
                   1429:         * Set socket options.
                   1430:         * Allow local port reuse in TIME_WAIT.
                   1431:         */
                   1432:        if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
                   1433:                error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
                   1434: }
                   1435:
1.41      markus   1436: /*
                   1437:  * This socket is listening for connections to a forwarded TCP/IP port.
                   1438:  */
1.259     stevesk  1439: /* ARGSUSED */
1.127     itojun   1440: static void
1.237     deraadt  1441: channel_post_port_listener(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1442: {
1.103     markus   1443:        Channel *nc;
1.285     djm      1444:        struct sockaddr_storage addr;
1.113     markus   1445:        int newsock, nextstate;
1.41      markus   1446:        socklen_t addrlen;
1.103     markus   1447:        char *rtype;
1.73      markus   1448:
1.41      markus   1449:        if (FD_ISSET(c->sock, readset)) {
                   1450:                debug("Connection to port %d forwarding "
                   1451:                    "to %.100s port %d requested.",
                   1452:                    c->listening_port, c->path, c->host_port);
1.103     markus   1453:
1.137     markus   1454:                if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
                   1455:                        nextstate = SSH_CHANNEL_OPENING;
                   1456:                        rtype = "forwarded-tcpip";
                   1457:                } else {
                   1458:                        if (c->host_port == 0) {
                   1459:                                nextstate = SSH_CHANNEL_DYNAMIC;
1.138     markus   1460:                                rtype = "dynamic-tcpip";
1.137     markus   1461:                        } else {
                   1462:                                nextstate = SSH_CHANNEL_OPENING;
                   1463:                                rtype = "direct-tcpip";
                   1464:                        }
                   1465:                }
1.103     markus   1466:
1.41      markus   1467:                addrlen = sizeof(addr);
1.285     djm      1468:                newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1.41      markus   1469:                if (newsock < 0) {
                   1470:                        error("accept: %.100s", strerror(errno));
                   1471:                        return;
                   1472:                }
1.169     stevesk  1473:                set_nodelay(newsock);
1.190     markus   1474:                nc = channel_new(rtype, nextstate, newsock, newsock, -1,
                   1475:                    c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1.103     markus   1476:                nc->listening_port = c->listening_port;
                   1477:                nc->host_port = c->host_port;
1.293     djm      1478:                if (c->path != NULL)
                   1479:                        nc->path = xstrdup(c->path);
1.103     markus   1480:
1.299     markus   1481:                if (nextstate != SSH_CHANNEL_DYNAMIC)
1.103     markus   1482:                        port_open_helper(nc, rtype);
1.41      markus   1483:        }
                   1484: }
1.25      markus   1485:
1.41      markus   1486: /*
                   1487:  * This is the authentication agent socket listening for connections from
                   1488:  * clients.
                   1489:  */
1.259     stevesk  1490: /* ARGSUSED */
1.127     itojun   1491: static void
1.237     deraadt  1492: channel_post_auth_listener(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1493: {
1.113     markus   1494:        Channel *nc;
                   1495:        int newsock;
1.285     djm      1496:        struct sockaddr_storage addr;
1.41      markus   1497:        socklen_t addrlen;
1.25      markus   1498:
1.41      markus   1499:        if (FD_ISSET(c->sock, readset)) {
                   1500:                addrlen = sizeof(addr);
1.285     djm      1501:                newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1.41      markus   1502:                if (newsock < 0) {
                   1503:                        error("accept from auth socket: %.100s", strerror(errno));
                   1504:                        return;
                   1505:                }
1.113     markus   1506:                nc = channel_new("accepted auth socket",
1.73      markus   1507:                    SSH_CHANNEL_OPENING, newsock, newsock, -1,
                   1508:                    c->local_window_max, c->local_maxpacket,
1.190     markus   1509:                    0, "accepted auth socket", 1);
1.73      markus   1510:                if (compat20) {
                   1511:                        packet_start(SSH2_MSG_CHANNEL_OPEN);
                   1512:                        packet_put_cstring("auth-agent@openssh.com");
1.113     markus   1513:                        packet_put_int(nc->self);
1.73      markus   1514:                        packet_put_int(c->local_window_max);
                   1515:                        packet_put_int(c->local_maxpacket);
                   1516:                } else {
                   1517:                        packet_start(SSH_SMSG_AGENT_OPEN);
1.113     markus   1518:                        packet_put_int(nc->self);
1.73      markus   1519:                }
1.41      markus   1520:                packet_send();
                   1521:        }
                   1522: }
1.25      markus   1523:
1.259     stevesk  1524: /* ARGSUSED */
1.127     itojun   1525: static void
1.237     deraadt  1526: channel_post_connecting(Channel *c, fd_set *readset, fd_set *writeset)
1.75      markus   1527: {
1.276     djm      1528:        int err = 0, sock;
1.129     stevesk  1529:        socklen_t sz = sizeof(err);
1.114     markus   1530:
1.75      markus   1531:        if (FD_ISSET(c->sock, writeset)) {
1.170     stevesk  1532:                if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1.114     markus   1533:                        err = errno;
                   1534:                        error("getsockopt SO_ERROR failed");
                   1535:                }
                   1536:                if (err == 0) {
1.276     djm      1537:                        debug("channel %d: connected to %s port %d",
                   1538:                            c->self, c->connect_ctx.host, c->connect_ctx.port);
                   1539:                        channel_connect_ctx_free(&c->connect_ctx);
1.114     markus   1540:                        c->type = SSH_CHANNEL_OPEN;
                   1541:                        if (compat20) {
                   1542:                                packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1543:                                packet_put_int(c->remote_id);
                   1544:                                packet_put_int(c->self);
                   1545:                                packet_put_int(c->local_window);
                   1546:                                packet_put_int(c->local_maxpacket);
                   1547:                        } else {
                   1548:                                packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1549:                                packet_put_int(c->remote_id);
                   1550:                                packet_put_int(c->self);
                   1551:                        }
1.75      markus   1552:                } else {
1.276     djm      1553:                        debug("channel %d: connection failed: %s",
1.114     markus   1554:                            c->self, strerror(err));
1.276     djm      1555:                        /* Try next address, if any */
                   1556:                        if ((sock = connect_next(&c->connect_ctx)) > 0) {
                   1557:                                close(c->sock);
                   1558:                                c->sock = c->rfd = c->wfd = sock;
                   1559:                                channel_max_fd = channel_find_maxfd();
                   1560:                                return;
                   1561:                        }
                   1562:                        /* Exhausted all addresses */
                   1563:                        error("connect_to %.100s port %d: failed.",
                   1564:                            c->connect_ctx.host, c->connect_ctx.port);
                   1565:                        channel_connect_ctx_free(&c->connect_ctx);
1.114     markus   1566:                        if (compat20) {
                   1567:                                packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
                   1568:                                packet_put_int(c->remote_id);
                   1569:                                packet_put_int(SSH2_OPEN_CONNECT_FAILED);
                   1570:                                if (!(datafellows & SSH_BUG_OPENFAILURE)) {
                   1571:                                        packet_put_cstring(strerror(err));
                   1572:                                        packet_put_cstring("");
                   1573:                                }
1.75      markus   1574:                        } else {
1.114     markus   1575:                                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   1576:                                packet_put_int(c->remote_id);
1.75      markus   1577:                        }
1.114     markus   1578:                        chan_mark_dead(c);
1.75      markus   1579:                }
1.114     markus   1580:                packet_send();
1.75      markus   1581:        }
                   1582: }
                   1583:
1.259     stevesk  1584: /* ARGSUSED */
1.127     itojun   1585: static int
1.237     deraadt  1586: channel_handle_rfd(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1587: {
1.214     markus   1588:        char buf[CHAN_RBUF];
1.41      markus   1589:        int len;
1.25      markus   1590:
1.118     markus   1591:        if (c->rfd != -1 &&
1.41      markus   1592:            FD_ISSET(c->rfd, readset)) {
                   1593:                len = read(c->rfd, buf, sizeof(buf));
1.53      markus   1594:                if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1595:                        return 1;
1.41      markus   1596:                if (len <= 0) {
1.194     markus   1597:                        debug2("channel %d: read<=0 rfd %d len %d",
1.41      markus   1598:                            c->self, c->rfd, len);
1.104     markus   1599:                        if (c->type != SSH_CHANNEL_OPEN) {
1.194     markus   1600:                                debug2("channel %d: not open", c->self);
1.113     markus   1601:                                chan_mark_dead(c);
1.103     markus   1602:                                return -1;
1.104     markus   1603:                        } else if (compat13) {
1.158     markus   1604:                                buffer_clear(&c->output);
1.41      markus   1605:                                c->type = SSH_CHANNEL_INPUT_DRAINING;
1.194     markus   1606:                                debug2("channel %d: input draining.", c->self);
1.25      markus   1607:                        } else {
1.41      markus   1608:                                chan_read_failed(c);
1.25      markus   1609:                        }
1.41      markus   1610:                        return -1;
                   1611:                }
1.143     deraadt  1612:                if (c->input_filter != NULL) {
1.66      markus   1613:                        if (c->input_filter(c, buf, len) == -1) {
1.194     markus   1614:                                debug2("channel %d: filter stops", c->self);
1.65      markus   1615:                                chan_read_failed(c);
                   1616:                        }
1.228     reyk     1617:                } else if (c->datagram) {
                   1618:                        buffer_put_string(&c->input, buf, len);
1.65      markus   1619:                } else {
                   1620:                        buffer_append(&c->input, buf, len);
                   1621:                }
1.41      markus   1622:        }
                   1623:        return 1;
                   1624: }
1.241     deraadt  1625:
1.259     stevesk  1626: /* ARGSUSED */
1.127     itojun   1627: static int
1.237     deraadt  1628: channel_handle_wfd(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1629: {
1.95      markus   1630:        struct termios tio;
1.231     reyk     1631:        u_char *data = NULL, *buf;
1.309     djm      1632:        u_int dlen, olen = 0;
1.41      markus   1633:        int len;
1.25      markus   1634:
1.41      markus   1635:        /* Send buffered output data to the socket. */
1.118     markus   1636:        if (c->wfd != -1 &&
1.41      markus   1637:            FD_ISSET(c->wfd, writeset) &&
                   1638:            buffer_len(&c->output) > 0) {
1.309     djm      1639:                olen = buffer_len(&c->output);
1.231     reyk     1640:                if (c->output_filter != NULL) {
                   1641:                        if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
                   1642:                                debug2("channel %d: filter stops", c->self);
1.232     reyk     1643:                                if (c->type != SSH_CHANNEL_OPEN)
                   1644:                                        chan_mark_dead(c);
                   1645:                                else
                   1646:                                        chan_write_failed(c);
                   1647:                                return -1;
1.231     reyk     1648:                        }
                   1649:                } else if (c->datagram) {
                   1650:                        buf = data = buffer_get_string(&c->output, &dlen);
                   1651:                } else {
                   1652:                        buf = data = buffer_ptr(&c->output);
                   1653:                        dlen = buffer_len(&c->output);
                   1654:                }
                   1655:
1.228     reyk     1656:                if (c->datagram) {
                   1657:                        /* ignore truncated writes, datagrams might get lost */
1.231     reyk     1658:                        len = write(c->wfd, buf, dlen);
1.228     reyk     1659:                        xfree(data);
                   1660:                        if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1661:                                return 1;
                   1662:                        if (len <= 0) {
                   1663:                                if (c->type != SSH_CHANNEL_OPEN)
                   1664:                                        chan_mark_dead(c);
                   1665:                                else
                   1666:                                        chan_write_failed(c);
                   1667:                                return -1;
                   1668:                        }
1.309     djm      1669:                        goto out;
1.228     reyk     1670:                }
1.231     reyk     1671:
                   1672:                len = write(c->wfd, buf, dlen);
1.53      markus   1673:                if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1674:                        return 1;
1.41      markus   1675:                if (len <= 0) {
1.104     markus   1676:                        if (c->type != SSH_CHANNEL_OPEN) {
1.194     markus   1677:                                debug2("channel %d: not open", c->self);
1.113     markus   1678:                                chan_mark_dead(c);
1.104     markus   1679:                                return -1;
                   1680:                        } else if (compat13) {
1.158     markus   1681:                                buffer_clear(&c->output);
1.194     markus   1682:                                debug2("channel %d: input draining.", c->self);
1.41      markus   1683:                                c->type = SSH_CHANNEL_INPUT_DRAINING;
                   1684:                        } else {
                   1685:                                chan_write_failed(c);
                   1686:                        }
                   1687:                        return -1;
1.91      markus   1688:                }
1.231     reyk     1689:                if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
1.91      markus   1690:                        if (tcgetattr(c->wfd, &tio) == 0 &&
                   1691:                            !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
                   1692:                                /*
                   1693:                                 * Simulate echo to reduce the impact of
1.96      markus   1694:                                 * traffic analysis. We need to match the
1.95      markus   1695:                                 * size of a SSH2_MSG_CHANNEL_DATA message
1.231     reyk     1696:                                 * (4 byte channel id + buf)
1.91      markus   1697:                                 */
1.95      markus   1698:                                packet_send_ignore(4 + len);
1.91      markus   1699:                                packet_send();
                   1700:                        }
1.25      markus   1701:                }
1.41      markus   1702:                buffer_consume(&c->output, len);
1.44      markus   1703:        }
1.309     djm      1704:  out:
                   1705:        if (compat20 && olen > 0)
                   1706:                c->local_consumed += olen - buffer_len(&c->output);
1.44      markus   1707:        return 1;
                   1708: }
1.241     deraadt  1709:
1.127     itojun   1710: static int
1.237     deraadt  1711: channel_handle_efd(Channel *c, fd_set *readset, fd_set *writeset)
1.44      markus   1712: {
1.214     markus   1713:        char buf[CHAN_RBUF];
1.44      markus   1714:        int len;
                   1715:
1.45      markus   1716: /** XXX handle drain efd, too */
1.44      markus   1717:        if (c->efd != -1) {
                   1718:                if (c->extended_usage == CHAN_EXTENDED_WRITE &&
                   1719:                    FD_ISSET(c->efd, writeset) &&
                   1720:                    buffer_len(&c->extended) > 0) {
                   1721:                        len = write(c->efd, buffer_ptr(&c->extended),
                   1722:                            buffer_len(&c->extended));
1.70      markus   1723:                        debug2("channel %d: written %d to efd %d",
1.44      markus   1724:                            c->self, len, c->efd);
1.93      markus   1725:                        if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1726:                                return 1;
                   1727:                        if (len <= 0) {
                   1728:                                debug2("channel %d: closing write-efd %d",
                   1729:                                    c->self, c->efd);
1.132     markus   1730:                                channel_close_fd(&c->efd);
1.93      markus   1731:                        } else {
1.44      markus   1732:                                buffer_consume(&c->extended, len);
                   1733:                                c->local_consumed += len;
                   1734:                        }
1.306     djm      1735:                } else if (c->efd != -1 &&
                   1736:                    (c->extended_usage == CHAN_EXTENDED_READ ||
                   1737:                    c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1.44      markus   1738:                    FD_ISSET(c->efd, readset)) {
                   1739:                        len = read(c->efd, buf, sizeof(buf));
1.70      markus   1740:                        debug2("channel %d: read %d from efd %d",
1.148     deraadt  1741:                            c->self, len, c->efd);
1.93      markus   1742:                        if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1743:                                return 1;
                   1744:                        if (len <= 0) {
                   1745:                                debug2("channel %d: closing read-efd %d",
1.45      markus   1746:                                    c->self, c->efd);
1.132     markus   1747:                                channel_close_fd(&c->efd);
1.93      markus   1748:                        } else {
1.306     djm      1749:                                if (c->extended_usage == CHAN_EXTENDED_IGNORE) {
                   1750:                                        debug3("channel %d: discard efd",
                   1751:                                            c->self);
                   1752:                                } else
                   1753:                                        buffer_append(&c->extended, buf, len);
1.93      markus   1754:                        }
1.44      markus   1755:                }
                   1756:        }
                   1757:        return 1;
                   1758: }
1.241     deraadt  1759:
1.259     stevesk  1760: /* ARGSUSED */
1.127     itojun   1761: static int
1.93      markus   1762: channel_check_window(Channel *c)
1.44      markus   1763: {
1.104     markus   1764:        if (c->type == SSH_CHANNEL_OPEN &&
                   1765:            !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1.270     dtucker  1766:            ((c->local_window_max - c->local_window >
1.269     markus   1767:            c->local_maxpacket*3) ||
                   1768:            c->local_window < c->local_window_max/2) &&
1.44      markus   1769:            c->local_consumed > 0) {
                   1770:                packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
                   1771:                packet_put_int(c->remote_id);
                   1772:                packet_put_int(c->local_consumed);
                   1773:                packet_send();
1.70      markus   1774:                debug2("channel %d: window %d sent adjust %d",
1.44      markus   1775:                    c->self, c->local_window,
                   1776:                    c->local_consumed);
                   1777:                c->local_window += c->local_consumed;
                   1778:                c->local_consumed = 0;
1.1       deraadt  1779:        }
1.41      markus   1780:        return 1;
1.1       deraadt  1781: }
                   1782:
1.127     itojun   1783: static void
1.237     deraadt  1784: channel_post_open(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1785: {
                   1786:        channel_handle_rfd(c, readset, writeset);
                   1787:        channel_handle_wfd(c, readset, writeset);
1.157     markus   1788:        if (!compat20)
1.137     markus   1789:                return;
1.44      markus   1790:        channel_handle_efd(c, readset, writeset);
1.93      markus   1791:        channel_check_window(c);
1.44      markus   1792: }
                   1793:
1.302     djm      1794: static u_int
                   1795: read_mux(Channel *c, u_int need)
                   1796: {
                   1797:        char buf[CHAN_RBUF];
                   1798:        int len;
                   1799:        u_int rlen;
                   1800:
                   1801:        if (buffer_len(&c->input) < need) {
                   1802:                rlen = need - buffer_len(&c->input);
                   1803:                len = read(c->rfd, buf, MIN(rlen, CHAN_RBUF));
                   1804:                if (len <= 0) {
                   1805:                        if (errno != EINTR && errno != EAGAIN) {
                   1806:                                debug2("channel %d: ctl read<=0 rfd %d len %d",
                   1807:                                    c->self, c->rfd, len);
                   1808:                                chan_read_failed(c);
                   1809:                                return 0;
                   1810:                        }
                   1811:                } else
                   1812:                        buffer_append(&c->input, buf, len);
                   1813:        }
                   1814:        return buffer_len(&c->input);
                   1815: }
                   1816:
                   1817: static void
                   1818: channel_post_mux_client(Channel *c, fd_set *readset, fd_set *writeset)
                   1819: {
                   1820:        u_int need;
                   1821:        ssize_t len;
                   1822:
                   1823:        if (!compat20)
                   1824:                fatal("%s: entered with !compat20", __func__);
                   1825:
1.304     djm      1826:        if (c->rfd != -1 && !c->mux_pause && FD_ISSET(c->rfd, readset) &&
1.302     djm      1827:            (c->istate == CHAN_INPUT_OPEN ||
                   1828:            c->istate == CHAN_INPUT_WAIT_DRAIN)) {
                   1829:                /*
                   1830:                 * Don't not read past the precise end of packets to
                   1831:                 * avoid disrupting fd passing.
                   1832:                 */
                   1833:                if (read_mux(c, 4) < 4) /* read header */
                   1834:                        return;
                   1835:                need = get_u32(buffer_ptr(&c->input));
                   1836: #define CHANNEL_MUX_MAX_PACKET (256 * 1024)
                   1837:                if (need > CHANNEL_MUX_MAX_PACKET) {
                   1838:                        debug2("channel %d: packet too big %u > %u",
                   1839:                            c->self, CHANNEL_MUX_MAX_PACKET, need);
                   1840:                        chan_rcvd_oclose(c);
                   1841:                        return;
                   1842:                }
                   1843:                if (read_mux(c, need + 4) < need + 4) /* read body */
                   1844:                        return;
                   1845:                if (c->mux_rcb(c) != 0) {
                   1846:                        debug("channel %d: mux_rcb failed", c->self);
                   1847:                        chan_mark_dead(c);
                   1848:                        return;
                   1849:                }
                   1850:        }
                   1851:
                   1852:        if (c->wfd != -1 && FD_ISSET(c->wfd, writeset) &&
                   1853:            buffer_len(&c->output) > 0) {
                   1854:                len = write(c->wfd, buffer_ptr(&c->output),
                   1855:                    buffer_len(&c->output));
                   1856:                if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1857:                        return;
                   1858:                if (len <= 0) {
                   1859:                        chan_mark_dead(c);
                   1860:                        return;
                   1861:                }
                   1862:                buffer_consume(&c->output, len);
                   1863:        }
                   1864: }
                   1865:
                   1866: static void
                   1867: channel_post_mux_listener(Channel *c, fd_set *readset, fd_set *writeset)
                   1868: {
                   1869:        Channel *nc;
                   1870:        struct sockaddr_storage addr;
                   1871:        socklen_t addrlen;
                   1872:        int newsock;
                   1873:        uid_t euid;
                   1874:        gid_t egid;
                   1875:
                   1876:        if (!FD_ISSET(c->sock, readset))
                   1877:                return;
                   1878:
                   1879:        debug("multiplexing control connection");
                   1880:
                   1881:        /*
                   1882:         * Accept connection on control socket
                   1883:         */
                   1884:        memset(&addr, 0, sizeof(addr));
                   1885:        addrlen = sizeof(addr);
                   1886:        if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
                   1887:            &addrlen)) == -1) {
                   1888:                error("%s accept: %s", __func__, strerror(errno));
                   1889:                return;
                   1890:        }
                   1891:
                   1892:        if (getpeereid(newsock, &euid, &egid) < 0) {
                   1893:                error("%s getpeereid failed: %s", __func__,
                   1894:                    strerror(errno));
                   1895:                close(newsock);
                   1896:                return;
                   1897:        }
                   1898:        if ((euid != 0) && (getuid() != euid)) {
                   1899:                error("multiplex uid mismatch: peer euid %u != uid %u",
                   1900:                    (u_int)euid, (u_int)getuid());
                   1901:                close(newsock);
                   1902:                return;
                   1903:        }
                   1904:        nc = channel_new("multiplex client", SSH_CHANNEL_MUX_CLIENT,
                   1905:            newsock, newsock, -1, c->local_window_max,
                   1906:            c->local_maxpacket, 0, "mux-control", 1);
                   1907:        nc->mux_rcb = c->mux_rcb;
                   1908:        debug3("%s: new mux channel %d fd %d", __func__,
                   1909:            nc->self, nc->sock);
                   1910:        /* establish state */
                   1911:        nc->mux_rcb(nc);
                   1912:        /* mux state transitions must not elicit protocol messages */
                   1913:        nc->flags |= CHAN_LOCAL;
                   1914: }
                   1915:
1.259     stevesk  1916: /* ARGSUSED */
1.127     itojun   1917: static void
1.237     deraadt  1918: channel_post_output_drain_13(Channel *c, fd_set *readset, fd_set *writeset)
1.1       deraadt  1919: {
1.41      markus   1920:        int len;
1.180     deraadt  1921:
1.41      markus   1922:        /* Send buffered output data to the socket. */
                   1923:        if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
                   1924:                len = write(c->sock, buffer_ptr(&c->output),
                   1925:                            buffer_len(&c->output));
                   1926:                if (len <= 0)
1.158     markus   1927:                        buffer_clear(&c->output);
1.41      markus   1928:                else
                   1929:                        buffer_consume(&c->output, len);
                   1930:        }
                   1931: }
1.25      markus   1932:
1.127     itojun   1933: static void
1.44      markus   1934: channel_handler_init_20(void)
                   1935: {
1.157     markus   1936:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open;
1.51      markus   1937:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
1.44      markus   1938:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
1.73      markus   1939:        channel_pre[SSH_CHANNEL_RPORT_LISTENER] =       &channel_pre_listener;
1.51      markus   1940:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
1.73      markus   1941:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1.75      markus   1942:        channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1.103     markus   1943:        channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1.302     djm      1944:        channel_pre[SSH_CHANNEL_MUX_LISTENER] =         &channel_pre_listener;
                   1945:        channel_pre[SSH_CHANNEL_MUX_CLIENT] =           &channel_pre_mux_client;
1.44      markus   1946:
1.157     markus   1947:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open;
1.44      markus   1948:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
1.73      markus   1949:        channel_post[SSH_CHANNEL_RPORT_LISTENER] =      &channel_post_port_listener;
1.51      markus   1950:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
1.73      markus   1951:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1.75      markus   1952:        channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1.157     markus   1953:        channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
1.302     djm      1954:        channel_post[SSH_CHANNEL_MUX_LISTENER] =        &channel_post_mux_listener;
                   1955:        channel_post[SSH_CHANNEL_MUX_CLIENT] =          &channel_post_mux_client;
1.44      markus   1956: }
                   1957:
1.127     itojun   1958: static void
1.41      markus   1959: channel_handler_init_13(void)
                   1960: {
                   1961:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_13;
                   1962:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open_13;
                   1963:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
                   1964:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
                   1965:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
                   1966:        channel_pre[SSH_CHANNEL_INPUT_DRAINING] =       &channel_pre_input_draining;
                   1967:        channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] =      &channel_pre_output_draining;
1.75      markus   1968:        channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1.103     markus   1969:        channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1.25      markus   1970:
1.157     markus   1971:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open;
1.41      markus   1972:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
                   1973:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
                   1974:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
                   1975:        channel_post[SSH_CHANNEL_OUTPUT_DRAINING] =     &channel_post_output_drain_13;
1.75      markus   1976:        channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1.157     markus   1977:        channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
1.41      markus   1978: }
1.25      markus   1979:
1.127     itojun   1980: static void
1.41      markus   1981: channel_handler_init_15(void)
                   1982: {
1.157     markus   1983:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open;
1.51      markus   1984:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
1.41      markus   1985:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
                   1986:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
                   1987:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1.75      markus   1988:        channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1.103     markus   1989:        channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1.25      markus   1990:
1.41      markus   1991:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
                   1992:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
                   1993:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1.157     markus   1994:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open;
1.75      markus   1995:        channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1.157     markus   1996:        channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
1.41      markus   1997: }
1.27      markus   1998:
1.127     itojun   1999: static void
1.41      markus   2000: channel_handler_init(void)
                   2001: {
                   2002:        int i;
1.180     deraadt  2003:
1.148     deraadt  2004:        for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1.41      markus   2005:                channel_pre[i] = NULL;
                   2006:                channel_post[i] = NULL;
                   2007:        }
1.44      markus   2008:        if (compat20)
                   2009:                channel_handler_init_20();
                   2010:        else if (compat13)
1.41      markus   2011:                channel_handler_init_13();
                   2012:        else
                   2013:                channel_handler_init_15();
                   2014: }
1.25      markus   2015:
1.140     markus   2016: /* gc dead channels */
                   2017: static void
                   2018: channel_garbage_collect(Channel *c)
                   2019: {
                   2020:        if (c == NULL)
                   2021:                return;
                   2022:        if (c->detach_user != NULL) {
1.225     djm      2023:                if (!chan_is_dead(c, c->detach_close))
1.140     markus   2024:                        return;
1.194     markus   2025:                debug2("channel %d: gc: notify user", c->self);
1.140     markus   2026:                c->detach_user(c->self, NULL);
                   2027:                /* if we still have a callback */
                   2028:                if (c->detach_user != NULL)
                   2029:                        return;
1.194     markus   2030:                debug2("channel %d: gc: user detached", c->self);
1.140     markus   2031:        }
                   2032:        if (!chan_is_dead(c, 1))
                   2033:                return;
1.194     markus   2034:        debug2("channel %d: garbage collecting", c->self);
1.140     markus   2035:        channel_free(c);
                   2036: }
                   2037:
1.127     itojun   2038: static void
1.237     deraadt  2039: channel_handler(chan_fn *ftab[], fd_set *readset, fd_set *writeset)
1.41      markus   2040: {
                   2041:        static int did_init = 0;
1.299     markus   2042:        u_int i, oalloc;
1.41      markus   2043:        Channel *c;
1.25      markus   2044:
1.41      markus   2045:        if (!did_init) {
                   2046:                channel_handler_init();
                   2047:                did_init = 1;
                   2048:        }
1.299     markus   2049:        for (i = 0, oalloc = channels_alloc; i < oalloc; i++) {
1.113     markus   2050:                c = channels[i];
                   2051:                if (c == NULL)
1.41      markus   2052:                        continue;
1.299     markus   2053:                if (c->delayed) {
                   2054:                        if (ftab == channel_pre)
                   2055:                                c->delayed = 0;
                   2056:                        else
                   2057:                                continue;
                   2058:                }
1.118     markus   2059:                if (ftab[c->type] != NULL)
                   2060:                        (*ftab[c->type])(c, readset, writeset);
1.140     markus   2061:                channel_garbage_collect(c);
1.1       deraadt  2062:        }
                   2063: }
                   2064:
1.121     markus   2065: /*
                   2066:  * Allocate/update select bitmasks and add any bits relevant to channels in
                   2067:  * select bitmasks.
                   2068:  */
1.49      markus   2069: void
1.100     markus   2070: channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1.209     avsm     2071:     u_int *nallocp, int rekeying)
1.41      markus   2072: {
1.243     djm      2073:        u_int n, sz, nfdset;
1.84      markus   2074:
                   2075:        n = MAX(*maxfdp, channel_max_fd);
                   2076:
1.243     djm      2077:        nfdset = howmany(n+1, NFDBITS);
                   2078:        /* Explicitly test here, because xrealloc isn't always called */
                   2079:        if (nfdset && SIZE_T_MAX / nfdset < sizeof(fd_mask))
                   2080:                fatal("channel_prepare_select: max_fd (%d) is too large", n);
                   2081:        sz = nfdset * sizeof(fd_mask);
                   2082:
1.132     markus   2083:        /* perhaps check sz < nalloc/2 and shrink? */
                   2084:        if (*readsetp == NULL || sz > *nallocp) {
1.243     djm      2085:                *readsetp = xrealloc(*readsetp, nfdset, sizeof(fd_mask));
                   2086:                *writesetp = xrealloc(*writesetp, nfdset, sizeof(fd_mask));
1.132     markus   2087:                *nallocp = sz;
1.84      markus   2088:        }
1.132     markus   2089:        *maxfdp = n;
1.84      markus   2090:        memset(*readsetp, 0, sz);
                   2091:        memset(*writesetp, 0, sz);
                   2092:
1.100     markus   2093:        if (!rekeying)
                   2094:                channel_handler(channel_pre, *readsetp, *writesetp);
1.41      markus   2095: }
                   2096:
1.121     markus   2097: /*
                   2098:  * After select, perform any appropriate operations for channels which have
                   2099:  * events pending.
                   2100:  */
1.49      markus   2101: void
1.237     deraadt  2102: channel_after_select(fd_set *readset, fd_set *writeset)
1.41      markus   2103: {
                   2104:        channel_handler(channel_post, readset, writeset);
                   2105: }
                   2106:
1.121     markus   2107:
1.84      markus   2108: /* If there is data to send to the connection, enqueue some of it now. */
1.49      markus   2109: void
1.142     itojun   2110: channel_output_poll(void)
1.1       deraadt  2111: {
1.41      markus   2112:        Channel *c;
1.209     avsm     2113:        u_int i, len;
1.1       deraadt  2114:
1.25      markus   2115:        for (i = 0; i < channels_alloc; i++) {
1.113     markus   2116:                c = channels[i];
                   2117:                if (c == NULL)
                   2118:                        continue;
1.37      markus   2119:
1.121     markus   2120:                /*
                   2121:                 * We are only interested in channels that can have buffered
                   2122:                 * incoming data.
                   2123:                 */
1.37      markus   2124:                if (compat13) {
1.41      markus   2125:                        if (c->type != SSH_CHANNEL_OPEN &&
                   2126:                            c->type != SSH_CHANNEL_INPUT_DRAINING)
1.37      markus   2127:                                continue;
                   2128:                } else {
1.41      markus   2129:                        if (c->type != SSH_CHANNEL_OPEN)
1.37      markus   2130:                                continue;
                   2131:                }
1.46      markus   2132:                if (compat20 &&
                   2133:                    (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1.93      markus   2134:                        /* XXX is this true? */
1.140     markus   2135:                        debug3("channel %d: will not send data after close", c->self);
1.44      markus   2136:                        continue;
                   2137:                }
1.25      markus   2138:
                   2139:                /* Get the amount of buffered data for this channel. */
1.93      markus   2140:                if ((c->istate == CHAN_INPUT_OPEN ||
                   2141:                    c->istate == CHAN_INPUT_WAIT_DRAIN) &&
                   2142:                    (len = buffer_len(&c->input)) > 0) {
1.228     reyk     2143:                        if (c->datagram) {
                   2144:                                if (len > 0) {
                   2145:                                        u_char *data;
                   2146:                                        u_int dlen;
                   2147:
                   2148:                                        data = buffer_get_string(&c->input,
                   2149:                                            &dlen);
1.309     djm      2150:                                        if (dlen > c->remote_window ||
                   2151:                                            dlen > c->remote_maxpacket) {
                   2152:                                                debug("channel %d: datagram "
                   2153:                                                    "too big for channel",
                   2154:                                                    c->self);
                   2155:                                                xfree(data);
                   2156:                                                continue;
                   2157:                                        }
1.228     reyk     2158:                                        packet_start(SSH2_MSG_CHANNEL_DATA);
                   2159:                                        packet_put_int(c->remote_id);
                   2160:                                        packet_put_string(data, dlen);
                   2161:                                        packet_send();
                   2162:                                        c->remote_window -= dlen + 4;
                   2163:                                        xfree(data);
                   2164:                                }
                   2165:                                continue;
                   2166:                        }
1.121     markus   2167:                        /*
                   2168:                         * Send some data for the other side over the secure
                   2169:                         * connection.
                   2170:                         */
1.44      markus   2171:                        if (compat20) {
                   2172:                                if (len > c->remote_window)
                   2173:                                        len = c->remote_window;
                   2174:                                if (len > c->remote_maxpacket)
                   2175:                                        len = c->remote_maxpacket;
1.25      markus   2176:                        } else {
1.44      markus   2177:                                if (packet_is_interactive()) {
                   2178:                                        if (len > 1024)
                   2179:                                                len = 512;
                   2180:                                } else {
                   2181:                                        /* Keep the packets at reasonable size. */
                   2182:                                        if (len > packet_get_maxsize()/2)
                   2183:                                                len = packet_get_maxsize()/2;
                   2184:                                }
1.25      markus   2185:                        }
1.41      markus   2186:                        if (len > 0) {
1.44      markus   2187:                                packet_start(compat20 ?
                   2188:                                    SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1.41      markus   2189:                                packet_put_int(c->remote_id);
                   2190:                                packet_put_string(buffer_ptr(&c->input), len);
                   2191:                                packet_send();
                   2192:                                buffer_consume(&c->input, len);
                   2193:                                c->remote_window -= len;
                   2194:                        }
                   2195:                } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1.25      markus   2196:                        if (compat13)
                   2197:                                fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1.27      markus   2198:                        /*
                   2199:                         * input-buffer is empty and read-socket shutdown:
1.172     markus   2200:                         * tell peer, that we will not send more data: send IEOF.
                   2201:                         * hack for extended data: delay EOF if EFD still in use.
1.27      markus   2202:                         */
1.172     markus   2203:                        if (CHANNEL_EFD_INPUT_ACTIVE(c))
1.223     djm      2204:                                debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
                   2205:                                    c->self, c->efd, buffer_len(&c->extended));
1.172     markus   2206:                        else
                   2207:                                chan_ibuf_empty(c);
1.25      markus   2208:                }
1.44      markus   2209:                /* Send extended data, i.e. stderr */
                   2210:                if (compat20 &&
1.172     markus   2211:                    !(c->flags & CHAN_EOF_SENT) &&
1.44      markus   2212:                    c->remote_window > 0 &&
                   2213:                    (len = buffer_len(&c->extended)) > 0 &&
                   2214:                    c->extended_usage == CHAN_EXTENDED_READ) {
1.178     markus   2215:                        debug2("channel %d: rwin %u elen %u euse %d",
1.93      markus   2216:                            c->self, c->remote_window, buffer_len(&c->extended),
                   2217:                            c->extended_usage);
1.44      markus   2218:                        if (len > c->remote_window)
                   2219:                                len = c->remote_window;
                   2220:                        if (len > c->remote_maxpacket)
                   2221:                                len = c->remote_maxpacket;
                   2222:                        packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
                   2223:                        packet_put_int(c->remote_id);
                   2224:                        packet_put_int(SSH2_EXTENDED_DATA_STDERR);
                   2225:                        packet_put_string(buffer_ptr(&c->extended), len);
                   2226:                        packet_send();
                   2227:                        buffer_consume(&c->extended, len);
                   2228:                        c->remote_window -= len;
1.93      markus   2229:                        debug2("channel %d: sent ext data %d", c->self, len);
1.44      markus   2230:                }
1.25      markus   2231:        }
1.1       deraadt  2232: }
                   2233:
1.121     markus   2234:
                   2235: /* -- protocol input */
1.249     djm      2236:
                   2237: /* ARGSUSED */
1.49      markus   2238: void
1.154     markus   2239: channel_input_data(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2240: {
1.37      markus   2241:        int id;
1.25      markus   2242:        char *data;
1.309     djm      2243:        u_int data_len, win_len;
1.41      markus   2244:        Channel *c;
1.25      markus   2245:
                   2246:        /* Get the channel number and verify it. */
1.37      markus   2247:        id = packet_get_int();
1.41      markus   2248:        c = channel_lookup(id);
                   2249:        if (c == NULL)
1.37      markus   2250:                packet_disconnect("Received data for nonexistent channel %d.", id);
1.25      markus   2251:
                   2252:        /* Ignore any data for non-open channels (might happen on close) */
1.41      markus   2253:        if (c->type != SSH_CHANNEL_OPEN &&
                   2254:            c->type != SSH_CHANNEL_X11_OPEN)
1.37      markus   2255:                return;
                   2256:
1.25      markus   2257:        /* Get the data. */
1.274     markus   2258:        data = packet_get_string_ptr(&data_len);
1.309     djm      2259:        win_len = data_len;
                   2260:        if (c->datagram)
                   2261:                win_len += 4;  /* string length header */
1.200     markus   2262:
                   2263:        /*
                   2264:         * Ignore data for protocol > 1.3 if output end is no longer open.
                   2265:         * For protocol 2 the sending side is reducing its window as it sends
                   2266:         * data, so we must 'fake' consumption of the data in order to ensure
                   2267:         * that window updates are sent back.  Otherwise the connection might
                   2268:         * deadlock.
                   2269:         */
                   2270:        if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
                   2271:                if (compat20) {
1.309     djm      2272:                        c->local_window -= win_len;
                   2273:                        c->local_consumed += win_len;
1.200     markus   2274:                }
                   2275:                return;
                   2276:        }
1.41      markus   2277:
1.143     deraadt  2278:        if (compat20) {
1.309     djm      2279:                if (win_len > c->local_maxpacket) {
1.188     itojun   2280:                        logit("channel %d: rcvd big packet %d, maxpack %d",
1.309     djm      2281:                            c->self, win_len, c->local_maxpacket);
1.44      markus   2282:                }
1.309     djm      2283:                if (win_len > c->local_window) {
1.188     itojun   2284:                        logit("channel %d: rcvd too much data %d, win %d",
1.309     djm      2285:                            c->self, win_len, c->local_window);
1.44      markus   2286:                        return;
                   2287:                }
1.309     djm      2288:                c->local_window -= win_len;
1.44      markus   2289:        }
1.228     reyk     2290:        if (c->datagram)
                   2291:                buffer_put_string(&c->output, data, data_len);
                   2292:        else
                   2293:                buffer_append(&c->output, data, data_len);
1.274     markus   2294:        packet_check_eom();
1.1       deraadt  2295: }
1.121     markus   2296:
1.249     djm      2297: /* ARGSUSED */
1.49      markus   2298: void
1.154     markus   2299: channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
1.44      markus   2300: {
                   2301:        int id;
                   2302:        char *data;
1.177     markus   2303:        u_int data_len, tcode;
1.44      markus   2304:        Channel *c;
                   2305:
                   2306:        /* Get the channel number and verify it. */
                   2307:        id = packet_get_int();
                   2308:        c = channel_lookup(id);
                   2309:
                   2310:        if (c == NULL)
                   2311:                packet_disconnect("Received extended_data for bad channel %d.", id);
                   2312:        if (c->type != SSH_CHANNEL_OPEN) {
1.188     itojun   2313:                logit("channel %d: ext data for non open", id);
1.44      markus   2314:                return;
1.172     markus   2315:        }
                   2316:        if (c->flags & CHAN_EOF_RCVD) {
                   2317:                if (datafellows & SSH_BUG_EXTEOF)
                   2318:                        debug("channel %d: accepting ext data after eof", id);
                   2319:                else
                   2320:                        packet_disconnect("Received extended_data after EOF "
                   2321:                            "on channel %d.", id);
1.44      markus   2322:        }
                   2323:        tcode = packet_get_int();
                   2324:        if (c->efd == -1 ||
                   2325:            c->extended_usage != CHAN_EXTENDED_WRITE ||
                   2326:            tcode != SSH2_EXTENDED_DATA_STDERR) {
1.188     itojun   2327:                logit("channel %d: bad ext data", c->self);
1.44      markus   2328:                return;
                   2329:        }
                   2330:        data = packet_get_string(&data_len);
1.152     markus   2331:        packet_check_eom();
1.44      markus   2332:        if (data_len > c->local_window) {
1.188     itojun   2333:                logit("channel %d: rcvd too much extended_data %d, win %d",
1.44      markus   2334:                    c->self, data_len, c->local_window);
                   2335:                xfree(data);
                   2336:                return;
                   2337:        }
1.70      markus   2338:        debug2("channel %d: rcvd ext data %d", c->self, data_len);
1.44      markus   2339:        c->local_window -= data_len;
                   2340:        buffer_append(&c->extended, data, data_len);
                   2341:        xfree(data);
                   2342: }
                   2343:
1.249     djm      2344: /* ARGSUSED */
1.49      markus   2345: void
1.154     markus   2346: channel_input_ieof(int type, u_int32_t seq, void *ctxt)
1.41      markus   2347: {
                   2348:        int id;
                   2349:        Channel *c;
                   2350:
                   2351:        id = packet_get_int();
1.152     markus   2352:        packet_check_eom();
1.41      markus   2353:        c = channel_lookup(id);
                   2354:        if (c == NULL)
                   2355:                packet_disconnect("Received ieof for nonexistent channel %d.", id);
                   2356:        chan_rcvd_ieof(c);
1.133     markus   2357:
                   2358:        /* XXX force input close */
1.156     markus   2359:        if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
1.133     markus   2360:                debug("channel %d: FORCE input drain", c->self);
                   2361:                c->istate = CHAN_INPUT_WAIT_DRAIN;
1.161     markus   2362:                if (buffer_len(&c->input) == 0)
                   2363:                        chan_ibuf_empty(c);
1.133     markus   2364:        }
                   2365:
1.41      markus   2366: }
1.1       deraadt  2367:
1.249     djm      2368: /* ARGSUSED */
1.49      markus   2369: void
1.154     markus   2370: channel_input_close(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2371: {
1.41      markus   2372:        int id;
                   2373:        Channel *c;
1.1       deraadt  2374:
1.41      markus   2375:        id = packet_get_int();
1.152     markus   2376:        packet_check_eom();
1.41      markus   2377:        c = channel_lookup(id);
                   2378:        if (c == NULL)
                   2379:                packet_disconnect("Received close for nonexistent channel %d.", id);
1.27      markus   2380:
                   2381:        /*
                   2382:         * Send a confirmation that we have closed the channel and no more
                   2383:         * data is coming for it.
                   2384:         */
1.25      markus   2385:        packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1.41      markus   2386:        packet_put_int(c->remote_id);
1.25      markus   2387:        packet_send();
                   2388:
1.27      markus   2389:        /*
                   2390:         * If the channel is in closed state, we have sent a close request,
                   2391:         * and the other side will eventually respond with a confirmation.
                   2392:         * Thus, we cannot free the channel here, because then there would be
                   2393:         * no-one to receive the confirmation.  The channel gets freed when
                   2394:         * the confirmation arrives.
                   2395:         */
1.41      markus   2396:        if (c->type != SSH_CHANNEL_CLOSED) {
1.27      markus   2397:                /*
                   2398:                 * Not a closed channel - mark it as draining, which will
                   2399:                 * cause it to be freed later.
                   2400:                 */
1.158     markus   2401:                buffer_clear(&c->input);
1.41      markus   2402:                c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1.25      markus   2403:        }
1.1       deraadt  2404: }
                   2405:
1.41      markus   2406: /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1.249     djm      2407: /* ARGSUSED */
1.49      markus   2408: void
1.154     markus   2409: channel_input_oclose(int type, u_int32_t seq, void *ctxt)
1.41      markus   2410: {
                   2411:        int id = packet_get_int();
                   2412:        Channel *c = channel_lookup(id);
1.151     markus   2413:
1.152     markus   2414:        packet_check_eom();
1.41      markus   2415:        if (c == NULL)
                   2416:                packet_disconnect("Received oclose for nonexistent channel %d.", id);
                   2417:        chan_rcvd_oclose(c);
                   2418: }
1.1       deraadt  2419:
1.249     djm      2420: /* ARGSUSED */
1.49      markus   2421: void
1.154     markus   2422: channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2423: {
1.41      markus   2424:        int id = packet_get_int();
                   2425:        Channel *c = channel_lookup(id);
1.1       deraadt  2426:
1.152     markus   2427:        packet_check_eom();
1.41      markus   2428:        if (c == NULL)
                   2429:                packet_disconnect("Received close confirmation for "
                   2430:                    "out-of-range channel %d.", id);
                   2431:        if (c->type != SSH_CHANNEL_CLOSED)
                   2432:                packet_disconnect("Received close confirmation for "
                   2433:                    "non-closed channel %d (type %d).", id, c->type);
1.113     markus   2434:        channel_free(c);
1.1       deraadt  2435: }
                   2436:
1.249     djm      2437: /* ARGSUSED */
1.49      markus   2438: void
1.154     markus   2439: channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2440: {
1.41      markus   2441:        int id, remote_id;
                   2442:        Channel *c;
1.1       deraadt  2443:
1.41      markus   2444:        id = packet_get_int();
                   2445:        c = channel_lookup(id);
1.25      markus   2446:
1.41      markus   2447:        if (c==NULL || c->type != SSH_CHANNEL_OPENING)
                   2448:                packet_disconnect("Received open confirmation for "
                   2449:                    "non-opening channel %d.", id);
                   2450:        remote_id = packet_get_int();
1.27      markus   2451:        /* Record the remote channel number and mark that the channel is now open. */
1.41      markus   2452:        c->remote_id = remote_id;
                   2453:        c->type = SSH_CHANNEL_OPEN;
1.44      markus   2454:
                   2455:        if (compat20) {
                   2456:                c->remote_window = packet_get_int();
                   2457:                c->remote_maxpacket = packet_get_int();
1.275     djm      2458:                if (c->open_confirm) {
1.70      markus   2459:                        debug2("callback start");
1.304     djm      2460:                        c->open_confirm(c->self, 1, c->open_confirm_ctx);
1.70      markus   2461:                        debug2("callback done");
1.44      markus   2462:                }
1.194     markus   2463:                debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
1.44      markus   2464:                    c->remote_window, c->remote_maxpacket);
                   2465:        }
1.152     markus   2466:        packet_check_eom();
1.1       deraadt  2467: }
                   2468:
1.127     itojun   2469: static char *
1.114     markus   2470: reason2txt(int reason)
                   2471: {
1.143     deraadt  2472:        switch (reason) {
1.114     markus   2473:        case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
                   2474:                return "administratively prohibited";
                   2475:        case SSH2_OPEN_CONNECT_FAILED:
                   2476:                return "connect failed";
                   2477:        case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
                   2478:                return "unknown channel type";
                   2479:        case SSH2_OPEN_RESOURCE_SHORTAGE:
                   2480:                return "resource shortage";
                   2481:        }
1.117     stevesk  2482:        return "unknown reason";
1.114     markus   2483: }
                   2484:
1.249     djm      2485: /* ARGSUSED */
1.49      markus   2486: void
1.154     markus   2487: channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2488: {
1.86      markus   2489:        int id, reason;
                   2490:        char *msg = NULL, *lang = NULL;
1.41      markus   2491:        Channel *c;
                   2492:
                   2493:        id = packet_get_int();
                   2494:        c = channel_lookup(id);
1.25      markus   2495:
1.41      markus   2496:        if (c==NULL || c->type != SSH_CHANNEL_OPENING)
                   2497:                packet_disconnect("Received open failure for "
                   2498:                    "non-opening channel %d.", id);
1.44      markus   2499:        if (compat20) {
1.86      markus   2500:                reason = packet_get_int();
1.110     markus   2501:                if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1.86      markus   2502:                        msg  = packet_get_string(NULL);
                   2503:                        lang = packet_get_string(NULL);
                   2504:                }
1.188     itojun   2505:                logit("channel %d: open failed: %s%s%s", id,
1.114     markus   2506:                    reason2txt(reason), msg ? ": ": "", msg ? msg : "");
1.86      markus   2507:                if (msg != NULL)
                   2508:                        xfree(msg);
                   2509:                if (lang != NULL)
                   2510:                        xfree(lang);
1.304     djm      2511:                if (c->open_confirm) {
                   2512:                        debug2("callback start");
                   2513:                        c->open_confirm(c->self, 0, c->open_confirm_ctx);
                   2514:                        debug2("callback done");
                   2515:                }
1.44      markus   2516:        }
1.152     markus   2517:        packet_check_eom();
1.291     djm      2518:        /* Schedule the channel for cleanup/deletion. */
                   2519:        chan_mark_dead(c);
1.44      markus   2520: }
                   2521:
1.249     djm      2522: /* ARGSUSED */
1.121     markus   2523: void
1.154     markus   2524: channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
1.121     markus   2525: {
                   2526:        Channel *c;
1.178     markus   2527:        int id;
                   2528:        u_int adjust;
1.121     markus   2529:
                   2530:        if (!compat20)
                   2531:                return;
                   2532:
                   2533:        /* Get the channel number and verify it. */
                   2534:        id = packet_get_int();
                   2535:        c = channel_lookup(id);
1.1       deraadt  2536:
1.229     markus   2537:        if (c == NULL) {
                   2538:                logit("Received window adjust for non-open channel %d.", id);
1.121     markus   2539:                return;
                   2540:        }
                   2541:        adjust = packet_get_int();
1.152     markus   2542:        packet_check_eom();
1.178     markus   2543:        debug2("channel %d: rcvd adjust %u", id, adjust);
1.121     markus   2544:        c->remote_window += adjust;
                   2545: }
1.1       deraadt  2546:
1.249     djm      2547: /* ARGSUSED */
1.121     markus   2548: void
1.154     markus   2549: channel_input_port_open(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2550: {
1.121     markus   2551:        Channel *c = NULL;
                   2552:        u_short host_port;
                   2553:        char *host, *originator_string;
1.276     djm      2554:        int remote_id;
1.121     markus   2555:
                   2556:        remote_id = packet_get_int();
                   2557:        host = packet_get_string(NULL);
                   2558:        host_port = packet_get_int();
1.25      markus   2559:
1.121     markus   2560:        if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
                   2561:                originator_string = packet_get_string(NULL);
                   2562:        } else {
                   2563:                originator_string = xstrdup("unknown (remote did not supply name)");
                   2564:        }
1.152     markus   2565:        packet_check_eom();
1.276     djm      2566:        c = channel_connect_to(host, host_port,
                   2567:            "connected socket", originator_string);
1.190     markus   2568:        xfree(originator_string);
1.276     djm      2569:        xfree(host);
1.121     markus   2570:        if (c == NULL) {
                   2571:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   2572:                packet_put_int(remote_id);
                   2573:                packet_send();
1.276     djm      2574:        } else
                   2575:                c->remote_id = remote_id;
1.1       deraadt  2576: }
                   2577:
1.275     djm      2578: /* ARGSUSED */
                   2579: void
                   2580: channel_input_status_confirm(int type, u_int32_t seq, void *ctxt)
                   2581: {
                   2582:        Channel *c;
                   2583:        struct channel_confirm *cc;
1.289     markus   2584:        int id;
1.275     djm      2585:
                   2586:        /* Reset keepalive timeout */
1.296     andreas  2587:        packet_set_alive_timeouts(0);
1.275     djm      2588:
1.289     markus   2589:        id = packet_get_int();
1.275     djm      2590:        packet_check_eom();
                   2591:
1.289     markus   2592:        debug2("channel_input_status_confirm: type %d id %d", type, id);
1.275     djm      2593:
1.289     markus   2594:        if ((c = channel_lookup(id)) == NULL) {
                   2595:                logit("channel_input_status_confirm: %d: unknown", id);
1.275     djm      2596:                return;
                   2597:        }
                   2598:        ;
                   2599:        if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
                   2600:                return;
                   2601:        cc->cb(type, c, cc->ctx);
                   2602:        TAILQ_REMOVE(&c->status_confirms, cc, entry);
                   2603:        bzero(cc, sizeof(*cc));
                   2604:        xfree(cc);
                   2605: }
1.121     markus   2606:
                   2607: /* -- tcp forwarding */
1.135     markus   2608:
                   2609: void
                   2610: channel_set_af(int af)
                   2611: {
                   2612:        IPv4or6 = af;
                   2613: }
1.121     markus   2614:
1.160     markus   2615: static int
1.295     djm      2616: channel_setup_fwd_listener(int type, const char *listen_addr,
                   2617:     u_short listen_port, int *allocated_listen_port,
1.160     markus   2618:     const char *host_to_connect, u_short port_to_connect, int gateway_ports)
1.25      markus   2619: {
1.113     markus   2620:        Channel *c;
1.226     djm      2621:        int sock, r, success = 0, wildcard = 0, is_client;
1.35      markus   2622:        struct addrinfo hints, *ai, *aitop;
1.212     djm      2623:        const char *host, *addr;
1.35      markus   2624:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1.295     djm      2625:        in_port_t *lport_p;
1.25      markus   2626:
1.160     markus   2627:        host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
                   2628:            listen_addr : host_to_connect;
1.212     djm      2629:        is_client = (type == SSH_CHANNEL_PORT_LISTENER);
1.87      markus   2630:
1.160     markus   2631:        if (host == NULL) {
                   2632:                error("No forward host name.");
1.218     markus   2633:                return 0;
1.73      markus   2634:        }
1.294     djm      2635:        if (strlen(host) >= NI_MAXHOST) {
1.87      markus   2636:                error("Forward host name too long.");
1.218     markus   2637:                return 0;
1.87      markus   2638:        }
1.25      markus   2639:
1.28      markus   2640:        /*
1.212     djm      2641:         * Determine whether or not a port forward listens to loopback,
1.213     deraadt  2642:         * specified address or wildcard. On the client, a specified bind
                   2643:         * address will always override gateway_ports. On the server, a
                   2644:         * gateway_ports of 1 (``yes'') will override the client's
                   2645:         * specification and force a wildcard bind, whereas a value of 2
                   2646:         * (``clientspecified'') will bind to whatever address the client
1.212     djm      2647:         * asked for.
                   2648:         *
                   2649:         * Special-case listen_addrs are:
                   2650:         *
                   2651:         * "0.0.0.0"               -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
                   2652:         * "" (empty string), "*"  -> wildcard v4/v6
                   2653:         * "localhost"             -> loopback v4/v6
                   2654:         */
                   2655:        addr = NULL;
                   2656:        if (listen_addr == NULL) {
                   2657:                /* No address specified: default to gateway_ports setting */
                   2658:                if (gateway_ports)
                   2659:                        wildcard = 1;
                   2660:        } else if (gateway_ports || is_client) {
                   2661:                if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
1.272     djm      2662:                    strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
1.212     djm      2663:                    *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
                   2664:                    (!is_client && gateway_ports == 1))
                   2665:                        wildcard = 1;
                   2666:                else if (strcmp(listen_addr, "localhost") != 0)
                   2667:                        addr = listen_addr;
                   2668:        }
                   2669:
                   2670:        debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
                   2671:            type, wildcard, (addr == NULL) ? "NULL" : addr);
                   2672:
                   2673:        /*
1.35      markus   2674:         * getaddrinfo returns a loopback address if the hostname is
                   2675:         * set to NULL and hints.ai_flags is not AI_PASSIVE
1.28      markus   2676:         */
1.35      markus   2677:        memset(&hints, 0, sizeof(hints));
                   2678:        hints.ai_family = IPv4or6;
1.212     djm      2679:        hints.ai_flags = wildcard ? AI_PASSIVE : 0;
1.35      markus   2680:        hints.ai_socktype = SOCK_STREAM;
1.73      markus   2681:        snprintf(strport, sizeof strport, "%d", listen_port);
1.212     djm      2682:        if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
                   2683:                if (addr == NULL) {
                   2684:                        /* This really shouldn't happen */
                   2685:                        packet_disconnect("getaddrinfo: fatal error: %s",
1.271     dtucker  2686:                            ssh_gai_strerror(r));
1.212     djm      2687:                } else {
1.218     markus   2688:                        error("channel_setup_fwd_listener: "
1.271     dtucker  2689:                            "getaddrinfo(%.64s): %s", addr,
                   2690:                            ssh_gai_strerror(r));
1.212     djm      2691:                }
1.218     markus   2692:                return 0;
1.212     djm      2693:        }
1.295     djm      2694:        if (allocated_listen_port != NULL)
                   2695:                *allocated_listen_port = 0;
1.35      markus   2696:        for (ai = aitop; ai; ai = ai->ai_next) {
1.295     djm      2697:                switch (ai->ai_family) {
                   2698:                case AF_INET:
                   2699:                        lport_p = &((struct sockaddr_in *)ai->ai_addr)->
                   2700:                            sin_port;
                   2701:                        break;
                   2702:                case AF_INET6:
                   2703:                        lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
                   2704:                            sin6_port;
                   2705:                        break;
                   2706:                default:
1.35      markus   2707:                        continue;
1.295     djm      2708:                }
                   2709:                /*
                   2710:                 * If allocating a port for -R forwards, then use the
                   2711:                 * same port for all address families.
                   2712:                 */
                   2713:                if (type == SSH_CHANNEL_RPORT_LISTENER && listen_port == 0 &&
                   2714:                    allocated_listen_port != NULL && *allocated_listen_port > 0)
                   2715:                        *lport_p = htons(*allocated_listen_port);
                   2716:
1.35      markus   2717:                if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
                   2718:                    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1.160     markus   2719:                        error("channel_setup_fwd_listener: getnameinfo failed");
1.35      markus   2720:                        continue;
                   2721:                }
                   2722:                /* Create a port to listen for the host. */
1.300     dtucker  2723:                sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1.35      markus   2724:                if (sock < 0) {
                   2725:                        /* this is no error since kernel may not support ipv6 */
                   2726:                        verbose("socket: %.100s", strerror(errno));
                   2727:                        continue;
                   2728:                }
1.226     djm      2729:
                   2730:                channel_set_reuseaddr(sock);
1.182     stevesk  2731:
1.295     djm      2732:                debug("Local forwarding listening on %s port %s.",
                   2733:                    ntop, strport);
1.35      markus   2734:
                   2735:                /* Bind the socket to the address. */
                   2736:                if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   2737:                        /* address can be in use ipv6 address is already bound */
                   2738:                        verbose("bind: %.100s", strerror(errno));
                   2739:                        close(sock);
                   2740:                        continue;
                   2741:                }
                   2742:                /* Start listening for connections on the socket. */
1.199     markus   2743:                if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1.35      markus   2744:                        error("listen: %.100s", strerror(errno));
                   2745:                        close(sock);
                   2746:                        continue;
                   2747:                }
1.295     djm      2748:
                   2749:                /*
                   2750:                 * listen_port == 0 requests a dynamically allocated port -
                   2751:                 * record what we got.
                   2752:                 */
                   2753:                if (type == SSH_CHANNEL_RPORT_LISTENER && listen_port == 0 &&
                   2754:                    allocated_listen_port != NULL &&
                   2755:                    *allocated_listen_port == 0) {
                   2756:                        *allocated_listen_port = get_sock_port(sock, 1);
                   2757:                        debug("Allocated listen port %d",
                   2758:                            *allocated_listen_port);
                   2759:                }
                   2760:
1.35      markus   2761:                /* Allocate a channel number for the socket. */
1.121     markus   2762:                c = channel_new("port listener", type, sock, sock, -1,
1.51      markus   2763:                    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1.190     markus   2764:                    0, "port listener", 1);
1.293     djm      2765:                c->path = xstrdup(host);
1.113     markus   2766:                c->host_port = port_to_connect;
                   2767:                c->listening_port = listen_port;
1.35      markus   2768:                success = 1;
                   2769:        }
                   2770:        if (success == 0)
1.160     markus   2771:                error("channel_setup_fwd_listener: cannot listen to port: %d",
1.87      markus   2772:                    listen_port);
1.35      markus   2773:        freeaddrinfo(aitop);
1.87      markus   2774:        return success;
1.25      markus   2775: }
1.1       deraadt  2776:
1.202     djm      2777: int
                   2778: channel_cancel_rport_listener(const char *host, u_short port)
                   2779: {
1.209     avsm     2780:        u_int i;
                   2781:        int found = 0;
1.202     djm      2782:
1.213     deraadt  2783:        for (i = 0; i < channels_alloc; i++) {
1.202     djm      2784:                Channel *c = channels[i];
                   2785:
                   2786:                if (c != NULL && c->type == SSH_CHANNEL_RPORT_LISTENER &&
1.293     djm      2787:                    strcmp(c->path, host) == 0 && c->listening_port == port) {
1.210     djm      2788:                        debug2("%s: close channel %d", __func__, i);
1.202     djm      2789:                        channel_free(c);
                   2790:                        found = 1;
                   2791:                }
                   2792:        }
                   2793:
                   2794:        return (found);
                   2795: }
                   2796:
1.160     markus   2797: /* protocol local port fwd, used by ssh (and sshd in v1) */
                   2798: int
1.212     djm      2799: channel_setup_local_fwd_listener(const char *listen_host, u_short listen_port,
1.160     markus   2800:     const char *host_to_connect, u_short port_to_connect, int gateway_ports)
                   2801: {
                   2802:        return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
1.295     djm      2803:            listen_host, listen_port, NULL, host_to_connect, port_to_connect,
1.212     djm      2804:            gateway_ports);
1.160     markus   2805: }
                   2806:
                   2807: /* protocol v2 remote port fwd, used by sshd */
                   2808: int
                   2809: channel_setup_remote_fwd_listener(const char *listen_address,
1.295     djm      2810:     u_short listen_port, int *allocated_listen_port, int gateway_ports)
1.160     markus   2811: {
                   2812:        return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
1.295     djm      2813:            listen_address, listen_port, allocated_listen_port,
                   2814:            NULL, 0, gateway_ports);
1.160     markus   2815: }
                   2816:
1.27      markus   2817: /*
                   2818:  * Initiate forwarding of connections to port "port" on remote host through
                   2819:  * the secure channel to host:port from local side.
                   2820:  */
1.1       deraadt  2821:
1.253     markus   2822: int
1.212     djm      2823: channel_request_remote_forwarding(const char *listen_host, u_short listen_port,
1.73      markus   2824:     const char *host_to_connect, u_short port_to_connect)
1.25      markus   2825: {
1.153     markus   2826:        int type, success = 0;
1.73      markus   2827:
1.25      markus   2828:        /* Send the forward request to the remote side. */
1.44      markus   2829:        if (compat20) {
1.212     djm      2830:                const char *address_to_bind;
1.267     djm      2831:                if (listen_host == NULL) {
                   2832:                        if (datafellows & SSH_BUG_RFWD_ADDR)
                   2833:                                address_to_bind = "127.0.0.1";
                   2834:                        else
                   2835:                                address_to_bind = "localhost";
                   2836:                } else if (*listen_host == '\0' ||
                   2837:                           strcmp(listen_host, "*") == 0) {
                   2838:                        if (datafellows & SSH_BUG_RFWD_ADDR)
                   2839:                                address_to_bind = "0.0.0.0";
                   2840:                        else
                   2841:                                address_to_bind = "";
                   2842:                } else
1.212     djm      2843:                        address_to_bind = listen_host;
                   2844:
1.44      markus   2845:                packet_start(SSH2_MSG_GLOBAL_REQUEST);
                   2846:                packet_put_cstring("tcpip-forward");
1.173     markus   2847:                packet_put_char(1);                     /* boolean: want reply */
1.44      markus   2848:                packet_put_cstring(address_to_bind);
                   2849:                packet_put_int(listen_port);
1.73      markus   2850:                packet_send();
                   2851:                packet_write_wait();
                   2852:                /* Assume that server accepts the request */
                   2853:                success = 1;
1.44      markus   2854:        } else {
                   2855:                packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1.50      markus   2856:                packet_put_int(listen_port);
                   2857:                packet_put_cstring(host_to_connect);
1.44      markus   2858:                packet_put_int(port_to_connect);
                   2859:                packet_send();
                   2860:                packet_write_wait();
1.73      markus   2861:
                   2862:                /* Wait for response from the remote side. */
1.153     markus   2863:                type = packet_read();
1.73      markus   2864:                switch (type) {
                   2865:                case SSH_SMSG_SUCCESS:
                   2866:                        success = 1;
                   2867:                        break;
                   2868:                case SSH_SMSG_FAILURE:
                   2869:                        break;
                   2870:                default:
                   2871:                        /* Unknown packet */
                   2872:                        packet_disconnect("Protocol error for port forward request:"
                   2873:                            "received packet type %d.", type);
                   2874:                }
                   2875:        }
                   2876:        if (success) {
1.305     djm      2877:                /* Record that connection to this host/port is permitted. */
                   2878:                permitted_opens = xrealloc(permitted_opens,
                   2879:                    num_permitted_opens + 1, sizeof(*permitted_opens));
1.73      markus   2880:                permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
                   2881:                permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
                   2882:                permitted_opens[num_permitted_opens].listen_port = listen_port;
                   2883:                num_permitted_opens++;
1.44      markus   2884:        }
1.253     markus   2885:        return (success ? 0 : -1);
1.1       deraadt  2886: }
                   2887:
1.27      markus   2888: /*
1.208     deraadt  2889:  * Request cancellation of remote forwarding of connection host:port from
1.202     djm      2890:  * local side.
                   2891:  */
                   2892: void
1.212     djm      2893: channel_request_rforward_cancel(const char *host, u_short port)
1.202     djm      2894: {
                   2895:        int i;
                   2896:
                   2897:        if (!compat20)
                   2898:                return;
                   2899:
                   2900:        for (i = 0; i < num_permitted_opens; i++) {
1.208     deraadt  2901:                if (permitted_opens[i].host_to_connect != NULL &&
1.202     djm      2902:                    permitted_opens[i].listen_port == port)
                   2903:                        break;
                   2904:        }
                   2905:        if (i >= num_permitted_opens) {
                   2906:                debug("%s: requested forward not found", __func__);
                   2907:                return;
                   2908:        }
                   2909:        packet_start(SSH2_MSG_GLOBAL_REQUEST);
                   2910:        packet_put_cstring("cancel-tcpip-forward");
                   2911:        packet_put_char(0);
1.212     djm      2912:        packet_put_cstring(host == NULL ? "" : host);
1.202     djm      2913:        packet_put_int(port);
                   2914:        packet_send();
                   2915:
                   2916:        permitted_opens[i].listen_port = 0;
                   2917:        permitted_opens[i].port_to_connect = 0;
1.227     stevesk  2918:        xfree(permitted_opens[i].host_to_connect);
1.202     djm      2919:        permitted_opens[i].host_to_connect = NULL;
                   2920: }
                   2921:
                   2922: /*
1.27      markus   2923:  * This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
                   2924:  * listening for the port, and sends back a success reply (or disconnect
1.253     markus   2925:  * message if there was an error).
1.27      markus   2926:  */
1.253     markus   2927: int
1.56      markus   2928: channel_input_port_forward_request(int is_root, int gateway_ports)
1.1       deraadt  2929: {
1.31      markus   2930:        u_short port, host_port;
1.253     markus   2931:        int success = 0;
1.25      markus   2932:        char *hostname;
1.1       deraadt  2933:
1.25      markus   2934:        /* Get arguments from the packet. */
                   2935:        port = packet_get_int();
                   2936:        hostname = packet_get_string(NULL);
                   2937:        host_port = packet_get_int();
                   2938:
1.27      markus   2939:        /*
                   2940:         * Check that an unprivileged user is not trying to forward a
                   2941:         * privileged port.
                   2942:         */
1.25      markus   2943:        if (port < IPPORT_RESERVED && !is_root)
1.192     markus   2944:                packet_disconnect(
                   2945:                    "Requested forwarding of port %d but user is not root.",
                   2946:                    port);
                   2947:        if (host_port == 0)
                   2948:                packet_disconnect("Dynamic forwarding denied.");
                   2949:
1.73      markus   2950:        /* Initiate forwarding */
1.253     markus   2951:        success = channel_setup_local_fwd_listener(NULL, port, hostname,
1.212     djm      2952:            host_port, gateway_ports);
1.25      markus   2953:
                   2954:        /* Free the argument string. */
                   2955:        xfree(hostname);
1.253     markus   2956:
                   2957:        return (success ? 0 : -1);
1.1       deraadt  2958: }
                   2959:
1.99      markus   2960: /*
                   2961:  * Permits opening to any host/port if permitted_opens[] is empty.  This is
                   2962:  * usually called by the server, because the user could connect to any port
                   2963:  * anyway, and the server has no way to know but to trust the client anyway.
                   2964:  */
                   2965: void
1.142     itojun   2966: channel_permit_all_opens(void)
1.99      markus   2967: {
                   2968:        if (num_permitted_opens == 0)
                   2969:                all_opens_permitted = 1;
                   2970: }
                   2971:
1.101     markus   2972: void
1.99      markus   2973: channel_add_permitted_opens(char *host, int port)
                   2974: {
                   2975:        debug("allow port forwarding to host %s port %d", host, port);
                   2976:
1.305     djm      2977:        permitted_opens = xrealloc(permitted_opens,
                   2978:            num_permitted_opens + 1, sizeof(*permitted_opens));
1.99      markus   2979:        permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
                   2980:        permitted_opens[num_permitted_opens].port_to_connect = port;
                   2981:        num_permitted_opens++;
                   2982:
                   2983:        all_opens_permitted = 0;
                   2984: }
                   2985:
1.258     dtucker  2986: int
1.257     dtucker  2987: channel_add_adm_permitted_opens(char *host, int port)
                   2988: {
1.258     dtucker  2989:        debug("config allows port forwarding to host %s port %d", host, port);
1.257     dtucker  2990:
1.305     djm      2991:        permitted_adm_opens = xrealloc(permitted_adm_opens,
                   2992:            num_adm_permitted_opens + 1, sizeof(*permitted_adm_opens));
1.257     dtucker  2993:        permitted_adm_opens[num_adm_permitted_opens].host_to_connect
                   2994:             = xstrdup(host);
                   2995:        permitted_adm_opens[num_adm_permitted_opens].port_to_connect = port;
1.258     dtucker  2996:        return ++num_adm_permitted_opens;
1.257     dtucker  2997: }
                   2998:
                   2999: void
1.99      markus   3000: channel_clear_permitted_opens(void)
                   3001: {
                   3002:        int i;
                   3003:
                   3004:        for (i = 0; i < num_permitted_opens; i++)
1.202     djm      3005:                if (permitted_opens[i].host_to_connect != NULL)
                   3006:                        xfree(permitted_opens[i].host_to_connect);
1.305     djm      3007:        if (num_permitted_opens > 0) {
                   3008:                xfree(permitted_opens);
                   3009:                permitted_opens = NULL;
                   3010:        }
1.99      markus   3011:        num_permitted_opens = 0;
1.257     dtucker  3012: }
                   3013:
                   3014: void
                   3015: channel_clear_adm_permitted_opens(void)
                   3016: {
                   3017:        int i;
1.99      markus   3018:
1.257     dtucker  3019:        for (i = 0; i < num_adm_permitted_opens; i++)
                   3020:                if (permitted_adm_opens[i].host_to_connect != NULL)
                   3021:                        xfree(permitted_adm_opens[i].host_to_connect);
1.305     djm      3022:        if (num_adm_permitted_opens > 0) {
                   3023:                xfree(permitted_adm_opens);
                   3024:                permitted_adm_opens = NULL;
                   3025:        }
1.257     dtucker  3026:        num_adm_permitted_opens = 0;
1.278     dtucker  3027: }
                   3028:
                   3029: void
                   3030: channel_print_adm_permitted_opens(void)
                   3031: {
1.286     djm      3032:        int i;
1.278     dtucker  3033:
1.290     stevesk  3034:        printf("permitopen");
1.288     stevesk  3035:        if (num_adm_permitted_opens == 0) {
1.290     stevesk  3036:                printf(" any\n");
1.288     stevesk  3037:                return;
                   3038:        }
1.278     dtucker  3039:        for (i = 0; i < num_adm_permitted_opens; i++)
                   3040:                if (permitted_adm_opens[i].host_to_connect != NULL)
                   3041:                        printf(" %s:%d", permitted_adm_opens[i].host_to_connect,
                   3042:                            permitted_adm_opens[i].port_to_connect);
1.290     stevesk  3043:        printf("\n");
1.99      markus   3044: }
                   3045:
1.276     djm      3046: /* Try to start non-blocking connect to next host in cctx list */
1.127     itojun   3047: static int
1.276     djm      3048: connect_next(struct channel_connect *cctx)
1.41      markus   3049: {
1.276     djm      3050:        int sock, saved_errno;
1.41      markus   3051:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
                   3052:
1.276     djm      3053:        for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
                   3054:                if (cctx->ai->ai_family != AF_INET &&
                   3055:                    cctx->ai->ai_family != AF_INET6)
1.41      markus   3056:                        continue;
1.276     djm      3057:                if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
                   3058:                    ntop, sizeof(ntop), strport, sizeof(strport),
                   3059:                    NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
                   3060:                        error("connect_next: getnameinfo failed");
1.41      markus   3061:                        continue;
                   3062:                }
1.300     dtucker  3063:                if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
                   3064:                    cctx->ai->ai_protocol)) == -1) {
1.276     djm      3065:                        if (cctx->ai->ai_next == NULL)
1.186     djm      3066:                                error("socket: %.100s", strerror(errno));
                   3067:                        else
                   3068:                                verbose("socket: %.100s", strerror(errno));
1.41      markus   3069:                        continue;
                   3070:                }
1.205     djm      3071:                if (set_nonblock(sock) == -1)
                   3072:                        fatal("%s: set_nonblock(%d)", __func__, sock);
1.276     djm      3073:                if (connect(sock, cctx->ai->ai_addr,
                   3074:                    cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
                   3075:                        debug("connect_next: host %.100s ([%.100s]:%s): "
                   3076:                            "%.100s", cctx->host, ntop, strport,
1.41      markus   3077:                            strerror(errno));
1.276     djm      3078:                        saved_errno = errno;
1.41      markus   3079:                        close(sock);
1.276     djm      3080:                        errno = saved_errno;
1.89      stevesk  3081:                        continue;       /* fail -- try next */
1.41      markus   3082:                }
1.276     djm      3083:                debug("connect_next: host %.100s ([%.100s]:%s) "
                   3084:                    "in progress, fd=%d", cctx->host, ntop, strport, sock);
                   3085:                cctx->ai = cctx->ai->ai_next;
                   3086:                set_nodelay(sock);
                   3087:                return sock;
                   3088:        }
                   3089:        return -1;
                   3090: }
1.41      markus   3091:
1.276     djm      3092: static void
                   3093: channel_connect_ctx_free(struct channel_connect *cctx)
                   3094: {
                   3095:        xfree(cctx->host);
                   3096:        if (cctx->aitop)
                   3097:                freeaddrinfo(cctx->aitop);
                   3098:        bzero(cctx, sizeof(*cctx));
                   3099:        cctx->host = NULL;
                   3100:        cctx->ai = cctx->aitop = NULL;
                   3101: }
                   3102:
                   3103: /* Return CONNECTING channel to remote host, port */
                   3104: static Channel *
                   3105: connect_to(const char *host, u_short port, char *ctype, char *rname)
                   3106: {
                   3107:        struct addrinfo hints;
                   3108:        int gaierr;
                   3109:        int sock = -1;
                   3110:        char strport[NI_MAXSERV];
                   3111:        struct channel_connect cctx;
                   3112:        Channel *c;
                   3113:
1.284     djm      3114:        memset(&cctx, 0, sizeof(cctx));
1.276     djm      3115:        memset(&hints, 0, sizeof(hints));
                   3116:        hints.ai_family = IPv4or6;
                   3117:        hints.ai_socktype = SOCK_STREAM;
                   3118:        snprintf(strport, sizeof strport, "%d", port);
                   3119:        if ((gaierr = getaddrinfo(host, strport, &hints, &cctx.aitop)) != 0) {
                   3120:                error("connect_to %.100s: unknown host (%s)", host,
                   3121:                    ssh_gai_strerror(gaierr));
                   3122:                return NULL;
1.41      markus   3123:        }
1.276     djm      3124:
                   3125:        cctx.host = xstrdup(host);
                   3126:        cctx.port = port;
                   3127:        cctx.ai = cctx.aitop;
                   3128:
                   3129:        if ((sock = connect_next(&cctx)) == -1) {
                   3130:                error("connect to %.100s port %d failed: %s",
                   3131:                    host, port, strerror(errno));
                   3132:                channel_connect_ctx_free(&cctx);
                   3133:                return NULL;
1.41      markus   3134:        }
1.276     djm      3135:        c = channel_new(ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
                   3136:            CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
                   3137:        c->connect_ctx = cctx;
                   3138:        return c;
1.41      markus   3139: }
1.99      markus   3140:
1.276     djm      3141: Channel *
                   3142: channel_connect_by_listen_address(u_short listen_port, char *ctype, char *rname)
1.73      markus   3143: {
                   3144:        int i;
1.99      markus   3145:
1.276     djm      3146:        for (i = 0; i < num_permitted_opens; i++) {
1.202     djm      3147:                if (permitted_opens[i].host_to_connect != NULL &&
1.276     djm      3148:                    permitted_opens[i].listen_port == listen_port) {
1.99      markus   3149:                        return connect_to(
1.73      markus   3150:                            permitted_opens[i].host_to_connect,
1.276     djm      3151:                            permitted_opens[i].port_to_connect, ctype, rname);
                   3152:                }
                   3153:        }
1.74      markus   3154:        error("WARNING: Server requests forwarding for unknown listen_port %d",
                   3155:            listen_port);
1.276     djm      3156:        return NULL;
1.73      markus   3157: }
                   3158:
1.99      markus   3159: /* Check if connecting to that port is permitted and connect. */
1.276     djm      3160: Channel *
                   3161: channel_connect_to(const char *host, u_short port, char *ctype, char *rname)
1.99      markus   3162: {
1.257     dtucker  3163:        int i, permit, permit_adm = 1;
1.99      markus   3164:
                   3165:        permit = all_opens_permitted;
                   3166:        if (!permit) {
                   3167:                for (i = 0; i < num_permitted_opens; i++)
1.202     djm      3168:                        if (permitted_opens[i].host_to_connect != NULL &&
                   3169:                            permitted_opens[i].port_to_connect == port &&
1.99      markus   3170:                            strcmp(permitted_opens[i].host_to_connect, host) == 0)
                   3171:                                permit = 1;
1.257     dtucker  3172:        }
1.99      markus   3173:
1.257     dtucker  3174:        if (num_adm_permitted_opens > 0) {
                   3175:                permit_adm = 0;
                   3176:                for (i = 0; i < num_adm_permitted_opens; i++)
                   3177:                        if (permitted_adm_opens[i].host_to_connect != NULL &&
                   3178:                            permitted_adm_opens[i].port_to_connect == port &&
                   3179:                            strcmp(permitted_adm_opens[i].host_to_connect, host)
                   3180:                            == 0)
                   3181:                                permit_adm = 1;
1.99      markus   3182:        }
1.257     dtucker  3183:
                   3184:        if (!permit || !permit_adm) {
1.188     itojun   3185:                logit("Received request to connect to host %.100s port %d, "
1.99      markus   3186:                    "but the request was denied.", host, port);
1.276     djm      3187:                return NULL;
1.99      markus   3188:        }
1.276     djm      3189:        return connect_to(host, port, ctype, rname);
1.204     djm      3190: }
                   3191:
                   3192: void
                   3193: channel_send_window_changes(void)
                   3194: {
1.209     avsm     3195:        u_int i;
1.204     djm      3196:        struct winsize ws;
                   3197:
                   3198:        for (i = 0; i < channels_alloc; i++) {
1.213     deraadt  3199:                if (channels[i] == NULL || !channels[i]->client_tty ||
1.204     djm      3200:                    channels[i]->type != SSH_CHANNEL_OPEN)
                   3201:                        continue;
                   3202:                if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
                   3203:                        continue;
                   3204:                channel_request_start(i, "window-change", 0);
1.238     deraadt  3205:                packet_put_int((u_int)ws.ws_col);
                   3206:                packet_put_int((u_int)ws.ws_row);
                   3207:                packet_put_int((u_int)ws.ws_xpixel);
                   3208:                packet_put_int((u_int)ws.ws_ypixel);
1.204     djm      3209:                packet_send();
                   3210:        }
1.99      markus   3211: }
                   3212:
1.121     markus   3213: /* -- X11 forwarding */
1.1       deraadt  3214:
1.27      markus   3215: /*
                   3216:  * Creates an internet domain socket for listening for X11 connections.
1.176     deraadt  3217:  * Returns 0 and a suitable display number for the DISPLAY variable
                   3218:  * stored in display_numberp , or -1 if an error occurs.
1.27      markus   3219:  */
1.141     stevesk  3220: int
1.163     stevesk  3221: x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
1.222     djm      3222:     int single_connection, u_int *display_numberp, int **chanids)
1.1       deraadt  3223: {
1.149     markus   3224:        Channel *nc = NULL;
1.31      markus   3225:        int display_number, sock;
                   3226:        u_short port;
1.35      markus   3227:        struct addrinfo hints, *ai, *aitop;
                   3228:        char strport[NI_MAXSERV];
                   3229:        int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
1.25      markus   3230:
1.224     markus   3231:        if (chanids == NULL)
                   3232:                return -1;
                   3233:
1.33      markus   3234:        for (display_number = x11_display_offset;
1.148     deraadt  3235:            display_number < MAX_DISPLAYS;
                   3236:            display_number++) {
1.25      markus   3237:                port = 6000 + display_number;
1.35      markus   3238:                memset(&hints, 0, sizeof(hints));
                   3239:                hints.ai_family = IPv4or6;
1.163     stevesk  3240:                hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
1.35      markus   3241:                hints.ai_socktype = SOCK_STREAM;
                   3242:                snprintf(strport, sizeof strport, "%d", port);
                   3243:                if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
1.271     dtucker  3244:                        error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
1.141     stevesk  3245:                        return -1;
1.25      markus   3246:                }
1.35      markus   3247:                for (ai = aitop; ai; ai = ai->ai_next) {
                   3248:                        if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   3249:                                continue;
1.300     dtucker  3250:                        sock = socket(ai->ai_family, ai->ai_socktype,
                   3251:                            ai->ai_protocol);
1.35      markus   3252:                        if (sock < 0) {
                   3253:                                error("socket: %.100s", strerror(errno));
1.203     markus   3254:                                freeaddrinfo(aitop);
1.141     stevesk  3255:                                return -1;
1.35      markus   3256:                        }
1.226     djm      3257:                        channel_set_reuseaddr(sock);
1.35      markus   3258:                        if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1.194     markus   3259:                                debug2("bind port %d: %.100s", port, strerror(errno));
1.35      markus   3260:                                close(sock);
1.183     itojun   3261:
1.35      markus   3262:                                for (n = 0; n < num_socks; n++) {
                   3263:                                        close(socks[n]);
                   3264:                                }
                   3265:                                num_socks = 0;
                   3266:                                break;
                   3267:                        }
                   3268:                        socks[num_socks++] = sock;
                   3269:                        if (num_socks == NUM_SOCKS)
                   3270:                                break;
1.25      markus   3271:                }
1.83      stevesk  3272:                freeaddrinfo(aitop);
1.35      markus   3273:                if (num_socks > 0)
                   3274:                        break;
1.25      markus   3275:        }
                   3276:        if (display_number >= MAX_DISPLAYS) {
                   3277:                error("Failed to allocate internet-domain X11 display socket.");
1.141     stevesk  3278:                return -1;
1.25      markus   3279:        }
                   3280:        /* Start listening for connections on the socket. */
1.35      markus   3281:        for (n = 0; n < num_socks; n++) {
                   3282:                sock = socks[n];
1.199     markus   3283:                if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1.35      markus   3284:                        error("listen: %.100s", strerror(errno));
                   3285:                        close(sock);
1.141     stevesk  3286:                        return -1;
1.35      markus   3287:                }
1.25      markus   3288:        }
1.35      markus   3289:
                   3290:        /* Allocate a channel for each socket. */
1.242     djm      3291:        *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
1.35      markus   3292:        for (n = 0; n < num_socks; n++) {
                   3293:                sock = socks[n];
1.149     markus   3294:                nc = channel_new("x11 listener",
1.51      markus   3295:                    SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
                   3296:                    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
1.190     markus   3297:                    0, "X11 inet listener", 1);
1.167     markus   3298:                nc->single_connection = single_connection;
1.224     markus   3299:                (*chanids)[n] = nc->self;
1.35      markus   3300:        }
1.224     markus   3301:        (*chanids)[n] = -1;
1.1       deraadt  3302:
1.141     stevesk  3303:        /* Return the display number for the DISPLAY environment variable. */
1.176     deraadt  3304:        *display_numberp = display_number;
                   3305:        return (0);
1.1       deraadt  3306: }
                   3307:
1.127     itojun   3308: static int
1.77      markus   3309: connect_local_xsocket(u_int dnr)
1.1       deraadt  3310: {
1.25      markus   3311:        int sock;
                   3312:        struct sockaddr_un addr;
                   3313:
1.147     stevesk  3314:        sock = socket(AF_UNIX, SOCK_STREAM, 0);
                   3315:        if (sock < 0)
                   3316:                error("socket: %.100s", strerror(errno));
                   3317:        memset(&addr, 0, sizeof(addr));
                   3318:        addr.sun_family = AF_UNIX;
                   3319:        snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
1.239     deraadt  3320:        if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
1.147     stevesk  3321:                return sock;
                   3322:        close(sock);
1.25      markus   3323:        error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
                   3324:        return -1;
1.1       deraadt  3325: }
                   3326:
1.51      markus   3327: int
                   3328: x11_connect_display(void)
1.1       deraadt  3329: {
1.248     deraadt  3330:        u_int display_number;
1.25      markus   3331:        const char *display;
1.51      markus   3332:        char buf[1024], *cp;
1.35      markus   3333:        struct addrinfo hints, *ai, *aitop;
                   3334:        char strport[NI_MAXSERV];
1.248     deraadt  3335:        int gaierr, sock = 0;
1.25      markus   3336:
                   3337:        /* Try to open a socket for the local X server. */
                   3338:        display = getenv("DISPLAY");
                   3339:        if (!display) {
                   3340:                error("DISPLAY not set.");
1.51      markus   3341:                return -1;
1.25      markus   3342:        }
1.27      markus   3343:        /*
                   3344:         * Now we decode the value of the DISPLAY variable and make a
                   3345:         * connection to the real X server.
                   3346:         */
                   3347:
                   3348:        /*
                   3349:         * Check if it is a unix domain socket.  Unix domain displays are in
                   3350:         * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
                   3351:         */
1.25      markus   3352:        if (strncmp(display, "unix:", 5) == 0 ||
                   3353:            display[0] == ':') {
                   3354:                /* Connect to the unix domain socket. */
1.248     deraadt  3355:                if (sscanf(strrchr(display, ':') + 1, "%u", &display_number) != 1) {
1.25      markus   3356:                        error("Could not parse display number from DISPLAY: %.100s",
1.148     deraadt  3357:                            display);
1.51      markus   3358:                        return -1;
1.25      markus   3359:                }
                   3360:                /* Create a socket. */
                   3361:                sock = connect_local_xsocket(display_number);
                   3362:                if (sock < 0)
1.51      markus   3363:                        return -1;
1.25      markus   3364:
                   3365:                /* OK, we now have a connection to the display. */
1.51      markus   3366:                return sock;
1.25      markus   3367:        }
1.27      markus   3368:        /*
                   3369:         * Connect to an inet socket.  The DISPLAY value is supposedly
                   3370:         * hostname:d[.s], where hostname may also be numeric IP address.
                   3371:         */
1.145     stevesk  3372:        strlcpy(buf, display, sizeof(buf));
1.25      markus   3373:        cp = strchr(buf, ':');
                   3374:        if (!cp) {
                   3375:                error("Could not find ':' in DISPLAY: %.100s", display);
1.51      markus   3376:                return -1;
1.25      markus   3377:        }
                   3378:        *cp = 0;
1.27      markus   3379:        /* buf now contains the host name.  But first we parse the display number. */
1.248     deraadt  3380:        if (sscanf(cp + 1, "%u", &display_number) != 1) {
1.25      markus   3381:                error("Could not parse display number from DISPLAY: %.100s",
1.148     deraadt  3382:                    display);
1.51      markus   3383:                return -1;
1.25      markus   3384:        }
1.35      markus   3385:
                   3386:        /* Look up the host address */
                   3387:        memset(&hints, 0, sizeof(hints));
                   3388:        hints.ai_family = IPv4or6;
                   3389:        hints.ai_socktype = SOCK_STREAM;
1.248     deraadt  3390:        snprintf(strport, sizeof strport, "%u", 6000 + display_number);
1.35      markus   3391:        if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
1.271     dtucker  3392:                error("%.100s: unknown host. (%s)", buf,
                   3393:                ssh_gai_strerror(gaierr));
1.51      markus   3394:                return -1;
1.25      markus   3395:        }
1.35      markus   3396:        for (ai = aitop; ai; ai = ai->ai_next) {
                   3397:                /* Create a socket. */
1.300     dtucker  3398:                sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1.35      markus   3399:                if (sock < 0) {
1.194     markus   3400:                        debug2("socket: %.100s", strerror(errno));
1.41      markus   3401:                        continue;
                   3402:                }
                   3403:                /* Connect it to the display. */
                   3404:                if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1.248     deraadt  3405:                        debug2("connect %.100s port %u: %.100s", buf,
1.41      markus   3406:                            6000 + display_number, strerror(errno));
                   3407:                        close(sock);
                   3408:                        continue;
                   3409:                }
                   3410:                /* Success */
                   3411:                break;
1.35      markus   3412:        }
                   3413:        freeaddrinfo(aitop);
                   3414:        if (!ai) {
1.248     deraadt  3415:                error("connect %.100s port %u: %.100s", buf, 6000 + display_number,
1.35      markus   3416:                    strerror(errno));
1.51      markus   3417:                return -1;
1.25      markus   3418:        }
1.162     stevesk  3419:        set_nodelay(sock);
1.51      markus   3420:        return sock;
                   3421: }
                   3422:
                   3423: /*
                   3424:  * This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
                   3425:  * the remote channel number.  We should do whatever we want, and respond
                   3426:  * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
                   3427:  */
                   3428:
1.259     stevesk  3429: /* ARGSUSED */
1.51      markus   3430: void
1.154     markus   3431: x11_input_open(int type, u_int32_t seq, void *ctxt)
1.51      markus   3432: {
1.113     markus   3433:        Channel *c = NULL;
                   3434:        int remote_id, sock = 0;
1.51      markus   3435:        char *remote_host;
1.25      markus   3436:
1.113     markus   3437:        debug("Received X11 open request.");
1.51      markus   3438:
1.113     markus   3439:        remote_id = packet_get_int();
1.121     markus   3440:
                   3441:        if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
1.113     markus   3442:                remote_host = packet_get_string(NULL);
1.51      markus   3443:        } else {
                   3444:                remote_host = xstrdup("unknown (remote did not supply name)");
                   3445:        }
1.152     markus   3446:        packet_check_eom();
1.25      markus   3447:
1.51      markus   3448:        /* Obtain a connection to the real X display. */
                   3449:        sock = x11_connect_display();
1.113     markus   3450:        if (sock != -1) {
                   3451:                /* Allocate a channel for this connection. */
                   3452:                c = channel_new("connected x11 socket",
                   3453:                    SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
                   3454:                    remote_host, 1);
1.167     markus   3455:                c->remote_id = remote_id;
                   3456:                c->force_drain = 1;
1.113     markus   3457:        }
1.190     markus   3458:        xfree(remote_host);
1.113     markus   3459:        if (c == NULL) {
1.51      markus   3460:                /* Send refusal to the remote host. */
                   3461:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1.113     markus   3462:                packet_put_int(remote_id);
1.51      markus   3463:        } else {
                   3464:                /* Send a confirmation to the remote host. */
                   3465:                packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1.113     markus   3466:                packet_put_int(remote_id);
                   3467:                packet_put_int(c->self);
1.51      markus   3468:        }
1.113     markus   3469:        packet_send();
1.72      markus   3470: }
                   3471:
                   3472: /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
1.259     stevesk  3473: /* ARGSUSED */
1.72      markus   3474: void
1.154     markus   3475: deny_input_open(int type, u_int32_t seq, void *ctxt)
1.72      markus   3476: {
                   3477:        int rchan = packet_get_int();
1.180     deraadt  3478:
1.143     deraadt  3479:        switch (type) {
1.72      markus   3480:        case SSH_SMSG_AGENT_OPEN:
                   3481:                error("Warning: ssh server tried agent forwarding.");
                   3482:                break;
                   3483:        case SSH_SMSG_X11_OPEN:
                   3484:                error("Warning: ssh server tried X11 forwarding.");
                   3485:                break;
                   3486:        default:
1.154     markus   3487:                error("deny_input_open: type %d", type);
1.72      markus   3488:                break;
                   3489:        }
1.230     stevesk  3490:        error("Warning: this is probably a break-in attempt by a malicious server.");
1.72      markus   3491:        packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   3492:        packet_put_int(rchan);
                   3493:        packet_send();
1.1       deraadt  3494: }
                   3495:
1.27      markus   3496: /*
                   3497:  * Requests forwarding of X11 connections, generates fake authentication
                   3498:  * data, and enables authentication spoofing.
1.121     markus   3499:  * This should be called in the client only.
1.27      markus   3500:  */
1.49      markus   3501: void
1.215     djm      3502: x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
1.311   ! djm      3503:     const char *proto, const char *data, int want_reply)
1.1       deraadt  3504: {
1.77      markus   3505:        u_int data_len = (u_int) strlen(data) / 2;
1.219     djm      3506:        u_int i, value;
1.25      markus   3507:        char *new_data;
                   3508:        int screen_number;
                   3509:        const char *cp;
1.207     avsm     3510:        u_int32_t rnd = 0;
1.25      markus   3511:
1.220     markus   3512:        if (x11_saved_display == NULL)
                   3513:                x11_saved_display = xstrdup(disp);
                   3514:        else if (strcmp(disp, x11_saved_display) != 0) {
1.219     djm      3515:                error("x11_request_forwarding_with_spoofing: different "
                   3516:                    "$DISPLAY already forwarded");
                   3517:                return;
                   3518:        }
                   3519:
1.266     djm      3520:        cp = strchr(disp, ':');
1.25      markus   3521:        if (cp)
                   3522:                cp = strchr(cp, '.');
                   3523:        if (cp)
1.245     deraadt  3524:                screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
1.25      markus   3525:        else
                   3526:                screen_number = 0;
                   3527:
1.219     djm      3528:        if (x11_saved_proto == NULL) {
                   3529:                /* Save protocol name. */
                   3530:                x11_saved_proto = xstrdup(proto);
                   3531:                /*
1.221     djm      3532:                 * Extract real authentication data and generate fake data
1.219     djm      3533:                 * of the same length.
                   3534:                 */
                   3535:                x11_saved_data = xmalloc(data_len);
                   3536:                x11_fake_data = xmalloc(data_len);
                   3537:                for (i = 0; i < data_len; i++) {
                   3538:                        if (sscanf(data + 2 * i, "%2x", &value) != 1)
                   3539:                                fatal("x11_request_forwarding: bad "
                   3540:                                    "authentication data: %.100s", data);
                   3541:                        if (i % 4 == 0)
                   3542:                                rnd = arc4random();
                   3543:                        x11_saved_data[i] = value;
                   3544:                        x11_fake_data[i] = rnd & 0xff;
                   3545:                        rnd >>= 8;
                   3546:                }
                   3547:                x11_saved_data_len = data_len;
                   3548:                x11_fake_data_len = data_len;
1.25      markus   3549:        }
                   3550:
                   3551:        /* Convert the fake data into hex. */
1.219     djm      3552:        new_data = tohex(x11_fake_data, data_len);
1.25      markus   3553:
                   3554:        /* Send the request packet. */
1.51      markus   3555:        if (compat20) {
1.311   ! djm      3556:                channel_request_start(client_session_id, "x11-req", want_reply);
1.51      markus   3557:                packet_put_char(0);     /* XXX bool single connection */
                   3558:        } else {
                   3559:                packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
                   3560:        }
                   3561:        packet_put_cstring(proto);
                   3562:        packet_put_cstring(new_data);
1.25      markus   3563:        packet_put_int(screen_number);
                   3564:        packet_send();
                   3565:        packet_write_wait();
                   3566:        xfree(new_data);
1.1       deraadt  3567: }
                   3568:
1.121     markus   3569:
                   3570: /* -- agent forwarding */
                   3571:
1.1       deraadt  3572: /* Sends a message to the server to request authentication fd forwarding. */
                   3573:
1.49      markus   3574: void
1.142     itojun   3575: auth_request_forwarding(void)
1.1       deraadt  3576: {
1.25      markus   3577:        packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
                   3578:        packet_send();
                   3579:        packet_write_wait();
1.1       deraadt  3580: }