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

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