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

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