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

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