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

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