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

1.354   ! markus      1: /* $OpenBSD: channels.c,v 1.353 2016/09/19 07:52:42 natano 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.336     millert    43: #include <sys/stat.h>
1.234     stevesk    44: #include <sys/ioctl.h>
1.235     stevesk    45: #include <sys/un.h>
1.251     stevesk    46: #include <sys/socket.h>
1.261     stevesk    47: #include <sys/time.h>
1.275     djm        48: #include <sys/queue.h>
1.251     stevesk    49:
                     50: #include <netinet/in.h>
                     51: #include <arpa/inet.h>
1.233     stevesk    52:
1.254     stevesk    53: #include <errno.h>
1.298     dtucker    54: #include <fcntl.h>
1.255     stevesk    55: #include <netdb.h>
1.341     millert    56: #include <stdint.h>
1.263     stevesk    57: #include <stdio.h>
1.262     stevesk    58: #include <stdlib.h>
1.260     stevesk    59: #include <string.h>
1.233     stevesk    60: #include <termios.h>
1.256     stevesk    61: #include <unistd.h>
1.265     deraadt    62: #include <stdarg.h>
1.1       deraadt    63:
1.265     deraadt    64: #include "xmalloc.h"
1.1       deraadt    65: #include "ssh.h"
1.82      markus     66: #include "ssh1.h"
                     67: #include "ssh2.h"
1.354   ! markus     68: #include "ssherr.h"
1.1       deraadt    69: #include "packet.h"
1.82      markus     70: #include "log.h"
                     71: #include "misc.h"
1.265     deraadt    72: #include "buffer.h"
1.14      markus     73: #include "channels.h"
                     74: #include "compat.h"
1.82      markus     75: #include "canohost.h"
1.64      markus     76: #include "key.h"
                     77: #include "authfd.h"
1.147     stevesk    78: #include "pathnames.h"
1.1       deraadt    79:
1.121     markus     80: /* -- channel core */
1.12      markus     81:
1.27      markus     82: /*
                     83:  * Pointer to an array containing all allocated channels.  The array is
                     84:  * dynamically extended as needed.
                     85:  */
1.113     markus     86: static Channel **channels = NULL;
1.1       deraadt    87:
1.27      markus     88: /*
                     89:  * Size of the channel array.  All slots of the array must always be
1.113     markus     90:  * initialized (at least the type field); unused slots set to NULL
1.27      markus     91:  */
1.209     avsm       92: static u_int channels_alloc = 0;
1.1       deraadt    93:
1.27      markus     94: /*
                     95:  * Maximum file descriptor value used in any of the channels.  This is
1.113     markus     96:  * updated in channel_new.
1.27      markus     97:  */
1.84      markus     98: static int channel_max_fd = 0;
1.1       deraadt    99:
                    100:
1.121     markus    101: /* -- tcp forwarding */
1.1       deraadt   102:
1.27      markus    103: /*
                    104:  * Data structure for storing which hosts are permitted for forward requests.
                    105:  * The local sides of any remote forwards are stored in this array to prevent
                    106:  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
                    107:  * network (which might be behind a firewall).
                    108:  */
1.336     millert   109: /* XXX: streamlocal wants a path instead of host:port */
                    110: /*      Overload host_to_connect; we could just make this match Forward */
                    111: /*     XXX - can we use listen_host instead of listen_path? */
1.25      markus    112: typedef struct {
1.41      markus    113:        char *host_to_connect;          /* Connect to 'host'. */
1.336     millert   114:        int port_to_connect;            /* Connect to 'port'. */
1.333     markus    115:        char *listen_host;              /* Remote side should listen address. */
1.336     millert   116:        char *listen_path;              /* Remote side should listen path. */
                    117:        int listen_port;                /* Remote side should listen port. */
1.354   ! markus    118:        Channel *downstream;            /* Downstream mux*/
1.1       deraadt   119: } ForwardPermission;
                    120:
1.257     dtucker   121: /* List of all permitted host/port pairs to connect by the user. */
1.305     djm       122: static ForwardPermission *permitted_opens = NULL;
1.121     markus    123:
1.257     dtucker   124: /* List of all permitted host/port pairs to connect by the admin. */
1.305     djm       125: static ForwardPermission *permitted_adm_opens = NULL;
1.257     dtucker   126:
                    127: /* Number of permitted host/port pairs in the array permitted by the user. */
1.1       deraadt   128: static int num_permitted_opens = 0;
1.257     dtucker   129:
                    130: /* Number of permitted host/port pair in the array permitted by the admin. */
                    131: static int num_adm_permitted_opens = 0;
                    132:
1.314     dtucker   133: /* special-case port number meaning allow any port */
                    134: #define FWD_PERMIT_ANY_PORT    0
                    135:
1.351     dtucker   136: /* special-case wildcard meaning allow any host */
                    137: #define FWD_PERMIT_ANY_HOST    "*"
                    138:
1.27      markus    139: /*
                    140:  * If this is true, all opens are permitted.  This is the case on the server
                    141:  * on which we have to trust the client anyway, and the user could do
                    142:  * anything after logging in anyway.
                    143:  */
1.1       deraadt   144: static int all_opens_permitted = 0;
                    145:
1.121     markus    146:
                    147: /* -- X11 forwarding */
                    148:
                    149: /* Maximum number of fake X11 displays to try. */
                    150: #define MAX_DISPLAYS  1000
                    151:
1.219     djm       152: /* Saved X11 local (client) display. */
                    153: static char *x11_saved_display = NULL;
                    154:
1.121     markus    155: /* Saved X11 authentication protocol name. */
                    156: static char *x11_saved_proto = NULL;
                    157:
                    158: /* Saved X11 authentication data.  This is the real data. */
                    159: static char *x11_saved_data = NULL;
                    160: static u_int x11_saved_data_len = 0;
                    161:
1.347     djm       162: /* Deadline after which all X11 connections are refused */
                    163: static u_int x11_refuse_time;
                    164:
1.121     markus    165: /*
                    166:  * Fake X11 authentication data.  This is what the server will be sending us;
                    167:  * we should replace any occurrences of this by the real data.
                    168:  */
1.240     deraadt   169: static u_char *x11_fake_data = NULL;
1.121     markus    170: static u_int x11_fake_data_len;
                    171:
                    172:
                    173: /* -- agent forwarding */
                    174:
                    175: #define        NUM_SOCKS       10
                    176:
1.82      markus    177: /* AF_UNSPEC or AF_INET or AF_INET6 */
1.135     markus    178: static int IPv4or6 = AF_UNSPEC;
1.1       deraadt   179:
1.121     markus    180: /* helper */
1.127     itojun    181: static void port_open_helper(Channel *c, char *rtype);
1.354   ! markus    182: static const char *channel_rfwd_bind_host(const char *listen_host);
1.103     markus    183:
1.276     djm       184: /* non-blocking connect helpers */
                    185: static int connect_next(struct channel_connect *);
                    186: static void channel_connect_ctx_free(struct channel_connect *);
                    187:
1.121     markus    188: /* -- channel core */
1.41      markus    189:
                    190: Channel *
1.229     markus    191: channel_by_id(int id)
1.41      markus    192: {
                    193:        Channel *c;
1.113     markus    194:
1.209     avsm      195:        if (id < 0 || (u_int)id >= channels_alloc) {
1.229     markus    196:                logit("channel_by_id: %d: bad id", id);
1.41      markus    197:                return NULL;
                    198:        }
1.113     markus    199:        c = channels[id];
                    200:        if (c == NULL) {
1.229     markus    201:                logit("channel_by_id: %d: bad id: channel free", id);
1.41      markus    202:                return NULL;
                    203:        }
                    204:        return c;
1.55      markus    205: }
                    206:
1.354   ! markus    207: Channel *
        !           208: channel_by_remote_id(int remote_id)
        !           209: {
        !           210:        Channel *c;
        !           211:        u_int i;
        !           212:
        !           213:        for (i = 0; i < channels_alloc; i++) {
        !           214:                c = channels[i];
        !           215:                if (c != NULL && c->remote_id == remote_id)
        !           216:                        return c;
        !           217:        }
        !           218:        return NULL;
        !           219: }
        !           220:
1.27      markus    221: /*
1.229     markus    222:  * Returns the channel if it is allowed to receive protocol messages.
                    223:  * Private channels, like listening sockets, may not receive messages.
                    224:  */
                    225: Channel *
                    226: channel_lookup(int id)
                    227: {
                    228:        Channel *c;
                    229:
                    230:        if ((c = channel_by_id(id)) == NULL)
                    231:                return (NULL);
                    232:
1.237     deraadt   233:        switch (c->type) {
1.229     markus    234:        case SSH_CHANNEL_X11_OPEN:
                    235:        case SSH_CHANNEL_LARVAL:
                    236:        case SSH_CHANNEL_CONNECTING:
                    237:        case SSH_CHANNEL_DYNAMIC:
                    238:        case SSH_CHANNEL_OPENING:
                    239:        case SSH_CHANNEL_OPEN:
                    240:        case SSH_CHANNEL_INPUT_DRAINING:
                    241:        case SSH_CHANNEL_OUTPUT_DRAINING:
1.323     dtucker   242:        case SSH_CHANNEL_ABANDONED:
1.354   ! markus    243:        case SSH_CHANNEL_MUX_PROXY:
1.229     markus    244:                return (c);
                    245:        }
                    246:        logit("Non-public channel %d, type %d.", id, c->type);
                    247:        return (NULL);
                    248: }
                    249:
                    250: /*
1.55      markus    251:  * Register filedescriptors for a channel, used when allocating a channel or
1.52      markus    252:  * when the channel consumer/producer is ready, e.g. shell exec'd
1.27      markus    253:  */
1.127     itojun    254: static void
1.71      markus    255: channel_register_fds(Channel *c, int rfd, int wfd, int efd,
1.282     dtucker   256:     int extusage, int nonblock, int is_tty)
1.1       deraadt   257: {
1.25      markus    258:        /* Update the maximum file descriptor value. */
1.352     deraadt   259:        channel_max_fd = MAXIMUM(channel_max_fd, rfd);
                    260:        channel_max_fd = MAXIMUM(channel_max_fd, wfd);
                    261:        channel_max_fd = MAXIMUM(channel_max_fd, efd);
1.84      markus    262:
1.298     dtucker   263:        if (rfd != -1)
                    264:                fcntl(rfd, F_SETFD, FD_CLOEXEC);
                    265:        if (wfd != -1 && wfd != rfd)
                    266:                fcntl(wfd, F_SETFD, FD_CLOEXEC);
                    267:        if (efd != -1 && efd != rfd && efd != wfd)
                    268:                fcntl(efd, F_SETFD, FD_CLOEXEC);
1.55      markus    269:
1.52      markus    270:        c->rfd = rfd;
                    271:        c->wfd = wfd;
                    272:        c->sock = (rfd == wfd) ? rfd : -1;
                    273:        c->efd = efd;
                    274:        c->extended_usage = extusage;
1.71      markus    275:
1.282     dtucker   276:        if ((c->isatty = is_tty) != 0)
1.194     markus    277:                debug2("channel %d: rfd %d isatty", c->self, c->rfd);
1.91      markus    278:
1.71      markus    279:        /* enable nonblocking mode */
                    280:        if (nonblock) {
                    281:                if (rfd != -1)
                    282:                        set_nonblock(rfd);
                    283:                if (wfd != -1)
                    284:                        set_nonblock(wfd);
                    285:                if (efd != -1)
                    286:                        set_nonblock(efd);
                    287:        }
1.52      markus    288: }
                    289:
                    290: /*
                    291:  * Allocate a new channel object and set its type and socket. This will cause
                    292:  * remote_name to be freed.
                    293:  */
1.113     markus    294: Channel *
1.52      markus    295: channel_new(char *ctype, int type, int rfd, int wfd, int efd,
1.178     markus    296:     u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
1.52      markus    297: {
1.209     avsm      298:        int found;
                    299:        u_int i;
1.52      markus    300:        Channel *c;
1.25      markus    301:
                    302:        /* Do initial allocation if this is the first call. */
                    303:        if (channels_alloc == 0) {
                    304:                channels_alloc = 10;
1.242     djm       305:                channels = xcalloc(channels_alloc, sizeof(Channel *));
1.25      markus    306:                for (i = 0; i < channels_alloc; i++)
1.113     markus    307:                        channels[i] = NULL;
1.25      markus    308:        }
                    309:        /* Try to find a free slot where to put the new channel. */
                    310:        for (found = -1, i = 0; i < channels_alloc; i++)
1.113     markus    311:                if (channels[i] == NULL) {
1.25      markus    312:                        /* Found a free slot. */
1.209     avsm      313:                        found = (int)i;
1.25      markus    314:                        break;
                    315:                }
1.209     avsm      316:        if (found < 0) {
1.27      markus    317:                /* There are no free slots.  Take last+1 slot and expand the array.  */
1.25      markus    318:                found = channels_alloc;
1.179     markus    319:                if (channels_alloc > 10000)
                    320:                        fatal("channel_new: internal error: channels_alloc %d "
                    321:                            "too big.", channels_alloc);
1.342     deraadt   322:                channels = xreallocarray(channels, channels_alloc + 10,
1.243     djm       323:                    sizeof(Channel *));
1.195     markus    324:                channels_alloc += 10;
1.70      markus    325:                debug2("channel: expanding %d", channels_alloc);
1.25      markus    326:                for (i = found; i < channels_alloc; i++)
1.113     markus    327:                        channels[i] = NULL;
1.25      markus    328:        }
1.113     markus    329:        /* Initialize and return new channel. */
1.242     djm       330:        c = channels[found] = xcalloc(1, sizeof(Channel));
1.25      markus    331:        buffer_init(&c->input);
                    332:        buffer_init(&c->output);
1.41      markus    333:        buffer_init(&c->extended);
1.293     djm       334:        c->path = NULL;
1.312     djm       335:        c->listening_addr = NULL;
                    336:        c->listening_port = 0;
1.159     markus    337:        c->ostate = CHAN_OUTPUT_OPEN;
                    338:        c->istate = CHAN_INPUT_OPEN;
                    339:        c->flags = 0;
1.281     djm       340:        channel_register_fds(c, rfd, wfd, efd, extusage, nonblock, 0);
1.317     djm       341:        c->notbefore = 0;
1.25      markus    342:        c->self = found;
                    343:        c->type = type;
1.41      markus    344:        c->ctype = ctype;
1.51      markus    345:        c->local_window = window;
                    346:        c->local_window_max = window;
                    347:        c->local_consumed = 0;
                    348:        c->local_maxpacket = maxpack;
1.25      markus    349:        c->remote_id = -1;
1.190     markus    350:        c->remote_name = xstrdup(remote_name);
1.41      markus    351:        c->remote_window = 0;
                    352:        c->remote_maxpacket = 0;
1.133     markus    353:        c->force_drain = 0;
1.149     markus    354:        c->single_connection = 0;
1.131     markus    355:        c->detach_user = NULL;
1.225     djm       356:        c->detach_close = 0;
1.275     djm       357:        c->open_confirm = NULL;
                    358:        c->open_confirm_ctx = NULL;
1.65      markus    359:        c->input_filter = NULL;
1.231     reyk      360:        c->output_filter = NULL;
1.280     djm       361:        c->filter_ctx = NULL;
                    362:        c->filter_cleanup = NULL;
1.302     djm       363:        c->ctl_chan = -1;
                    364:        c->mux_rcb = NULL;
                    365:        c->mux_ctx = NULL;
1.304     djm       366:        c->mux_pause = 0;
1.299     markus    367:        c->delayed = 1;         /* prevent call to channel_post handler */
1.275     djm       368:        TAILQ_INIT(&c->status_confirms);
1.25      markus    369:        debug("channel %d: new [%s]", found, remote_name);
1.113     markus    370:        return c;
1.1       deraadt   371: }
1.52      markus    372:
1.132     markus    373: static int
                    374: channel_find_maxfd(void)
                    375: {
1.209     avsm      376:        u_int i;
                    377:        int max = 0;
1.132     markus    378:        Channel *c;
                    379:
                    380:        for (i = 0; i < channels_alloc; i++) {
                    381:                c = channels[i];
                    382:                if (c != NULL) {
1.352     deraadt   383:                        max = MAXIMUM(max, c->rfd);
                    384:                        max = MAXIMUM(max, c->wfd);
                    385:                        max = MAXIMUM(max, c->efd);
1.132     markus    386:                }
                    387:        }
                    388:        return max;
                    389: }
                    390:
                    391: int
                    392: channel_close_fd(int *fdp)
                    393: {
                    394:        int ret = 0, fd = *fdp;
                    395:
                    396:        if (fd != -1) {
                    397:                ret = close(fd);
                    398:                *fdp = -1;
                    399:                if (fd == channel_max_fd)
                    400:                        channel_max_fd = channel_find_maxfd();
                    401:        }
                    402:        return ret;
                    403: }
                    404:
1.52      markus    405: /* Close all channel fd/socket. */
1.127     itojun    406: static void
1.52      markus    407: channel_close_fds(Channel *c)
                    408: {
1.132     markus    409:        channel_close_fd(&c->sock);
                    410:        channel_close_fd(&c->rfd);
                    411:        channel_close_fd(&c->wfd);
                    412:        channel_close_fd(&c->efd);
1.121     markus    413: }
                    414:
                    415: /* Free the channel and close its fd/socket. */
                    416: void
                    417: channel_free(Channel *c)
                    418: {
                    419:        char *s;
1.209     avsm      420:        u_int i, n;
1.354   ! markus    421:        Channel *other;
1.275     djm       422:        struct channel_confirm *cc;
1.121     markus    423:
1.354   ! markus    424:        for (n = 0, i = 0; i < channels_alloc; i++) {
        !           425:                if ((other = channels[i]) != NULL) {
1.121     markus    426:                        n++;
1.354   ! markus    427:
        !           428:                        /* detach from mux client and prepare for closing */
        !           429:                        if (c->type == SSH_CHANNEL_MUX_CLIENT &&
        !           430:                            other->type == SSH_CHANNEL_MUX_PROXY &&
        !           431:                            other->mux_ctx == c) {
        !           432:                                other->mux_ctx = NULL;
        !           433:                                other->type = SSH_CHANNEL_OPEN;
        !           434:                                other->istate = CHAN_INPUT_CLOSED;
        !           435:                                other->ostate = CHAN_OUTPUT_CLOSED;
        !           436:                        }
        !           437:                }
        !           438:        }
1.209     avsm      439:        debug("channel %d: free: %s, nchannels %u", c->self,
1.121     markus    440:            c->remote_name ? c->remote_name : "???", n);
                    441:
1.354   ! markus    442:        /* XXX more MUX cleanup: remove remote forwardings */
        !           443:        if (c->type == SSH_CHANNEL_MUX_CLIENT) {
        !           444:                for (i = 0; i < (u_int)num_permitted_opens; i++) {
        !           445:                        if (permitted_opens[i].downstream != c)
        !           446:                                continue;
        !           447:                        /* cancel on the server, since mux client is gone */
        !           448:                        debug("channel %d: cleanup remote forward for %s:%u",
        !           449:                            c->self,
        !           450:                            permitted_opens[i].listen_host,
        !           451:                            permitted_opens[i].listen_port);
        !           452:                        packet_start(SSH2_MSG_GLOBAL_REQUEST);
        !           453:                        packet_put_cstring("cancel-tcpip-forward");
        !           454:                        packet_put_char(0);
        !           455:                        packet_put_cstring(channel_rfwd_bind_host(
        !           456:                            permitted_opens[i].listen_host));
        !           457:                        packet_put_int(permitted_opens[i].listen_port);
        !           458:                        packet_send();
        !           459:                        /* unregister */
        !           460:                        permitted_opens[i].listen_port = 0;
        !           461:                        permitted_opens[i].port_to_connect = 0;
        !           462:                        free(permitted_opens[i].host_to_connect);
        !           463:                        permitted_opens[i].host_to_connect = NULL;
        !           464:                        free(permitted_opens[i].listen_host);
        !           465:                        permitted_opens[i].listen_host = NULL;
        !           466:                        permitted_opens[i].listen_path = NULL;
        !           467:                        permitted_opens[i].downstream = NULL;
        !           468:                }
        !           469:        }
        !           470:
1.121     markus    471:        s = channel_open_message();
1.194     markus    472:        debug3("channel %d: status: %s", c->self, s);
1.321     djm       473:        free(s);
1.121     markus    474:
                    475:        if (c->sock != -1)
                    476:                shutdown(c->sock, SHUT_RDWR);
                    477:        channel_close_fds(c);
                    478:        buffer_free(&c->input);
                    479:        buffer_free(&c->output);
                    480:        buffer_free(&c->extended);
1.321     djm       481:        free(c->remote_name);
                    482:        c->remote_name = NULL;
                    483:        free(c->path);
                    484:        c->path = NULL;
                    485:        free(c->listening_addr);
                    486:        c->listening_addr = NULL;
1.275     djm       487:        while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
                    488:                if (cc->abandon_cb != NULL)
                    489:                        cc->abandon_cb(c, cc->ctx);
                    490:                TAILQ_REMOVE(&c->status_confirms, cc, entry);
1.329     tedu      491:                explicit_bzero(cc, sizeof(*cc));
1.321     djm       492:                free(cc);
1.275     djm       493:        }
1.280     djm       494:        if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
                    495:                c->filter_cleanup(c->self, c->filter_ctx);
1.121     markus    496:        channels[c->self] = NULL;
1.321     djm       497:        free(c);
1.121     markus    498: }
                    499:
                    500: void
1.126     markus    501: channel_free_all(void)
1.121     markus    502: {
1.209     avsm      503:        u_int i;
1.121     markus    504:
1.126     markus    505:        for (i = 0; i < channels_alloc; i++)
                    506:                if (channels[i] != NULL)
                    507:                        channel_free(channels[i]);
1.131     markus    508: }
                    509:
1.121     markus    510: /*
                    511:  * Closes the sockets/fds of all channels.  This is used to close extra file
                    512:  * descriptors after a fork.
                    513:  */
                    514: void
1.142     itojun    515: channel_close_all(void)
1.121     markus    516: {
1.209     avsm      517:        u_int i;
1.121     markus    518:
                    519:        for (i = 0; i < channels_alloc; i++)
                    520:                if (channels[i] != NULL)
                    521:                        channel_close_fds(channels[i]);
                    522: }
                    523:
                    524: /*
1.131     markus    525:  * Stop listening to channels.
                    526:  */
                    527: void
                    528: channel_stop_listening(void)
                    529: {
1.209     avsm      530:        u_int i;
1.131     markus    531:        Channel *c;
                    532:
                    533:        for (i = 0; i < channels_alloc; i++) {
                    534:                c = channels[i];
                    535:                if (c != NULL) {
                    536:                        switch (c->type) {
                    537:                        case SSH_CHANNEL_AUTH_SOCKET:
                    538:                        case SSH_CHANNEL_PORT_LISTENER:
                    539:                        case SSH_CHANNEL_RPORT_LISTENER:
                    540:                        case SSH_CHANNEL_X11_LISTENER:
1.336     millert   541:                        case SSH_CHANNEL_UNIX_LISTENER:
                    542:                        case SSH_CHANNEL_RUNIX_LISTENER:
1.132     markus    543:                                channel_close_fd(&c->sock);
1.131     markus    544:                                channel_free(c);
                    545:                                break;
                    546:                        }
                    547:                }
                    548:        }
                    549: }
                    550:
                    551: /*
1.121     markus    552:  * Returns true if no channel has too much buffered data, and false if one or
                    553:  * more channel is overfull.
                    554:  */
                    555: int
1.142     itojun    556: channel_not_very_much_buffered_data(void)
1.121     markus    557: {
                    558:        u_int i;
                    559:        Channel *c;
                    560:
                    561:        for (i = 0; i < channels_alloc; i++) {
                    562:                c = channels[i];
                    563:                if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
1.136     markus    564: #if 0
                    565:                        if (!compat20 &&
                    566:                            buffer_len(&c->input) > packet_get_maxsize()) {
1.185     markus    567:                                debug2("channel %d: big input buffer %d",
1.121     markus    568:                                    c->self, buffer_len(&c->input));
                    569:                                return 0;
                    570:                        }
1.136     markus    571: #endif
1.121     markus    572:                        if (buffer_len(&c->output) > packet_get_maxsize()) {
1.191     markus    573:                                debug2("channel %d: big output buffer %u > %u",
1.136     markus    574:                                    c->self, buffer_len(&c->output),
                    575:                                    packet_get_maxsize());
1.121     markus    576:                                return 0;
                    577:                        }
                    578:                }
                    579:        }
                    580:        return 1;
                    581: }
                    582:
                    583: /* Returns true if any channel is still open. */
                    584: int
1.142     itojun    585: channel_still_open(void)
1.121     markus    586: {
1.209     avsm      587:        u_int i;
1.121     markus    588:        Channel *c;
                    589:
                    590:        for (i = 0; i < channels_alloc; i++) {
                    591:                c = channels[i];
                    592:                if (c == NULL)
                    593:                        continue;
                    594:                switch (c->type) {
                    595:                case SSH_CHANNEL_X11_LISTENER:
                    596:                case SSH_CHANNEL_PORT_LISTENER:
                    597:                case SSH_CHANNEL_RPORT_LISTENER:
1.302     djm       598:                case SSH_CHANNEL_MUX_LISTENER:
1.121     markus    599:                case SSH_CHANNEL_CLOSED:
                    600:                case SSH_CHANNEL_AUTH_SOCKET:
                    601:                case SSH_CHANNEL_DYNAMIC:
                    602:                case SSH_CHANNEL_CONNECTING:
                    603:                case SSH_CHANNEL_ZOMBIE:
1.323     dtucker   604:                case SSH_CHANNEL_ABANDONED:
1.336     millert   605:                case SSH_CHANNEL_UNIX_LISTENER:
                    606:                case SSH_CHANNEL_RUNIX_LISTENER:
1.121     markus    607:                        continue;
                    608:                case SSH_CHANNEL_LARVAL:
                    609:                        if (!compat20)
                    610:                                fatal("cannot happen: SSH_CHANNEL_LARVAL");
                    611:                        continue;
                    612:                case SSH_CHANNEL_OPENING:
                    613:                case SSH_CHANNEL_OPEN:
                    614:                case SSH_CHANNEL_X11_OPEN:
1.302     djm       615:                case SSH_CHANNEL_MUX_CLIENT:
1.354   ! markus    616:                case SSH_CHANNEL_MUX_PROXY:
1.121     markus    617:                        return 1;
                    618:                case SSH_CHANNEL_INPUT_DRAINING:
                    619:                case SSH_CHANNEL_OUTPUT_DRAINING:
                    620:                        if (!compat13)
                    621:                                fatal("cannot happen: OUT_DRAIN");
                    622:                        return 1;
                    623:                default:
                    624:                        fatal("channel_still_open: bad channel type %d", c->type);
                    625:                        /* NOTREACHED */
                    626:                }
                    627:        }
                    628:        return 0;
                    629: }
                    630:
                    631: /* Returns the id of an open channel suitable for keepaliving */
                    632: int
1.142     itojun    633: channel_find_open(void)
1.121     markus    634: {
1.209     avsm      635:        u_int i;
1.121     markus    636:        Channel *c;
                    637:
                    638:        for (i = 0; i < channels_alloc; i++) {
                    639:                c = channels[i];
1.206     djm       640:                if (c == NULL || c->remote_id < 0)
1.121     markus    641:                        continue;
                    642:                switch (c->type) {
                    643:                case SSH_CHANNEL_CLOSED:
                    644:                case SSH_CHANNEL_DYNAMIC:
                    645:                case SSH_CHANNEL_X11_LISTENER:
                    646:                case SSH_CHANNEL_PORT_LISTENER:
                    647:                case SSH_CHANNEL_RPORT_LISTENER:
1.302     djm       648:                case SSH_CHANNEL_MUX_LISTENER:
                    649:                case SSH_CHANNEL_MUX_CLIENT:
1.354   ! markus    650:                case SSH_CHANNEL_MUX_PROXY:
1.121     markus    651:                case SSH_CHANNEL_OPENING:
                    652:                case SSH_CHANNEL_CONNECTING:
                    653:                case SSH_CHANNEL_ZOMBIE:
1.323     dtucker   654:                case SSH_CHANNEL_ABANDONED:
1.336     millert   655:                case SSH_CHANNEL_UNIX_LISTENER:
                    656:                case SSH_CHANNEL_RUNIX_LISTENER:
1.121     markus    657:                        continue;
                    658:                case SSH_CHANNEL_LARVAL:
                    659:                case SSH_CHANNEL_AUTH_SOCKET:
                    660:                case SSH_CHANNEL_OPEN:
                    661:                case SSH_CHANNEL_X11_OPEN:
                    662:                        return i;
                    663:                case SSH_CHANNEL_INPUT_DRAINING:
                    664:                case SSH_CHANNEL_OUTPUT_DRAINING:
                    665:                        if (!compat13)
                    666:                                fatal("cannot happen: OUT_DRAIN");
                    667:                        return i;
                    668:                default:
                    669:                        fatal("channel_find_open: bad channel type %d", c->type);
                    670:                        /* NOTREACHED */
                    671:                }
                    672:        }
                    673:        return -1;
                    674: }
                    675:
                    676: /*
                    677:  * Returns a message describing the currently open forwarded connections,
                    678:  * suitable for sending to the client.  The message contains crlf pairs for
                    679:  * newlines.
                    680:  */
                    681: char *
1.142     itojun    682: channel_open_message(void)
1.121     markus    683: {
                    684:        Buffer buffer;
                    685:        Channel *c;
                    686:        char buf[1024], *cp;
1.209     avsm      687:        u_int i;
1.121     markus    688:
                    689:        buffer_init(&buffer);
                    690:        snprintf(buf, sizeof buf, "The following connections are open:\r\n");
                    691:        buffer_append(&buffer, buf, strlen(buf));
                    692:        for (i = 0; i < channels_alloc; i++) {
                    693:                c = channels[i];
                    694:                if (c == NULL)
                    695:                        continue;
                    696:                switch (c->type) {
                    697:                case SSH_CHANNEL_X11_LISTENER:
                    698:                case SSH_CHANNEL_PORT_LISTENER:
                    699:                case SSH_CHANNEL_RPORT_LISTENER:
                    700:                case SSH_CHANNEL_CLOSED:
                    701:                case SSH_CHANNEL_AUTH_SOCKET:
                    702:                case SSH_CHANNEL_ZOMBIE:
1.323     dtucker   703:                case SSH_CHANNEL_ABANDONED:
1.302     djm       704:                case SSH_CHANNEL_MUX_LISTENER:
1.336     millert   705:                case SSH_CHANNEL_UNIX_LISTENER:
                    706:                case SSH_CHANNEL_RUNIX_LISTENER:
1.121     markus    707:                        continue;
                    708:                case SSH_CHANNEL_LARVAL:
                    709:                case SSH_CHANNEL_OPENING:
                    710:                case SSH_CHANNEL_CONNECTING:
                    711:                case SSH_CHANNEL_DYNAMIC:
                    712:                case SSH_CHANNEL_OPEN:
                    713:                case SSH_CHANNEL_X11_OPEN:
                    714:                case SSH_CHANNEL_INPUT_DRAINING:
                    715:                case SSH_CHANNEL_OUTPUT_DRAINING:
1.354   ! markus    716:                case SSH_CHANNEL_MUX_PROXY:
        !           717:                case SSH_CHANNEL_MUX_CLIENT:
1.204     djm       718:                        snprintf(buf, sizeof buf,
1.348     djm       719:                            "  #%d %.300s (t%d r%d i%u/%d o%u/%d fd %d/%d cc %d)\r\n",
1.121     markus    720:                            c->self, c->remote_name,
                    721:                            c->type, c->remote_id,
                    722:                            c->istate, buffer_len(&c->input),
                    723:                            c->ostate, buffer_len(&c->output),
1.302     djm       724:                            c->rfd, c->wfd, c->ctl_chan);
1.121     markus    725:                        buffer_append(&buffer, buf, strlen(buf));
                    726:                        continue;
                    727:                default:
                    728:                        fatal("channel_open_message: bad channel type %d", c->type);
                    729:                        /* NOTREACHED */
                    730:                }
                    731:        }
                    732:        buffer_append(&buffer, "\0", 1);
1.337     djm       733:        cp = xstrdup((char *)buffer_ptr(&buffer));
1.121     markus    734:        buffer_free(&buffer);
                    735:        return cp;
                    736: }
                    737:
                    738: void
                    739: channel_send_open(int id)
                    740: {
                    741:        Channel *c = channel_lookup(id);
1.180     deraadt   742:
1.121     markus    743:        if (c == NULL) {
1.188     itojun    744:                logit("channel_send_open: %d: bad id", id);
1.121     markus    745:                return;
                    746:        }
1.184     markus    747:        debug2("channel %d: send open", id);
1.121     markus    748:        packet_start(SSH2_MSG_CHANNEL_OPEN);
                    749:        packet_put_cstring(c->ctype);
                    750:        packet_put_int(c->self);
                    751:        packet_put_int(c->local_window);
                    752:        packet_put_int(c->local_maxpacket);
                    753:        packet_send();
                    754: }
                    755:
                    756: void
1.184     markus    757: channel_request_start(int id, char *service, int wantconfirm)
1.121     markus    758: {
1.184     markus    759:        Channel *c = channel_lookup(id);
1.180     deraadt   760:
1.121     markus    761:        if (c == NULL) {
1.188     itojun    762:                logit("channel_request_start: %d: unknown channel id", id);
1.121     markus    763:                return;
                    764:        }
1.204     djm       765:        debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
1.121     markus    766:        packet_start(SSH2_MSG_CHANNEL_REQUEST);
                    767:        packet_put_int(c->remote_id);
                    768:        packet_put_cstring(service);
                    769:        packet_put_char(wantconfirm);
                    770: }
1.241     deraadt   771:
1.121     markus    772: void
1.275     djm       773: channel_register_status_confirm(int id, channel_confirm_cb *cb,
                    774:     channel_confirm_abandon_cb *abandon_cb, void *ctx)
                    775: {
                    776:        struct channel_confirm *cc;
                    777:        Channel *c;
                    778:
                    779:        if ((c = channel_lookup(id)) == NULL)
                    780:                fatal("channel_register_expect: %d: bad id", id);
                    781:
1.327     djm       782:        cc = xcalloc(1, sizeof(*cc));
1.275     djm       783:        cc->cb = cb;
                    784:        cc->abandon_cb = abandon_cb;
                    785:        cc->ctx = ctx;
                    786:        TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
                    787: }
                    788:
                    789: void
1.304     djm       790: channel_register_open_confirm(int id, channel_open_fn *fn, void *ctx)
1.121     markus    791: {
                    792:        Channel *c = channel_lookup(id);
1.180     deraadt   793:
1.121     markus    794:        if (c == NULL) {
1.287     stevesk   795:                logit("channel_register_open_confirm: %d: bad id", id);
1.121     markus    796:                return;
                    797:        }
1.275     djm       798:        c->open_confirm = fn;
                    799:        c->open_confirm_ctx = ctx;
1.121     markus    800: }
1.241     deraadt   801:
1.121     markus    802: void
1.225     djm       803: channel_register_cleanup(int id, channel_callback_fn *fn, int do_close)
1.121     markus    804: {
1.229     markus    805:        Channel *c = channel_by_id(id);
1.180     deraadt   806:
1.121     markus    807:        if (c == NULL) {
1.188     itojun    808:                logit("channel_register_cleanup: %d: bad id", id);
1.121     markus    809:                return;
                    810:        }
1.131     markus    811:        c->detach_user = fn;
1.225     djm       812:        c->detach_close = do_close;
1.121     markus    813: }
1.241     deraadt   814:
1.121     markus    815: void
                    816: channel_cancel_cleanup(int id)
                    817: {
1.229     markus    818:        Channel *c = channel_by_id(id);
1.180     deraadt   819:
1.121     markus    820:        if (c == NULL) {
1.188     itojun    821:                logit("channel_cancel_cleanup: %d: bad id", id);
1.121     markus    822:                return;
1.52      markus    823:        }
1.131     markus    824:        c->detach_user = NULL;
1.225     djm       825:        c->detach_close = 0;
1.121     markus    826: }
1.241     deraadt   827:
1.121     markus    828: void
1.231     reyk      829: channel_register_filter(int id, channel_infilter_fn *ifn,
1.280     djm       830:     channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
1.121     markus    831: {
                    832:        Channel *c = channel_lookup(id);
1.180     deraadt   833:
1.121     markus    834:        if (c == NULL) {
1.188     itojun    835:                logit("channel_register_filter: %d: bad id", id);
1.121     markus    836:                return;
1.52      markus    837:        }
1.231     reyk      838:        c->input_filter = ifn;
                    839:        c->output_filter = ofn;
1.279     djm       840:        c->filter_ctx = ctx;
1.280     djm       841:        c->filter_cleanup = cfn;
1.52      markus    842: }
                    843:
1.49      markus    844: void
1.121     markus    845: channel_set_fds(int id, int rfd, int wfd, int efd,
1.282     dtucker   846:     int extusage, int nonblock, int is_tty, u_int window_max)
1.1       deraadt   847: {
1.121     markus    848:        Channel *c = channel_lookup(id);
1.180     deraadt   849:
1.121     markus    850:        if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
                    851:                fatal("channel_activate for non-larval channel %d.", id);
1.282     dtucker   852:        channel_register_fds(c, rfd, wfd, efd, extusage, nonblock, is_tty);
1.121     markus    853:        c->type = SSH_CHANNEL_OPEN;
1.168     markus    854:        c->local_window = c->local_window_max = window_max;
1.121     markus    855:        packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
                    856:        packet_put_int(c->remote_id);
                    857:        packet_put_int(c->local_window);
                    858:        packet_send();
1.1       deraadt   859: }
                    860:
1.27      markus    861: /*
1.41      markus    862:  * 'channel_pre*' are called just before select() to add any bits relevant to
                    863:  * channels in the select bitmasks.
                    864:  */
                    865: /*
                    866:  * 'channel_post*': perform any appropriate operations for channels which
                    867:  * have events pending.
1.27      markus    868:  */
1.237     deraadt   869: typedef void chan_fn(Channel *c, fd_set *readset, fd_set *writeset);
1.41      markus    870: chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
                    871: chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
                    872:
1.259     stevesk   873: /* ARGSUSED */
1.127     itojun    874: static void
1.237     deraadt   875: channel_pre_listener(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    876: {
                    877:        FD_SET(c->sock, readset);
                    878: }
                    879:
1.259     stevesk   880: /* ARGSUSED */
1.127     itojun    881: static void
1.237     deraadt   882: channel_pre_connecting(Channel *c, fd_set *readset, fd_set *writeset)
1.75      markus    883: {
                    884:        debug3("channel %d: waiting for connection", c->self);
                    885:        FD_SET(c->sock, writeset);
                    886: }
                    887:
1.127     itojun    888: static void
1.237     deraadt   889: channel_pre_open_13(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    890: {
                    891:        if (buffer_len(&c->input) < packet_get_maxsize())
                    892:                FD_SET(c->sock, readset);
                    893:        if (buffer_len(&c->output) > 0)
                    894:                FD_SET(c->sock, writeset);
                    895: }
1.1       deraadt   896:
1.127     itojun    897: static void
1.237     deraadt   898: channel_pre_open(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    899: {
1.157     markus    900:        u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
1.41      markus    901:
1.44      markus    902:        if (c->istate == CHAN_INPUT_OPEN &&
1.157     markus    903:            limit > 0 &&
1.250     djm       904:            buffer_len(&c->input) < limit &&
                    905:            buffer_check_alloc(&c->input, CHAN_RBUF))
1.44      markus    906:                FD_SET(c->rfd, readset);
                    907:        if (c->ostate == CHAN_OUTPUT_OPEN ||
                    908:            c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
                    909:                if (buffer_len(&c->output) > 0) {
                    910:                        FD_SET(c->wfd, writeset);
                    911:                } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1.172     markus    912:                        if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
1.223     djm       913:                                debug2("channel %d: obuf_empty delayed efd %d/(%d)",
                    914:                                    c->self, c->efd, buffer_len(&c->extended));
1.172     markus    915:                        else
                    916:                                chan_obuf_empty(c);
1.44      markus    917:                }
                    918:        }
                    919:        /** XXX check close conditions, too */
1.277     markus    920:        if (compat20 && c->efd != -1 &&
                    921:            !(c->istate == CHAN_INPUT_CLOSED && c->ostate == CHAN_OUTPUT_CLOSED)) {
1.44      markus    922:                if (c->extended_usage == CHAN_EXTENDED_WRITE &&
                    923:                    buffer_len(&c->extended) > 0)
                    924:                        FD_SET(c->efd, writeset);
1.306     djm       925:                else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
                    926:                    (c->extended_usage == CHAN_EXTENDED_READ ||
                    927:                    c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1.44      markus    928:                    buffer_len(&c->extended) < c->remote_window)
                    929:                        FD_SET(c->efd, readset);
                    930:        }
1.204     djm       931:        /* XXX: What about efd? races? */
1.44      markus    932: }
                    933:
1.259     stevesk   934: /* ARGSUSED */
1.127     itojun    935: static void
1.237     deraadt   936: channel_pre_input_draining(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    937: {
                    938:        if (buffer_len(&c->input) == 0) {
                    939:                packet_start(SSH_MSG_CHANNEL_CLOSE);
                    940:                packet_put_int(c->remote_id);
                    941:                packet_send();
                    942:                c->type = SSH_CHANNEL_CLOSED;
1.194     markus    943:                debug2("channel %d: closing after input drain.", c->self);
1.41      markus    944:        }
                    945: }
                    946:
1.259     stevesk   947: /* ARGSUSED */
1.127     itojun    948: static void
1.237     deraadt   949: channel_pre_output_draining(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    950: {
                    951:        if (buffer_len(&c->output) == 0)
1.113     markus    952:                chan_mark_dead(c);
1.49      markus    953:        else
1.41      markus    954:                FD_SET(c->sock, writeset);
                    955: }
                    956:
                    957: /*
                    958:  * This is a special state for X11 authentication spoofing.  An opened X11
                    959:  * connection (when authentication spoofing is being done) remains in this
                    960:  * state until the first packet has been completely read.  The authentication
                    961:  * data in that packet is then substituted by the real data if it matches the
                    962:  * fake data, and the channel is put into normal mode.
1.51      markus    963:  * XXX All this happens at the client side.
1.121     markus    964:  * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
1.41      markus    965:  */
1.127     itojun    966: static int
1.121     markus    967: x11_open_helper(Buffer *b)
1.1       deraadt   968: {
1.77      markus    969:        u_char *ucp;
                    970:        u_int proto_len, data_len;
1.25      markus    971:
1.347     djm       972:        /* Is this being called after the refusal deadline? */
                    973:        if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
                    974:                verbose("Rejected X11 connection after ForwardX11Timeout "
                    975:                    "expired");
                    976:                return -1;
                    977:        }
                    978:
1.41      markus    979:        /* Check if the fixed size part of the packet is in buffer. */
1.121     markus    980:        if (buffer_len(b) < 12)
1.41      markus    981:                return 0;
                    982:
                    983:        /* Parse the lengths of variable-length fields. */
1.155     stevesk   984:        ucp = buffer_ptr(b);
1.41      markus    985:        if (ucp[0] == 0x42) {   /* Byte order MSB first. */
                    986:                proto_len = 256 * ucp[6] + ucp[7];
                    987:                data_len = 256 * ucp[8] + ucp[9];
                    988:        } else if (ucp[0] == 0x6c) {    /* Byte order LSB first. */
                    989:                proto_len = ucp[6] + 256 * ucp[7];
                    990:                data_len = ucp[8] + 256 * ucp[9];
                    991:        } else {
1.194     markus    992:                debug2("Initial X11 packet contains bad byte order byte: 0x%x",
1.148     deraadt   993:                    ucp[0]);
1.41      markus    994:                return -1;
                    995:        }
                    996:
                    997:        /* Check if the whole packet is in buffer. */
1.121     markus    998:        if (buffer_len(b) <
1.41      markus    999:            12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
                   1000:                return 0;
                   1001:
                   1002:        /* Check if authentication protocol matches. */
                   1003:        if (proto_len != strlen(x11_saved_proto) ||
                   1004:            memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
1.194     markus   1005:                debug2("X11 connection uses different authentication protocol.");
1.41      markus   1006:                return -1;
                   1007:        }
                   1008:        /* Check if authentication data matches our fake data. */
                   1009:        if (data_len != x11_fake_data_len ||
1.308     djm      1010:            timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
1.41      markus   1011:                x11_fake_data, x11_fake_data_len) != 0) {
1.194     markus   1012:                debug2("X11 auth data does not match fake data.");
1.41      markus   1013:                return -1;
                   1014:        }
                   1015:        /* Check fake data length */
                   1016:        if (x11_fake_data_len != x11_saved_data_len) {
                   1017:                error("X11 fake_data_len %d != saved_data_len %d",
                   1018:                    x11_fake_data_len, x11_saved_data_len);
                   1019:                return -1;
                   1020:        }
                   1021:        /*
                   1022:         * Received authentication protocol and data match
                   1023:         * our fake data. Substitute the fake data with real
                   1024:         * data.
                   1025:         */
                   1026:        memcpy(ucp + 12 + ((proto_len + 3) & ~3),
                   1027:            x11_saved_data, x11_saved_data_len);
                   1028:        return 1;
                   1029: }
                   1030:
1.127     itojun   1031: static void
1.237     deraadt  1032: channel_pre_x11_open_13(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1033: {
1.121     markus   1034:        int ret = x11_open_helper(&c->output);
1.180     deraadt  1035:
1.41      markus   1036:        if (ret == 1) {
                   1037:                /* Start normal processing for the channel. */
                   1038:                c->type = SSH_CHANNEL_OPEN;
1.47      markus   1039:                channel_pre_open_13(c, readset, writeset);
1.41      markus   1040:        } else if (ret == -1) {
                   1041:                /*
                   1042:                 * We have received an X11 connection that has bad
                   1043:                 * authentication information.
                   1044:                 */
1.188     itojun   1045:                logit("X11 connection rejected because of wrong authentication.");
1.41      markus   1046:                buffer_clear(&c->input);
                   1047:                buffer_clear(&c->output);
1.132     markus   1048:                channel_close_fd(&c->sock);
1.41      markus   1049:                c->sock = -1;
                   1050:                c->type = SSH_CHANNEL_CLOSED;
                   1051:                packet_start(SSH_MSG_CHANNEL_CLOSE);
                   1052:                packet_put_int(c->remote_id);
                   1053:                packet_send();
                   1054:        }
                   1055: }
1.25      markus   1056:
1.127     itojun   1057: static void
1.237     deraadt  1058: channel_pre_x11_open(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1059: {
1.121     markus   1060:        int ret = x11_open_helper(&c->output);
1.133     markus   1061:
                   1062:        /* c->force_drain = 1; */
                   1063:
1.41      markus   1064:        if (ret == 1) {
                   1065:                c->type = SSH_CHANNEL_OPEN;
1.157     markus   1066:                channel_pre_open(c, readset, writeset);
1.41      markus   1067:        } else if (ret == -1) {
1.188     itojun   1068:                logit("X11 connection rejected because of wrong authentication.");
1.194     markus   1069:                debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
1.156     markus   1070:                chan_read_failed(c);
                   1071:                buffer_clear(&c->input);
                   1072:                chan_ibuf_empty(c);
                   1073:                buffer_clear(&c->output);
                   1074:                /* for proto v1, the peer will send an IEOF */
                   1075:                if (compat20)
                   1076:                        chan_write_failed(c);
                   1077:                else
                   1078:                        c->type = SSH_CHANNEL_OPEN;
1.194     markus   1079:                debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
1.41      markus   1080:        }
                   1081: }
1.25      markus   1082:
1.302     djm      1083: static void
                   1084: channel_pre_mux_client(Channel *c, fd_set *readset, fd_set *writeset)
                   1085: {
1.304     djm      1086:        if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
1.302     djm      1087:            buffer_check_alloc(&c->input, CHAN_RBUF))
                   1088:                FD_SET(c->rfd, readset);
                   1089:        if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
                   1090:                /* clear buffer immediately (discard any partial packet) */
                   1091:                buffer_clear(&c->input);
                   1092:                chan_ibuf_empty(c);
                   1093:                /* Start output drain. XXX just kill chan? */
                   1094:                chan_rcvd_oclose(c);
                   1095:        }
                   1096:        if (c->ostate == CHAN_OUTPUT_OPEN ||
                   1097:            c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
                   1098:                if (buffer_len(&c->output) > 0)
                   1099:                        FD_SET(c->wfd, writeset);
                   1100:                else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
                   1101:                        chan_obuf_empty(c);
                   1102:        }
                   1103: }
                   1104:
1.104     markus   1105: /* try to decode a socks4 header */
1.259     stevesk  1106: /* ARGSUSED */
1.127     itojun   1107: static int
1.237     deraadt  1108: channel_decode_socks4(Channel *c, fd_set *readset, fd_set *writeset)
1.103     markus   1109: {
1.181     markus   1110:        char *p, *host;
1.292     djm      1111:        u_int len, have, i, found, need;
1.148     deraadt  1112:        char username[256];
1.103     markus   1113:        struct {
                   1114:                u_int8_t version;
                   1115:                u_int8_t command;
                   1116:                u_int16_t dest_port;
1.104     markus   1117:                struct in_addr dest_addr;
1.103     markus   1118:        } s4_req, s4_rsp;
                   1119:
1.104     markus   1120:        debug2("channel %d: decode socks4", c->self);
1.109     markus   1121:
                   1122:        have = buffer_len(&c->input);
                   1123:        len = sizeof(s4_req);
                   1124:        if (have < len)
                   1125:                return 0;
1.337     djm      1126:        p = (char *)buffer_ptr(&c->input);
1.292     djm      1127:
                   1128:        need = 1;
                   1129:        /* SOCKS4A uses an invalid IP address 0.0.0.x */
                   1130:        if (p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] != 0) {
                   1131:                debug2("channel %d: socks4a request", c->self);
                   1132:                /* ... and needs an extra string (the hostname) */
                   1133:                need = 2;
                   1134:        }
                   1135:        /* Check for terminating NUL on the string(s) */
1.109     markus   1136:        for (found = 0, i = len; i < have; i++) {
                   1137:                if (p[i] == '\0') {
1.292     djm      1138:                        found++;
                   1139:                        if (found == need)
                   1140:                                break;
1.109     markus   1141:                }
                   1142:                if (i > 1024) {
                   1143:                        /* the peer is probably sending garbage */
                   1144:                        debug("channel %d: decode socks4: too long",
                   1145:                            c->self);
                   1146:                        return -1;
                   1147:                }
                   1148:        }
1.292     djm      1149:        if (found < need)
1.109     markus   1150:                return 0;
1.103     markus   1151:        buffer_get(&c->input, (char *)&s4_req.version, 1);
                   1152:        buffer_get(&c->input, (char *)&s4_req.command, 1);
                   1153:        buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
1.104     markus   1154:        buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
1.109     markus   1155:        have = buffer_len(&c->input);
1.337     djm      1156:        p = (char *)buffer_ptr(&c->input);
1.331     djm      1157:        if (memchr(p, '\0', have) == NULL)
                   1158:                fatal("channel %d: decode socks4: user not nul terminated",
                   1159:                    c->self);
1.103     markus   1160:        len = strlen(p);
1.106     markus   1161:        debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1.292     djm      1162:        len++;                                  /* trailing '\0' */
1.103     markus   1163:        if (len > have)
1.104     markus   1164:                fatal("channel %d: decode socks4: len %d > have %d",
1.103     markus   1165:                    c->self, len, have);
                   1166:        strlcpy(username, p, sizeof(username));
                   1167:        buffer_consume(&c->input, len);
                   1168:
1.321     djm      1169:        free(c->path);
                   1170:        c->path = NULL;
1.292     djm      1171:        if (need == 1) {                        /* SOCKS4: one string */
                   1172:                host = inet_ntoa(s4_req.dest_addr);
1.293     djm      1173:                c->path = xstrdup(host);
1.292     djm      1174:        } else {                                /* SOCKS4A: two strings */
                   1175:                have = buffer_len(&c->input);
1.337     djm      1176:                p = (char *)buffer_ptr(&c->input);
1.292     djm      1177:                len = strlen(p);
                   1178:                debug2("channel %d: decode socks4a: host %s/%d",
                   1179:                    c->self, p, len);
                   1180:                len++;                          /* trailing '\0' */
                   1181:                if (len > have)
                   1182:                        fatal("channel %d: decode socks4a: len %d > have %d",
                   1183:                            c->self, len, have);
1.293     djm      1184:                if (len > NI_MAXHOST) {
1.292     djm      1185:                        error("channel %d: hostname \"%.100s\" too long",
                   1186:                            c->self, p);
                   1187:                        return -1;
                   1188:                }
1.293     djm      1189:                c->path = xstrdup(p);
1.292     djm      1190:                buffer_consume(&c->input, len);
                   1191:        }
1.103     markus   1192:        c->host_port = ntohs(s4_req.dest_port);
1.148     deraadt  1193:
1.194     markus   1194:        debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1.292     djm      1195:            c->self, c->path, c->host_port, s4_req.command);
1.103     markus   1196:
1.104     markus   1197:        if (s4_req.command != 1) {
1.292     djm      1198:                debug("channel %d: cannot handle: %s cn %d",
                   1199:                    c->self, need == 1 ? "SOCKS4" : "SOCKS4A", s4_req.command);
1.104     markus   1200:                return -1;
1.103     markus   1201:        }
1.104     markus   1202:        s4_rsp.version = 0;                     /* vn: 0 for reply */
                   1203:        s4_rsp.command = 90;                    /* cd: req granted */
1.103     markus   1204:        s4_rsp.dest_port = 0;                   /* ignored */
1.104     markus   1205:        s4_rsp.dest_addr.s_addr = INADDR_ANY;   /* ignored */
1.246     deraadt  1206:        buffer_append(&c->output, &s4_rsp, sizeof(s4_rsp));
1.104     markus   1207:        return 1;
                   1208: }
                   1209:
1.193     markus   1210: /* try to decode a socks5 header */
                   1211: #define SSH_SOCKS5_AUTHDONE    0x1000
                   1212: #define SSH_SOCKS5_NOAUTH      0x00
                   1213: #define SSH_SOCKS5_IPV4                0x01
                   1214: #define SSH_SOCKS5_DOMAIN      0x03
                   1215: #define SSH_SOCKS5_IPV6                0x04
                   1216: #define SSH_SOCKS5_CONNECT     0x01
                   1217: #define SSH_SOCKS5_SUCCESS     0x00
                   1218:
1.259     stevesk  1219: /* ARGSUSED */
1.193     markus   1220: static int
1.237     deraadt  1221: channel_decode_socks5(Channel *c, fd_set *readset, fd_set *writeset)
1.193     markus   1222: {
                   1223:        struct {
                   1224:                u_int8_t version;
                   1225:                u_int8_t command;
                   1226:                u_int8_t reserved;
                   1227:                u_int8_t atyp;
                   1228:        } s5_req, s5_rsp;
                   1229:        u_int16_t dest_port;
1.324     djm      1230:        char dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
                   1231:        u_char *p;
1.252     djm      1232:        u_int have, need, i, found, nmethods, addrlen, af;
1.193     markus   1233:
                   1234:        debug2("channel %d: decode socks5", c->self);
                   1235:        p = buffer_ptr(&c->input);
                   1236:        if (p[0] != 0x05)
                   1237:                return -1;
                   1238:        have = buffer_len(&c->input);
                   1239:        if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
                   1240:                /* format: ver | nmethods | methods */
1.198     djm      1241:                if (have < 2)
1.193     markus   1242:                        return 0;
                   1243:                nmethods = p[1];
                   1244:                if (have < nmethods + 2)
                   1245:                        return 0;
                   1246:                /* look for method: "NO AUTHENTICATION REQUIRED" */
1.268     stevesk  1247:                for (found = 0, i = 2; i < nmethods + 2; i++) {
1.264     stevesk  1248:                        if (p[i] == SSH_SOCKS5_NOAUTH) {
1.193     markus   1249:                                found = 1;
                   1250:                                break;
                   1251:                        }
                   1252:                }
                   1253:                if (!found) {
                   1254:                        debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
                   1255:                            c->self);
                   1256:                        return -1;
                   1257:                }
                   1258:                buffer_consume(&c->input, nmethods + 2);
                   1259:                buffer_put_char(&c->output, 0x05);              /* version */
                   1260:                buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
                   1261:                FD_SET(c->sock, writeset);
                   1262:                c->flags |= SSH_SOCKS5_AUTHDONE;
                   1263:                debug2("channel %d: socks5 auth done", c->self);
                   1264:                return 0;                               /* need more */
                   1265:        }
                   1266:        debug2("channel %d: socks5 post auth", c->self);
                   1267:        if (have < sizeof(s5_req)+1)
                   1268:                return 0;                       /* need more */
1.247     deraadt  1269:        memcpy(&s5_req, p, sizeof(s5_req));
1.193     markus   1270:        if (s5_req.version != 0x05 ||
                   1271:            s5_req.command != SSH_SOCKS5_CONNECT ||
                   1272:            s5_req.reserved != 0x00) {
1.194     markus   1273:                debug2("channel %d: only socks5 connect supported", c->self);
1.193     markus   1274:                return -1;
                   1275:        }
1.213     deraadt  1276:        switch (s5_req.atyp){
1.193     markus   1277:        case SSH_SOCKS5_IPV4:
                   1278:                addrlen = 4;
                   1279:                af = AF_INET;
                   1280:                break;
                   1281:        case SSH_SOCKS5_DOMAIN:
                   1282:                addrlen = p[sizeof(s5_req)];
                   1283:                af = -1;
                   1284:                break;
                   1285:        case SSH_SOCKS5_IPV6:
                   1286:                addrlen = 16;
                   1287:                af = AF_INET6;
                   1288:                break;
                   1289:        default:
1.194     markus   1290:                debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1.193     markus   1291:                return -1;
                   1292:        }
1.252     djm      1293:        need = sizeof(s5_req) + addrlen + 2;
                   1294:        if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
                   1295:                need++;
                   1296:        if (have < need)
1.193     markus   1297:                return 0;
                   1298:        buffer_consume(&c->input, sizeof(s5_req));
                   1299:        if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
                   1300:                buffer_consume(&c->input, 1);    /* host string length */
1.324     djm      1301:        buffer_get(&c->input, &dest_addr, addrlen);
1.193     markus   1302:        buffer_get(&c->input, (char *)&dest_port, 2);
                   1303:        dest_addr[addrlen] = '\0';
1.321     djm      1304:        free(c->path);
                   1305:        c->path = NULL;
1.293     djm      1306:        if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1.294     djm      1307:                if (addrlen >= NI_MAXHOST) {
1.293     djm      1308:                        error("channel %d: dynamic request: socks5 hostname "
                   1309:                            "\"%.100s\" too long", c->self, dest_addr);
                   1310:                        return -1;
                   1311:                }
                   1312:                c->path = xstrdup(dest_addr);
                   1313:        } else {
                   1314:                if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
                   1315:                        return -1;
                   1316:                c->path = xstrdup(ntop);
                   1317:        }
1.193     markus   1318:        c->host_port = ntohs(dest_port);
1.198     djm      1319:
1.194     markus   1320:        debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1.193     markus   1321:            c->self, c->path, c->host_port, s5_req.command);
                   1322:
                   1323:        s5_rsp.version = 0x05;
                   1324:        s5_rsp.command = SSH_SOCKS5_SUCCESS;
                   1325:        s5_rsp.reserved = 0;                    /* ignored */
                   1326:        s5_rsp.atyp = SSH_SOCKS5_IPV4;
                   1327:        dest_port = 0;                          /* ignored */
                   1328:
1.246     deraadt  1329:        buffer_append(&c->output, &s5_rsp, sizeof(s5_rsp));
1.325     djm      1330:        buffer_put_int(&c->output, ntohl(INADDR_ANY)); /* bind address */
1.246     deraadt  1331:        buffer_append(&c->output, &dest_port, sizeof(dest_port));
1.193     markus   1332:        return 1;
1.301     dtucker  1333: }
                   1334:
                   1335: Channel *
1.302     djm      1336: channel_connect_stdio_fwd(const char *host_to_connect, u_short port_to_connect,
                   1337:     int in, int out)
1.301     dtucker  1338: {
                   1339:        Channel *c;
                   1340:
                   1341:        debug("channel_connect_stdio_fwd %s:%d", host_to_connect,
                   1342:            port_to_connect);
                   1343:
                   1344:        c = channel_new("stdio-forward", SSH_CHANNEL_OPENING, in, out,
                   1345:            -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
                   1346:            0, "stdio-forward", /*nonblock*/0);
                   1347:
                   1348:        c->path = xstrdup(host_to_connect);
                   1349:        c->host_port = port_to_connect;
                   1350:        c->listening_port = 0;
                   1351:        c->force_drain = 1;
                   1352:
                   1353:        channel_register_fds(c, in, out, -1, 0, 1, 0);
                   1354:        port_open_helper(c, "direct-tcpip");
                   1355:
                   1356:        return c;
1.193     markus   1357: }
                   1358:
1.104     markus   1359: /* dynamic port forwarding */
1.127     itojun   1360: static void
1.237     deraadt  1361: channel_pre_dynamic(Channel *c, fd_set *readset, fd_set *writeset)
1.104     markus   1362: {
                   1363:        u_char *p;
1.217     djm      1364:        u_int have;
                   1365:        int ret;
1.103     markus   1366:
1.104     markus   1367:        have = buffer_len(&c->input);
                   1368:        debug2("channel %d: pre_dynamic: have %d", c->self, have);
1.105     markus   1369:        /* buffer_dump(&c->input); */
1.104     markus   1370:        /* check if the fixed size part of the packet is in buffer. */
1.193     markus   1371:        if (have < 3) {
1.104     markus   1372:                /* need more */
                   1373:                FD_SET(c->sock, readset);
                   1374:                return;
                   1375:        }
                   1376:        /* try to guess the protocol */
                   1377:        p = buffer_ptr(&c->input);
                   1378:        switch (p[0]) {
                   1379:        case 0x04:
                   1380:                ret = channel_decode_socks4(c, readset, writeset);
1.193     markus   1381:                break;
                   1382:        case 0x05:
                   1383:                ret = channel_decode_socks5(c, readset, writeset);
1.104     markus   1384:                break;
                   1385:        default:
                   1386:                ret = -1;
                   1387:                break;
                   1388:        }
                   1389:        if (ret < 0) {
1.113     markus   1390:                chan_mark_dead(c);
1.104     markus   1391:        } else if (ret == 0) {
                   1392:                debug2("channel %d: pre_dynamic: need more", c->self);
                   1393:                /* need more */
                   1394:                FD_SET(c->sock, readset);
                   1395:        } else {
                   1396:                /* switch to the next state */
                   1397:                c->type = SSH_CHANNEL_OPENING;
                   1398:                port_open_helper(c, "direct-tcpip");
                   1399:        }
1.103     markus   1400: }
                   1401:
1.41      markus   1402: /* This is our fake X11 server socket. */
1.259     stevesk  1403: /* ARGSUSED */
1.127     itojun   1404: static void
1.237     deraadt  1405: channel_post_x11_listener(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1406: {
1.113     markus   1407:        Channel *nc;
1.285     djm      1408:        struct sockaddr_storage addr;
1.320     markus   1409:        int newsock, oerrno;
1.41      markus   1410:        socklen_t addrlen;
1.85      markus   1411:        char buf[16384], *remote_ipaddr;
1.51      markus   1412:        int remote_port;
1.25      markus   1413:
1.41      markus   1414:        if (FD_ISSET(c->sock, readset)) {
                   1415:                debug("X11 connection requested.");
                   1416:                addrlen = sizeof(addr);
1.285     djm      1417:                newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1.149     markus   1418:                if (c->single_connection) {
1.320     markus   1419:                        oerrno = errno;
1.194     markus   1420:                        debug2("single_connection: closing X11 listener.");
1.149     markus   1421:                        channel_close_fd(&c->sock);
                   1422:                        chan_mark_dead(c);
1.320     markus   1423:                        errno = oerrno;
1.149     markus   1424:                }
1.41      markus   1425:                if (newsock < 0) {
1.320     markus   1426:                        if (errno != EINTR && errno != EWOULDBLOCK &&
                   1427:                            errno != ECONNABORTED)
                   1428:                                error("accept: %.100s", strerror(errno));
1.317     djm      1429:                        if (errno == EMFILE || errno == ENFILE)
1.322     dtucker  1430:                                c->notbefore = monotime() + 1;
1.41      markus   1431:                        return;
                   1432:                }
1.162     stevesk  1433:                set_nodelay(newsock);
1.85      markus   1434:                remote_ipaddr = get_peer_ipaddr(newsock);
1.51      markus   1435:                remote_port = get_peer_port(newsock);
1.41      markus   1436:                snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1.85      markus   1437:                    remote_ipaddr, remote_port);
1.51      markus   1438:
1.113     markus   1439:                nc = channel_new("accepted x11 socket",
1.51      markus   1440:                    SSH_CHANNEL_OPENING, newsock, newsock, -1,
1.190     markus   1441:                    c->local_window_max, c->local_maxpacket, 0, buf, 1);
1.51      markus   1442:                if (compat20) {
                   1443:                        packet_start(SSH2_MSG_CHANNEL_OPEN);
                   1444:                        packet_put_cstring("x11");
1.113     markus   1445:                        packet_put_int(nc->self);
1.149     markus   1446:                        packet_put_int(nc->local_window_max);
                   1447:                        packet_put_int(nc->local_maxpacket);
1.85      markus   1448:                        /* originator ipaddr and port */
                   1449:                        packet_put_cstring(remote_ipaddr);
1.57      markus   1450:                        if (datafellows & SSH_BUG_X11FWD) {
1.194     markus   1451:                                debug2("ssh2 x11 bug compat mode");
1.57      markus   1452:                        } else {
                   1453:                                packet_put_int(remote_port);
                   1454:                        }
1.51      markus   1455:                        packet_send();
                   1456:                } else {
                   1457:                        packet_start(SSH_SMSG_X11_OPEN);
1.113     markus   1458:                        packet_put_int(nc->self);
1.121     markus   1459:                        if (packet_get_protocol_flags() &
                   1460:                            SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1.125     markus   1461:                                packet_put_cstring(buf);
1.51      markus   1462:                        packet_send();
                   1463:                }
1.321     djm      1464:                free(remote_ipaddr);
1.41      markus   1465:        }
                   1466: }
1.25      markus   1467:
1.127     itojun   1468: static void
1.103     markus   1469: port_open_helper(Channel *c, char *rtype)
                   1470: {
                   1471:        char buf[1024];
1.328     djm      1472:        char *local_ipaddr = get_local_ipaddr(c->sock);
1.350     djm      1473:        int local_port = c->sock == -1 ? 65536 : get_local_port(c->sock);
1.103     markus   1474:        char *remote_ipaddr = get_peer_ipaddr(c->sock);
1.216     markus   1475:        int remote_port = get_peer_port(c->sock);
1.303     djm      1476:
                   1477:        if (remote_port == -1) {
                   1478:                /* Fake addr/port to appease peers that validate it (Tectia) */
1.321     djm      1479:                free(remote_ipaddr);
1.303     djm      1480:                remote_ipaddr = xstrdup("127.0.0.1");
                   1481:                remote_port = 65535;
                   1482:        }
1.103     markus   1483:
                   1484:        snprintf(buf, sizeof buf,
                   1485:            "%s: listening port %d for %.100s port %d, "
1.328     djm      1486:            "connect from %.200s port %d to %.100s port %d",
1.103     markus   1487:            rtype, c->listening_port, c->path, c->host_port,
1.328     djm      1488:            remote_ipaddr, remote_port, local_ipaddr, local_port);
1.103     markus   1489:
1.321     djm      1490:        free(c->remote_name);
1.103     markus   1491:        c->remote_name = xstrdup(buf);
                   1492:
                   1493:        if (compat20) {
                   1494:                packet_start(SSH2_MSG_CHANNEL_OPEN);
                   1495:                packet_put_cstring(rtype);
                   1496:                packet_put_int(c->self);
                   1497:                packet_put_int(c->local_window_max);
                   1498:                packet_put_int(c->local_maxpacket);
1.336     millert  1499:                if (strcmp(rtype, "direct-tcpip") == 0) {
1.103     markus   1500:                        /* target host, port */
                   1501:                        packet_put_cstring(c->path);
                   1502:                        packet_put_int(c->host_port);
1.336     millert  1503:                } else if (strcmp(rtype, "direct-streamlocal@openssh.com") == 0) {
                   1504:                        /* target path */
                   1505:                        packet_put_cstring(c->path);
                   1506:                } else if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
                   1507:                        /* listen path */
                   1508:                        packet_put_cstring(c->path);
1.103     markus   1509:                } else {
                   1510:                        /* listen address, port */
                   1511:                        packet_put_cstring(c->path);
1.328     djm      1512:                        packet_put_int(local_port);
1.103     markus   1513:                }
1.336     millert  1514:                if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
                   1515:                        /* reserved for future owner/mode info */
                   1516:                        packet_put_cstring("");
                   1517:                } else {
                   1518:                        /* originator host and port */
                   1519:                        packet_put_cstring(remote_ipaddr);
                   1520:                        packet_put_int((u_int)remote_port);
                   1521:                }
1.103     markus   1522:                packet_send();
                   1523:        } else {
                   1524:                packet_start(SSH_MSG_PORT_OPEN);
                   1525:                packet_put_int(c->self);
                   1526:                packet_put_cstring(c->path);
                   1527:                packet_put_int(c->host_port);
1.121     markus   1528:                if (packet_get_protocol_flags() &
                   1529:                    SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1.103     markus   1530:                        packet_put_cstring(c->remote_name);
                   1531:                packet_send();
                   1532:        }
1.321     djm      1533:        free(remote_ipaddr);
1.328     djm      1534:        free(local_ipaddr);
1.103     markus   1535: }
                   1536:
1.226     djm      1537: static void
                   1538: channel_set_reuseaddr(int fd)
                   1539: {
                   1540:        int on = 1;
                   1541:
                   1542:        /*
                   1543:         * Set socket options.
                   1544:         * Allow local port reuse in TIME_WAIT.
                   1545:         */
                   1546:        if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
                   1547:                error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
1.347     djm      1548: }
                   1549:
                   1550: void
                   1551: channel_set_x11_refuse_time(u_int refuse_time)
                   1552: {
                   1553:        x11_refuse_time = refuse_time;
1.226     djm      1554: }
                   1555:
1.41      markus   1556: /*
                   1557:  * This socket is listening for connections to a forwarded TCP/IP port.
                   1558:  */
1.259     stevesk  1559: /* ARGSUSED */
1.127     itojun   1560: static void
1.237     deraadt  1561: channel_post_port_listener(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1562: {
1.103     markus   1563:        Channel *nc;
1.285     djm      1564:        struct sockaddr_storage addr;
1.113     markus   1565:        int newsock, nextstate;
1.41      markus   1566:        socklen_t addrlen;
1.103     markus   1567:        char *rtype;
1.73      markus   1568:
1.41      markus   1569:        if (FD_ISSET(c->sock, readset)) {
                   1570:                debug("Connection to port %d forwarding "
                   1571:                    "to %.100s port %d requested.",
                   1572:                    c->listening_port, c->path, c->host_port);
1.103     markus   1573:
1.137     markus   1574:                if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
                   1575:                        nextstate = SSH_CHANNEL_OPENING;
                   1576:                        rtype = "forwarded-tcpip";
1.336     millert  1577:                } else if (c->type == SSH_CHANNEL_RUNIX_LISTENER) {
                   1578:                        nextstate = SSH_CHANNEL_OPENING;
                   1579:                        rtype = "forwarded-streamlocal@openssh.com";
                   1580:                } else if (c->host_port == PORT_STREAMLOCAL) {
                   1581:                        nextstate = SSH_CHANNEL_OPENING;
                   1582:                        rtype = "direct-streamlocal@openssh.com";
                   1583:                } else if (c->host_port == 0) {
                   1584:                        nextstate = SSH_CHANNEL_DYNAMIC;
                   1585:                        rtype = "dynamic-tcpip";
1.137     markus   1586:                } else {
1.336     millert  1587:                        nextstate = SSH_CHANNEL_OPENING;
                   1588:                        rtype = "direct-tcpip";
1.137     markus   1589:                }
1.103     markus   1590:
1.41      markus   1591:                addrlen = sizeof(addr);
1.285     djm      1592:                newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1.41      markus   1593:                if (newsock < 0) {
1.320     markus   1594:                        if (errno != EINTR && errno != EWOULDBLOCK &&
                   1595:                            errno != ECONNABORTED)
                   1596:                                error("accept: %.100s", strerror(errno));
1.317     djm      1597:                        if (errno == EMFILE || errno == ENFILE)
1.322     dtucker  1598:                                c->notbefore = monotime() + 1;
1.41      markus   1599:                        return;
                   1600:                }
1.336     millert  1601:                if (c->host_port != PORT_STREAMLOCAL)
                   1602:                        set_nodelay(newsock);
1.190     markus   1603:                nc = channel_new(rtype, nextstate, newsock, newsock, -1,
                   1604:                    c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1.103     markus   1605:                nc->listening_port = c->listening_port;
                   1606:                nc->host_port = c->host_port;
1.293     djm      1607:                if (c->path != NULL)
                   1608:                        nc->path = xstrdup(c->path);
1.103     markus   1609:
1.299     markus   1610:                if (nextstate != SSH_CHANNEL_DYNAMIC)
1.103     markus   1611:                        port_open_helper(nc, rtype);
1.41      markus   1612:        }
                   1613: }
1.25      markus   1614:
1.41      markus   1615: /*
                   1616:  * This is the authentication agent socket listening for connections from
                   1617:  * clients.
                   1618:  */
1.259     stevesk  1619: /* ARGSUSED */
1.127     itojun   1620: static void
1.237     deraadt  1621: channel_post_auth_listener(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1622: {
1.113     markus   1623:        Channel *nc;
                   1624:        int newsock;
1.285     djm      1625:        struct sockaddr_storage addr;
1.41      markus   1626:        socklen_t addrlen;
1.25      markus   1627:
1.41      markus   1628:        if (FD_ISSET(c->sock, readset)) {
                   1629:                addrlen = sizeof(addr);
1.285     djm      1630:                newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1.41      markus   1631:                if (newsock < 0) {
1.317     djm      1632:                        error("accept from auth socket: %.100s",
                   1633:                            strerror(errno));
                   1634:                        if (errno == EMFILE || errno == ENFILE)
1.322     dtucker  1635:                                c->notbefore = monotime() + 1;
1.41      markus   1636:                        return;
                   1637:                }
1.113     markus   1638:                nc = channel_new("accepted auth socket",
1.73      markus   1639:                    SSH_CHANNEL_OPENING, newsock, newsock, -1,
                   1640:                    c->local_window_max, c->local_maxpacket,
1.190     markus   1641:                    0, "accepted auth socket", 1);
1.73      markus   1642:                if (compat20) {
                   1643:                        packet_start(SSH2_MSG_CHANNEL_OPEN);
                   1644:                        packet_put_cstring("auth-agent@openssh.com");
1.113     markus   1645:                        packet_put_int(nc->self);
1.73      markus   1646:                        packet_put_int(c->local_window_max);
                   1647:                        packet_put_int(c->local_maxpacket);
                   1648:                } else {
                   1649:                        packet_start(SSH_SMSG_AGENT_OPEN);
1.113     markus   1650:                        packet_put_int(nc->self);
1.73      markus   1651:                }
1.41      markus   1652:                packet_send();
                   1653:        }
                   1654: }
1.25      markus   1655:
1.259     stevesk  1656: /* ARGSUSED */
1.127     itojun   1657: static void
1.237     deraadt  1658: channel_post_connecting(Channel *c, fd_set *readset, fd_set *writeset)
1.75      markus   1659: {
1.276     djm      1660:        int err = 0, sock;
1.129     stevesk  1661:        socklen_t sz = sizeof(err);
1.114     markus   1662:
1.75      markus   1663:        if (FD_ISSET(c->sock, writeset)) {
1.170     stevesk  1664:                if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1.114     markus   1665:                        err = errno;
                   1666:                        error("getsockopt SO_ERROR failed");
                   1667:                }
                   1668:                if (err == 0) {
1.276     djm      1669:                        debug("channel %d: connected to %s port %d",
                   1670:                            c->self, c->connect_ctx.host, c->connect_ctx.port);
                   1671:                        channel_connect_ctx_free(&c->connect_ctx);
1.114     markus   1672:                        c->type = SSH_CHANNEL_OPEN;
                   1673:                        if (compat20) {
                   1674:                                packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1675:                                packet_put_int(c->remote_id);
                   1676:                                packet_put_int(c->self);
                   1677:                                packet_put_int(c->local_window);
                   1678:                                packet_put_int(c->local_maxpacket);
                   1679:                        } else {
                   1680:                                packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1681:                                packet_put_int(c->remote_id);
                   1682:                                packet_put_int(c->self);
                   1683:                        }
1.75      markus   1684:                } else {
1.276     djm      1685:                        debug("channel %d: connection failed: %s",
1.114     markus   1686:                            c->self, strerror(err));
1.276     djm      1687:                        /* Try next address, if any */
                   1688:                        if ((sock = connect_next(&c->connect_ctx)) > 0) {
                   1689:                                close(c->sock);
                   1690:                                c->sock = c->rfd = c->wfd = sock;
                   1691:                                channel_max_fd = channel_find_maxfd();
                   1692:                                return;
                   1693:                        }
                   1694:                        /* Exhausted all addresses */
                   1695:                        error("connect_to %.100s port %d: failed.",
                   1696:                            c->connect_ctx.host, c->connect_ctx.port);
                   1697:                        channel_connect_ctx_free(&c->connect_ctx);
1.114     markus   1698:                        if (compat20) {
                   1699:                                packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
                   1700:                                packet_put_int(c->remote_id);
                   1701:                                packet_put_int(SSH2_OPEN_CONNECT_FAILED);
                   1702:                                if (!(datafellows & SSH_BUG_OPENFAILURE)) {
                   1703:                                        packet_put_cstring(strerror(err));
                   1704:                                        packet_put_cstring("");
                   1705:                                }
1.75      markus   1706:                        } else {
1.114     markus   1707:                                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   1708:                                packet_put_int(c->remote_id);
1.75      markus   1709:                        }
1.114     markus   1710:                        chan_mark_dead(c);
1.75      markus   1711:                }
1.114     markus   1712:                packet_send();
1.75      markus   1713:        }
                   1714: }
                   1715:
1.259     stevesk  1716: /* ARGSUSED */
1.127     itojun   1717: static int
1.237     deraadt  1718: channel_handle_rfd(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1719: {
1.214     markus   1720:        char buf[CHAN_RBUF];
1.41      markus   1721:        int len;
1.25      markus   1722:
1.118     markus   1723:        if (c->rfd != -1 &&
1.41      markus   1724:            FD_ISSET(c->rfd, readset)) {
                   1725:                len = read(c->rfd, buf, sizeof(buf));
1.53      markus   1726:                if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1727:                        return 1;
1.41      markus   1728:                if (len <= 0) {
1.194     markus   1729:                        debug2("channel %d: read<=0 rfd %d len %d",
1.41      markus   1730:                            c->self, c->rfd, len);
1.104     markus   1731:                        if (c->type != SSH_CHANNEL_OPEN) {
1.194     markus   1732:                                debug2("channel %d: not open", c->self);
1.113     markus   1733:                                chan_mark_dead(c);
1.103     markus   1734:                                return -1;
1.104     markus   1735:                        } else if (compat13) {
1.158     markus   1736:                                buffer_clear(&c->output);
1.41      markus   1737:                                c->type = SSH_CHANNEL_INPUT_DRAINING;
1.194     markus   1738:                                debug2("channel %d: input draining.", c->self);
1.25      markus   1739:                        } else {
1.41      markus   1740:                                chan_read_failed(c);
1.25      markus   1741:                        }
1.41      markus   1742:                        return -1;
                   1743:                }
1.143     deraadt  1744:                if (c->input_filter != NULL) {
1.66      markus   1745:                        if (c->input_filter(c, buf, len) == -1) {
1.194     markus   1746:                                debug2("channel %d: filter stops", c->self);
1.65      markus   1747:                                chan_read_failed(c);
                   1748:                        }
1.228     reyk     1749:                } else if (c->datagram) {
                   1750:                        buffer_put_string(&c->input, buf, len);
1.65      markus   1751:                } else {
                   1752:                        buffer_append(&c->input, buf, len);
                   1753:                }
1.41      markus   1754:        }
                   1755:        return 1;
                   1756: }
1.241     deraadt  1757:
1.259     stevesk  1758: /* ARGSUSED */
1.127     itojun   1759: static int
1.237     deraadt  1760: channel_handle_wfd(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1761: {
1.95      markus   1762:        struct termios tio;
1.231     reyk     1763:        u_char *data = NULL, *buf;
1.309     djm      1764:        u_int dlen, olen = 0;
1.41      markus   1765:        int len;
1.25      markus   1766:
1.41      markus   1767:        /* Send buffered output data to the socket. */
1.118     markus   1768:        if (c->wfd != -1 &&
1.41      markus   1769:            FD_ISSET(c->wfd, writeset) &&
                   1770:            buffer_len(&c->output) > 0) {
1.309     djm      1771:                olen = buffer_len(&c->output);
1.231     reyk     1772:                if (c->output_filter != NULL) {
                   1773:                        if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
                   1774:                                debug2("channel %d: filter stops", c->self);
1.232     reyk     1775:                                if (c->type != SSH_CHANNEL_OPEN)
                   1776:                                        chan_mark_dead(c);
                   1777:                                else
                   1778:                                        chan_write_failed(c);
                   1779:                                return -1;
1.231     reyk     1780:                        }
                   1781:                } else if (c->datagram) {
                   1782:                        buf = data = buffer_get_string(&c->output, &dlen);
                   1783:                } else {
                   1784:                        buf = data = buffer_ptr(&c->output);
                   1785:                        dlen = buffer_len(&c->output);
                   1786:                }
                   1787:
1.228     reyk     1788:                if (c->datagram) {
                   1789:                        /* ignore truncated writes, datagrams might get lost */
1.231     reyk     1790:                        len = write(c->wfd, buf, dlen);
1.321     djm      1791:                        free(data);
1.228     reyk     1792:                        if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1793:                                return 1;
                   1794:                        if (len <= 0) {
                   1795:                                if (c->type != SSH_CHANNEL_OPEN)
                   1796:                                        chan_mark_dead(c);
                   1797:                                else
                   1798:                                        chan_write_failed(c);
                   1799:                                return -1;
                   1800:                        }
1.309     djm      1801:                        goto out;
1.228     reyk     1802:                }
1.231     reyk     1803:
                   1804:                len = write(c->wfd, buf, dlen);
1.53      markus   1805:                if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1806:                        return 1;
1.41      markus   1807:                if (len <= 0) {
1.104     markus   1808:                        if (c->type != SSH_CHANNEL_OPEN) {
1.194     markus   1809:                                debug2("channel %d: not open", c->self);
1.113     markus   1810:                                chan_mark_dead(c);
1.104     markus   1811:                                return -1;
                   1812:                        } else if (compat13) {
1.158     markus   1813:                                buffer_clear(&c->output);
1.194     markus   1814:                                debug2("channel %d: input draining.", c->self);
1.41      markus   1815:                                c->type = SSH_CHANNEL_INPUT_DRAINING;
                   1816:                        } else {
                   1817:                                chan_write_failed(c);
                   1818:                        }
                   1819:                        return -1;
1.91      markus   1820:                }
1.231     reyk     1821:                if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
1.91      markus   1822:                        if (tcgetattr(c->wfd, &tio) == 0 &&
                   1823:                            !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
                   1824:                                /*
                   1825:                                 * Simulate echo to reduce the impact of
1.96      markus   1826:                                 * traffic analysis. We need to match the
1.95      markus   1827:                                 * size of a SSH2_MSG_CHANNEL_DATA message
1.231     reyk     1828:                                 * (4 byte channel id + buf)
1.91      markus   1829:                                 */
1.95      markus   1830:                                packet_send_ignore(4 + len);
1.91      markus   1831:                                packet_send();
                   1832:                        }
1.25      markus   1833:                }
1.41      markus   1834:                buffer_consume(&c->output, len);
1.44      markus   1835:        }
1.309     djm      1836:  out:
                   1837:        if (compat20 && olen > 0)
                   1838:                c->local_consumed += olen - buffer_len(&c->output);
1.44      markus   1839:        return 1;
                   1840: }
1.241     deraadt  1841:
1.127     itojun   1842: static int
1.237     deraadt  1843: channel_handle_efd(Channel *c, fd_set *readset, fd_set *writeset)
1.44      markus   1844: {
1.214     markus   1845:        char buf[CHAN_RBUF];
1.44      markus   1846:        int len;
                   1847:
1.45      markus   1848: /** XXX handle drain efd, too */
1.44      markus   1849:        if (c->efd != -1) {
                   1850:                if (c->extended_usage == CHAN_EXTENDED_WRITE &&
                   1851:                    FD_ISSET(c->efd, writeset) &&
                   1852:                    buffer_len(&c->extended) > 0) {
                   1853:                        len = write(c->efd, buffer_ptr(&c->extended),
                   1854:                            buffer_len(&c->extended));
1.70      markus   1855:                        debug2("channel %d: written %d to efd %d",
1.44      markus   1856:                            c->self, len, c->efd);
1.93      markus   1857:                        if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1858:                                return 1;
                   1859:                        if (len <= 0) {
                   1860:                                debug2("channel %d: closing write-efd %d",
                   1861:                                    c->self, c->efd);
1.132     markus   1862:                                channel_close_fd(&c->efd);
1.93      markus   1863:                        } else {
1.44      markus   1864:                                buffer_consume(&c->extended, len);
                   1865:                                c->local_consumed += len;
                   1866:                        }
1.306     djm      1867:                } else if (c->efd != -1 &&
                   1868:                    (c->extended_usage == CHAN_EXTENDED_READ ||
                   1869:                    c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1.44      markus   1870:                    FD_ISSET(c->efd, readset)) {
                   1871:                        len = read(c->efd, buf, sizeof(buf));
1.70      markus   1872:                        debug2("channel %d: read %d from efd %d",
1.148     deraadt  1873:                            c->self, len, c->efd);
1.93      markus   1874:                        if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1875:                                return 1;
                   1876:                        if (len <= 0) {
                   1877:                                debug2("channel %d: closing read-efd %d",
1.45      markus   1878:                                    c->self, c->efd);
1.132     markus   1879:                                channel_close_fd(&c->efd);
1.93      markus   1880:                        } else {
1.306     djm      1881:                                if (c->extended_usage == CHAN_EXTENDED_IGNORE) {
                   1882:                                        debug3("channel %d: discard efd",
                   1883:                                            c->self);
                   1884:                                } else
                   1885:                                        buffer_append(&c->extended, buf, len);
1.93      markus   1886:                        }
1.44      markus   1887:                }
                   1888:        }
                   1889:        return 1;
                   1890: }
1.241     deraadt  1891:
1.259     stevesk  1892: /* ARGSUSED */
1.127     itojun   1893: static int
1.93      markus   1894: channel_check_window(Channel *c)
1.44      markus   1895: {
1.104     markus   1896:        if (c->type == SSH_CHANNEL_OPEN &&
                   1897:            !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1.270     dtucker  1898:            ((c->local_window_max - c->local_window >
1.269     markus   1899:            c->local_maxpacket*3) ||
                   1900:            c->local_window < c->local_window_max/2) &&
1.44      markus   1901:            c->local_consumed > 0) {
                   1902:                packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
                   1903:                packet_put_int(c->remote_id);
                   1904:                packet_put_int(c->local_consumed);
                   1905:                packet_send();
1.70      markus   1906:                debug2("channel %d: window %d sent adjust %d",
1.44      markus   1907:                    c->self, c->local_window,
                   1908:                    c->local_consumed);
                   1909:                c->local_window += c->local_consumed;
                   1910:                c->local_consumed = 0;
1.1       deraadt  1911:        }
1.41      markus   1912:        return 1;
1.1       deraadt  1913: }
                   1914:
1.127     itojun   1915: static void
1.237     deraadt  1916: channel_post_open(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1917: {
                   1918:        channel_handle_rfd(c, readset, writeset);
                   1919:        channel_handle_wfd(c, readset, writeset);
1.157     markus   1920:        if (!compat20)
1.137     markus   1921:                return;
1.44      markus   1922:        channel_handle_efd(c, readset, writeset);
1.93      markus   1923:        channel_check_window(c);
1.44      markus   1924: }
                   1925:
1.302     djm      1926: static u_int
                   1927: read_mux(Channel *c, u_int need)
                   1928: {
                   1929:        char buf[CHAN_RBUF];
                   1930:        int len;
                   1931:        u_int rlen;
                   1932:
                   1933:        if (buffer_len(&c->input) < need) {
                   1934:                rlen = need - buffer_len(&c->input);
1.352     deraadt  1935:                len = read(c->rfd, buf, MINIMUM(rlen, CHAN_RBUF));
1.349     naddy    1936:                if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1937:                        return buffer_len(&c->input);
1.302     djm      1938:                if (len <= 0) {
1.349     naddy    1939:                        debug2("channel %d: ctl read<=0 rfd %d len %d",
                   1940:                            c->self, c->rfd, len);
                   1941:                        chan_read_failed(c);
                   1942:                        return 0;
1.302     djm      1943:                } else
                   1944:                        buffer_append(&c->input, buf, len);
                   1945:        }
                   1946:        return buffer_len(&c->input);
                   1947: }
                   1948:
                   1949: static void
                   1950: channel_post_mux_client(Channel *c, fd_set *readset, fd_set *writeset)
                   1951: {
                   1952:        u_int need;
                   1953:        ssize_t len;
                   1954:
                   1955:        if (!compat20)
                   1956:                fatal("%s: entered with !compat20", __func__);
                   1957:
1.304     djm      1958:        if (c->rfd != -1 && !c->mux_pause && FD_ISSET(c->rfd, readset) &&
1.302     djm      1959:            (c->istate == CHAN_INPUT_OPEN ||
                   1960:            c->istate == CHAN_INPUT_WAIT_DRAIN)) {
                   1961:                /*
                   1962:                 * Don't not read past the precise end of packets to
                   1963:                 * avoid disrupting fd passing.
                   1964:                 */
                   1965:                if (read_mux(c, 4) < 4) /* read header */
                   1966:                        return;
                   1967:                need = get_u32(buffer_ptr(&c->input));
                   1968: #define CHANNEL_MUX_MAX_PACKET (256 * 1024)
                   1969:                if (need > CHANNEL_MUX_MAX_PACKET) {
                   1970:                        debug2("channel %d: packet too big %u > %u",
                   1971:                            c->self, CHANNEL_MUX_MAX_PACKET, need);
                   1972:                        chan_rcvd_oclose(c);
                   1973:                        return;
                   1974:                }
                   1975:                if (read_mux(c, need + 4) < need + 4) /* read body */
                   1976:                        return;
                   1977:                if (c->mux_rcb(c) != 0) {
                   1978:                        debug("channel %d: mux_rcb failed", c->self);
                   1979:                        chan_mark_dead(c);
                   1980:                        return;
                   1981:                }
                   1982:        }
                   1983:
                   1984:        if (c->wfd != -1 && FD_ISSET(c->wfd, writeset) &&
                   1985:            buffer_len(&c->output) > 0) {
                   1986:                len = write(c->wfd, buffer_ptr(&c->output),
                   1987:                    buffer_len(&c->output));
                   1988:                if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1989:                        return;
                   1990:                if (len <= 0) {
                   1991:                        chan_mark_dead(c);
                   1992:                        return;
                   1993:                }
                   1994:                buffer_consume(&c->output, len);
                   1995:        }
                   1996: }
                   1997:
                   1998: static void
                   1999: channel_post_mux_listener(Channel *c, fd_set *readset, fd_set *writeset)
                   2000: {
                   2001:        Channel *nc;
                   2002:        struct sockaddr_storage addr;
                   2003:        socklen_t addrlen;
                   2004:        int newsock;
                   2005:        uid_t euid;
                   2006:        gid_t egid;
                   2007:
                   2008:        if (!FD_ISSET(c->sock, readset))
                   2009:                return;
                   2010:
                   2011:        debug("multiplexing control connection");
                   2012:
                   2013:        /*
                   2014:         * Accept connection on control socket
                   2015:         */
                   2016:        memset(&addr, 0, sizeof(addr));
                   2017:        addrlen = sizeof(addr);
                   2018:        if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
                   2019:            &addrlen)) == -1) {
                   2020:                error("%s accept: %s", __func__, strerror(errno));
1.317     djm      2021:                if (errno == EMFILE || errno == ENFILE)
1.322     dtucker  2022:                        c->notbefore = monotime() + 1;
1.302     djm      2023:                return;
                   2024:        }
                   2025:
                   2026:        if (getpeereid(newsock, &euid, &egid) < 0) {
                   2027:                error("%s getpeereid failed: %s", __func__,
                   2028:                    strerror(errno));
                   2029:                close(newsock);
                   2030:                return;
                   2031:        }
                   2032:        if ((euid != 0) && (getuid() != euid)) {
                   2033:                error("multiplex uid mismatch: peer euid %u != uid %u",
                   2034:                    (u_int)euid, (u_int)getuid());
                   2035:                close(newsock);
                   2036:                return;
                   2037:        }
                   2038:        nc = channel_new("multiplex client", SSH_CHANNEL_MUX_CLIENT,
                   2039:            newsock, newsock, -1, c->local_window_max,
                   2040:            c->local_maxpacket, 0, "mux-control", 1);
                   2041:        nc->mux_rcb = c->mux_rcb;
                   2042:        debug3("%s: new mux channel %d fd %d", __func__,
                   2043:            nc->self, nc->sock);
                   2044:        /* establish state */
                   2045:        nc->mux_rcb(nc);
                   2046:        /* mux state transitions must not elicit protocol messages */
                   2047:        nc->flags |= CHAN_LOCAL;
                   2048: }
                   2049:
1.259     stevesk  2050: /* ARGSUSED */
1.127     itojun   2051: static void
1.237     deraadt  2052: channel_post_output_drain_13(Channel *c, fd_set *readset, fd_set *writeset)
1.1       deraadt  2053: {
1.41      markus   2054:        int len;
1.180     deraadt  2055:
1.41      markus   2056:        /* Send buffered output data to the socket. */
                   2057:        if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
                   2058:                len = write(c->sock, buffer_ptr(&c->output),
                   2059:                            buffer_len(&c->output));
                   2060:                if (len <= 0)
1.158     markus   2061:                        buffer_clear(&c->output);
1.41      markus   2062:                else
                   2063:                        buffer_consume(&c->output, len);
                   2064:        }
                   2065: }
1.25      markus   2066:
1.127     itojun   2067: static void
1.44      markus   2068: channel_handler_init_20(void)
                   2069: {
1.157     markus   2070:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open;
1.51      markus   2071:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
1.44      markus   2072:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
1.73      markus   2073:        channel_pre[SSH_CHANNEL_RPORT_LISTENER] =       &channel_pre_listener;
1.336     millert  2074:        channel_pre[SSH_CHANNEL_UNIX_LISTENER] =        &channel_pre_listener;
                   2075:        channel_pre[SSH_CHANNEL_RUNIX_LISTENER] =       &channel_pre_listener;
1.51      markus   2076:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
1.73      markus   2077:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1.75      markus   2078:        channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1.103     markus   2079:        channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1.302     djm      2080:        channel_pre[SSH_CHANNEL_MUX_LISTENER] =         &channel_pre_listener;
                   2081:        channel_pre[SSH_CHANNEL_MUX_CLIENT] =           &channel_pre_mux_client;
1.44      markus   2082:
1.157     markus   2083:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open;
1.44      markus   2084:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
1.73      markus   2085:        channel_post[SSH_CHANNEL_RPORT_LISTENER] =      &channel_post_port_listener;
1.336     millert  2086:        channel_post[SSH_CHANNEL_UNIX_LISTENER] =       &channel_post_port_listener;
                   2087:        channel_post[SSH_CHANNEL_RUNIX_LISTENER] =      &channel_post_port_listener;
1.51      markus   2088:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
1.73      markus   2089:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1.75      markus   2090:        channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1.157     markus   2091:        channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
1.302     djm      2092:        channel_post[SSH_CHANNEL_MUX_LISTENER] =        &channel_post_mux_listener;
                   2093:        channel_post[SSH_CHANNEL_MUX_CLIENT] =          &channel_post_mux_client;
1.44      markus   2094: }
                   2095:
1.127     itojun   2096: static void
1.41      markus   2097: channel_handler_init_13(void)
                   2098: {
                   2099:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_13;
                   2100:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open_13;
                   2101:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
                   2102:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
                   2103:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
                   2104:        channel_pre[SSH_CHANNEL_INPUT_DRAINING] =       &channel_pre_input_draining;
                   2105:        channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] =      &channel_pre_output_draining;
1.75      markus   2106:        channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1.103     markus   2107:        channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1.25      markus   2108:
1.157     markus   2109:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open;
1.41      markus   2110:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
                   2111:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
                   2112:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
                   2113:        channel_post[SSH_CHANNEL_OUTPUT_DRAINING] =     &channel_post_output_drain_13;
1.75      markus   2114:        channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1.157     markus   2115:        channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
1.41      markus   2116: }
1.25      markus   2117:
1.127     itojun   2118: static void
1.41      markus   2119: channel_handler_init_15(void)
                   2120: {
1.157     markus   2121:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open;
1.51      markus   2122:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
1.41      markus   2123:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
                   2124:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
                   2125:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1.75      markus   2126:        channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1.103     markus   2127:        channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1.25      markus   2128:
1.41      markus   2129:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
                   2130:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
                   2131:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1.157     markus   2132:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open;
1.75      markus   2133:        channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1.157     markus   2134:        channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
1.41      markus   2135: }
1.27      markus   2136:
1.127     itojun   2137: static void
1.41      markus   2138: channel_handler_init(void)
                   2139: {
                   2140:        int i;
1.180     deraadt  2141:
1.148     deraadt  2142:        for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1.41      markus   2143:                channel_pre[i] = NULL;
                   2144:                channel_post[i] = NULL;
                   2145:        }
1.44      markus   2146:        if (compat20)
                   2147:                channel_handler_init_20();
                   2148:        else if (compat13)
1.41      markus   2149:                channel_handler_init_13();
                   2150:        else
                   2151:                channel_handler_init_15();
                   2152: }
1.25      markus   2153:
1.140     markus   2154: /* gc dead channels */
                   2155: static void
                   2156: channel_garbage_collect(Channel *c)
                   2157: {
                   2158:        if (c == NULL)
                   2159:                return;
                   2160:        if (c->detach_user != NULL) {
1.225     djm      2161:                if (!chan_is_dead(c, c->detach_close))
1.140     markus   2162:                        return;
1.194     markus   2163:                debug2("channel %d: gc: notify user", c->self);
1.140     markus   2164:                c->detach_user(c->self, NULL);
                   2165:                /* if we still have a callback */
                   2166:                if (c->detach_user != NULL)
                   2167:                        return;
1.194     markus   2168:                debug2("channel %d: gc: user detached", c->self);
1.140     markus   2169:        }
                   2170:        if (!chan_is_dead(c, 1))
                   2171:                return;
1.194     markus   2172:        debug2("channel %d: garbage collecting", c->self);
1.140     markus   2173:        channel_free(c);
                   2174: }
                   2175:
1.127     itojun   2176: static void
1.317     djm      2177: channel_handler(chan_fn *ftab[], fd_set *readset, fd_set *writeset,
                   2178:     time_t *unpause_secs)
1.41      markus   2179: {
                   2180:        static int did_init = 0;
1.299     markus   2181:        u_int i, oalloc;
1.41      markus   2182:        Channel *c;
1.317     djm      2183:        time_t now;
1.25      markus   2184:
1.41      markus   2185:        if (!did_init) {
                   2186:                channel_handler_init();
                   2187:                did_init = 1;
                   2188:        }
1.322     dtucker  2189:        now = monotime();
1.317     djm      2190:        if (unpause_secs != NULL)
                   2191:                *unpause_secs = 0;
1.299     markus   2192:        for (i = 0, oalloc = channels_alloc; i < oalloc; i++) {
1.113     markus   2193:                c = channels[i];
                   2194:                if (c == NULL)
1.41      markus   2195:                        continue;
1.299     markus   2196:                if (c->delayed) {
                   2197:                        if (ftab == channel_pre)
                   2198:                                c->delayed = 0;
                   2199:                        else
                   2200:                                continue;
                   2201:                }
1.317     djm      2202:                if (ftab[c->type] != NULL) {
                   2203:                        /*
                   2204:                         * Run handlers that are not paused.
                   2205:                         */
                   2206:                        if (c->notbefore <= now)
                   2207:                                (*ftab[c->type])(c, readset, writeset);
                   2208:                        else if (unpause_secs != NULL) {
                   2209:                                /*
                   2210:                                 * Collect the time that the earliest
                   2211:                                 * channel comes off pause.
                   2212:                                 */
                   2213:                                debug3("%s: chan %d: skip for %d more seconds",
                   2214:                                    __func__, c->self,
                   2215:                                    (int)(c->notbefore - now));
                   2216:                                if (*unpause_secs == 0 ||
                   2217:                                    (c->notbefore - now) < *unpause_secs)
                   2218:                                        *unpause_secs = c->notbefore - now;
                   2219:                        }
                   2220:                }
1.140     markus   2221:                channel_garbage_collect(c);
1.1       deraadt  2222:        }
1.317     djm      2223:        if (unpause_secs != NULL && *unpause_secs != 0)
                   2224:                debug3("%s: first channel unpauses in %d seconds",
                   2225:                    __func__, (int)*unpause_secs);
1.1       deraadt  2226: }
                   2227:
1.121     markus   2228: /*
                   2229:  * Allocate/update select bitmasks and add any bits relevant to channels in
                   2230:  * select bitmasks.
                   2231:  */
1.49      markus   2232: void
1.100     markus   2233: channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1.318     djm      2234:     u_int *nallocp, time_t *minwait_secs, int rekeying)
1.41      markus   2235: {
1.243     djm      2236:        u_int n, sz, nfdset;
1.84      markus   2237:
1.352     deraadt  2238:        n = MAXIMUM(*maxfdp, channel_max_fd);
1.84      markus   2239:
1.243     djm      2240:        nfdset = howmany(n+1, NFDBITS);
                   2241:        /* Explicitly test here, because xrealloc isn't always called */
1.341     millert  2242:        if (nfdset && SIZE_MAX / nfdset < sizeof(fd_mask))
1.243     djm      2243:                fatal("channel_prepare_select: max_fd (%d) is too large", n);
                   2244:        sz = nfdset * sizeof(fd_mask);
                   2245:
1.132     markus   2246:        /* perhaps check sz < nalloc/2 and shrink? */
                   2247:        if (*readsetp == NULL || sz > *nallocp) {
1.342     deraadt  2248:                *readsetp = xreallocarray(*readsetp, nfdset, sizeof(fd_mask));
                   2249:                *writesetp = xreallocarray(*writesetp, nfdset, sizeof(fd_mask));
1.132     markus   2250:                *nallocp = sz;
1.84      markus   2251:        }
1.132     markus   2252:        *maxfdp = n;
1.84      markus   2253:        memset(*readsetp, 0, sz);
                   2254:        memset(*writesetp, 0, sz);
                   2255:
1.100     markus   2256:        if (!rekeying)
1.317     djm      2257:                channel_handler(channel_pre, *readsetp, *writesetp,
                   2258:                    minwait_secs);
1.41      markus   2259: }
                   2260:
1.121     markus   2261: /*
                   2262:  * After select, perform any appropriate operations for channels which have
                   2263:  * events pending.
                   2264:  */
1.49      markus   2265: void
1.237     deraadt  2266: channel_after_select(fd_set *readset, fd_set *writeset)
1.41      markus   2267: {
1.317     djm      2268:        channel_handler(channel_post, readset, writeset, NULL);
1.41      markus   2269: }
                   2270:
1.121     markus   2271:
1.84      markus   2272: /* If there is data to send to the connection, enqueue some of it now. */
1.49      markus   2273: void
1.142     itojun   2274: channel_output_poll(void)
1.1       deraadt  2275: {
1.41      markus   2276:        Channel *c;
1.209     avsm     2277:        u_int i, len;
1.1       deraadt  2278:
1.25      markus   2279:        for (i = 0; i < channels_alloc; i++) {
1.113     markus   2280:                c = channels[i];
                   2281:                if (c == NULL)
                   2282:                        continue;
1.37      markus   2283:
1.121     markus   2284:                /*
                   2285:                 * We are only interested in channels that can have buffered
                   2286:                 * incoming data.
                   2287:                 */
1.37      markus   2288:                if (compat13) {
1.41      markus   2289:                        if (c->type != SSH_CHANNEL_OPEN &&
                   2290:                            c->type != SSH_CHANNEL_INPUT_DRAINING)
1.37      markus   2291:                                continue;
                   2292:                } else {
1.41      markus   2293:                        if (c->type != SSH_CHANNEL_OPEN)
1.37      markus   2294:                                continue;
                   2295:                }
1.46      markus   2296:                if (compat20 &&
                   2297:                    (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1.93      markus   2298:                        /* XXX is this true? */
1.140     markus   2299:                        debug3("channel %d: will not send data after close", c->self);
1.44      markus   2300:                        continue;
                   2301:                }
1.25      markus   2302:
                   2303:                /* Get the amount of buffered data for this channel. */
1.93      markus   2304:                if ((c->istate == CHAN_INPUT_OPEN ||
                   2305:                    c->istate == CHAN_INPUT_WAIT_DRAIN) &&
                   2306:                    (len = buffer_len(&c->input)) > 0) {
1.228     reyk     2307:                        if (c->datagram) {
                   2308:                                if (len > 0) {
                   2309:                                        u_char *data;
                   2310:                                        u_int dlen;
                   2311:
                   2312:                                        data = buffer_get_string(&c->input,
                   2313:                                            &dlen);
1.309     djm      2314:                                        if (dlen > c->remote_window ||
                   2315:                                            dlen > c->remote_maxpacket) {
                   2316:                                                debug("channel %d: datagram "
                   2317:                                                    "too big for channel",
                   2318:                                                    c->self);
1.321     djm      2319:                                                free(data);
1.309     djm      2320:                                                continue;
                   2321:                                        }
1.228     reyk     2322:                                        packet_start(SSH2_MSG_CHANNEL_DATA);
                   2323:                                        packet_put_int(c->remote_id);
                   2324:                                        packet_put_string(data, dlen);
                   2325:                                        packet_send();
1.345     djm      2326:                                        c->remote_window -= dlen;
1.321     djm      2327:                                        free(data);
1.228     reyk     2328:                                }
                   2329:                                continue;
                   2330:                        }
1.121     markus   2331:                        /*
                   2332:                         * Send some data for the other side over the secure
                   2333:                         * connection.
                   2334:                         */
1.44      markus   2335:                        if (compat20) {
                   2336:                                if (len > c->remote_window)
                   2337:                                        len = c->remote_window;
                   2338:                                if (len > c->remote_maxpacket)
                   2339:                                        len = c->remote_maxpacket;
1.25      markus   2340:                        } else {
1.44      markus   2341:                                if (packet_is_interactive()) {
                   2342:                                        if (len > 1024)
                   2343:                                                len = 512;
                   2344:                                } else {
                   2345:                                        /* Keep the packets at reasonable size. */
                   2346:                                        if (len > packet_get_maxsize()/2)
                   2347:                                                len = packet_get_maxsize()/2;
                   2348:                                }
1.25      markus   2349:                        }
1.41      markus   2350:                        if (len > 0) {
1.44      markus   2351:                                packet_start(compat20 ?
                   2352:                                    SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1.41      markus   2353:                                packet_put_int(c->remote_id);
                   2354:                                packet_put_string(buffer_ptr(&c->input), len);
                   2355:                                packet_send();
                   2356:                                buffer_consume(&c->input, len);
                   2357:                                c->remote_window -= len;
                   2358:                        }
                   2359:                } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1.25      markus   2360:                        if (compat13)
                   2361:                                fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1.27      markus   2362:                        /*
                   2363:                         * input-buffer is empty and read-socket shutdown:
1.172     markus   2364:                         * tell peer, that we will not send more data: send IEOF.
                   2365:                         * hack for extended data: delay EOF if EFD still in use.
1.27      markus   2366:                         */
1.172     markus   2367:                        if (CHANNEL_EFD_INPUT_ACTIVE(c))
1.223     djm      2368:                                debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
                   2369:                                    c->self, c->efd, buffer_len(&c->extended));
1.172     markus   2370:                        else
                   2371:                                chan_ibuf_empty(c);
1.25      markus   2372:                }
1.44      markus   2373:                /* Send extended data, i.e. stderr */
                   2374:                if (compat20 &&
1.172     markus   2375:                    !(c->flags & CHAN_EOF_SENT) &&
1.44      markus   2376:                    c->remote_window > 0 &&
                   2377:                    (len = buffer_len(&c->extended)) > 0 &&
                   2378:                    c->extended_usage == CHAN_EXTENDED_READ) {
1.178     markus   2379:                        debug2("channel %d: rwin %u elen %u euse %d",
1.93      markus   2380:                            c->self, c->remote_window, buffer_len(&c->extended),
                   2381:                            c->extended_usage);
1.44      markus   2382:                        if (len > c->remote_window)
                   2383:                                len = c->remote_window;
                   2384:                        if (len > c->remote_maxpacket)
                   2385:                                len = c->remote_maxpacket;
                   2386:                        packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
                   2387:                        packet_put_int(c->remote_id);
                   2388:                        packet_put_int(SSH2_EXTENDED_DATA_STDERR);
                   2389:                        packet_put_string(buffer_ptr(&c->extended), len);
                   2390:                        packet_send();
                   2391:                        buffer_consume(&c->extended, len);
                   2392:                        c->remote_window -= len;
1.93      markus   2393:                        debug2("channel %d: sent ext data %d", c->self, len);
1.44      markus   2394:                }
1.25      markus   2395:        }
1.1       deraadt  2396: }
                   2397:
1.354   ! markus   2398: /* -- mux proxy support  */
        !          2399:
        !          2400: /*
        !          2401:  * When multiplexing channel messages for mux clients we have to deal
        !          2402:  * with downstream messages from the mux client and upstream messages
        !          2403:  * from the ssh server:
        !          2404:  * 1) Handling downstream messages is straightforward and happens
        !          2405:  *    in channel_proxy_downstream():
        !          2406:  *    - We forward all messages (mostly) unmodified to the server.
        !          2407:  *    - However, in order to route messages from upstream to the correct
        !          2408:  *      downstream client, we have to replace the channel IDs used by the
        !          2409:  *      mux clients with a unique channel ID because the mux clients might
        !          2410:  *      use conflicting channel IDs.
        !          2411:  *    - so we inspect and change both SSH2_MSG_CHANNEL_OPEN and
        !          2412:  *      SSH2_MSG_CHANNEL_OPEN_CONFIRMATION messages, create a local
        !          2413:  *      SSH_CHANNEL_MUX_PROXY channel and replace the mux clients ID
        !          2414:  *      with the newly allocated channel ID.
        !          2415:  * 2) Upstream messages are received by matching SSH_CHANNEL_MUX_PROXY
        !          2416:  *    channels and procesed by channel_proxy_upstream(). The local channel ID
        !          2417:  *    is then translated back to the original mux client ID.
        !          2418:  * 3) In both cases we need to keep track of matching SSH2_MSG_CHANNEL_CLOSE
        !          2419:  *    messages so we can clean up SSH_CHANNEL_MUX_PROXY channels.
        !          2420:  * 4) The SSH_CHANNEL_MUX_PROXY channels also need to closed when the
        !          2421:  *    downstream mux client are removed.
        !          2422:  * 5) Handling SSH2_MSG_CHANNEL_OPEN messages from the upstream server
        !          2423:  *    requires more work, because they are not addressed to a specific
        !          2424:  *    channel. E.g. client_request_forwarded_tcpip() needs to figure
        !          2425:  *    out whether the request is addressed to the local client or a
        !          2426:  *    specific downstream client based on the listen-address/port.
        !          2427:  * 6) Agent and X11-Forwarding have a similar problem and are currenly
        !          2428:  *    not supported as the matching session/channel cannot be identified
        !          2429:  *    easily.
        !          2430:  */
        !          2431:
        !          2432: /*
        !          2433:  * receive packets from downstream mux clients:
        !          2434:  * channel callback fired on read from mux client, creates
        !          2435:  * SSH_CHANNEL_MUX_PROXY channels and translates channel IDs
        !          2436:  * on channel creation.
        !          2437:  */
        !          2438: int
        !          2439: channel_proxy_downstream(Channel *downstream)
        !          2440: {
        !          2441:        Channel *c = NULL;
        !          2442:        struct ssh *ssh = active_state;
        !          2443:        struct sshbuf *original = NULL, *modified = NULL;
        !          2444:        const u_char *cp;
        !          2445:        char *ctype = NULL, *listen_host = NULL;
        !          2446:        u_char type;
        !          2447:        size_t have;
        !          2448:        int ret = -1, r, id, remote_id, listen_port, idx;
        !          2449:
        !          2450:        /* sshbuf_dump(&downstream->input, stderr); */
        !          2451:        if ((r = sshbuf_get_string_direct(&downstream->input, &cp, &have))
        !          2452:            != 0) {
        !          2453:                error("%s: malformed message: %s", __func__, ssh_err(r));
        !          2454:                return -1;
        !          2455:        }
        !          2456:        if (have < 2) {
        !          2457:                error("%s: short message", __func__);
        !          2458:                return -1;
        !          2459:        }
        !          2460:        type = cp[1];
        !          2461:        /* skip padlen + type */
        !          2462:        cp += 2;
        !          2463:        have -= 2;
        !          2464:        if (ssh_packet_log_type(type))
        !          2465:                debug3("%s: channel %u: down->up: type %u", __func__,
        !          2466:                    downstream->self, type);
        !          2467:
        !          2468:        switch (type) {
        !          2469:        case SSH2_MSG_CHANNEL_OPEN:
        !          2470:                if ((original = sshbuf_from(cp, have)) == NULL ||
        !          2471:                    (modified = sshbuf_new()) == NULL) {
        !          2472:                        error("%s: alloc", __func__);
        !          2473:                        goto out;
        !          2474:                }
        !          2475:                if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0 ||
        !          2476:                    (r = sshbuf_get_u32(original, &id)) != 0) {
        !          2477:                        error("%s: parse error %s", __func__, ssh_err(r));
        !          2478:                        goto out;
        !          2479:                }
        !          2480:                c = channel_new("mux proxy", SSH_CHANNEL_MUX_PROXY,
        !          2481:                   -1, -1, -1, 0, 0, 0, ctype, 1);
        !          2482:                c->mux_ctx = downstream;        /* point to mux client */
        !          2483:                c->mux_downstream_id = id;      /* original downstream id */
        !          2484:                if ((r = sshbuf_put_cstring(modified, ctype)) != 0 ||
        !          2485:                    (r = sshbuf_put_u32(modified, c->self)) != 0 ||
        !          2486:                    (r = sshbuf_putb(modified, original)) != 0) {
        !          2487:                        error("%s: compose error %s", __func__, ssh_err(r));
        !          2488:                        channel_free(c);
        !          2489:                        goto out;
        !          2490:                }
        !          2491:                break;
        !          2492:        case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
        !          2493:                /*
        !          2494:                 * Almost the same as SSH2_MSG_CHANNEL_OPEN, except then we
        !          2495:                 * need to parse 'remote_id' instead of 'ctype'.
        !          2496:                 */
        !          2497:                if ((original = sshbuf_from(cp, have)) == NULL ||
        !          2498:                    (modified = sshbuf_new()) == NULL) {
        !          2499:                        error("%s: alloc", __func__);
        !          2500:                        goto out;
        !          2501:                }
        !          2502:                if ((r = sshbuf_get_u32(original, &remote_id)) != 0 ||
        !          2503:                    (r = sshbuf_get_u32(original, &id)) != 0) {
        !          2504:                        error("%s: parse error %s", __func__, ssh_err(r));
        !          2505:                        goto out;
        !          2506:                }
        !          2507:                c = channel_new("mux proxy", SSH_CHANNEL_MUX_PROXY,
        !          2508:                   -1, -1, -1, 0, 0, 0, "mux-down-connect", 1);
        !          2509:                c->mux_ctx = downstream;        /* point to mux client */
        !          2510:                c->mux_downstream_id = id;
        !          2511:                c->remote_id = remote_id;
        !          2512:                if ((r = sshbuf_put_u32(modified, remote_id)) != 0 ||
        !          2513:                    (r = sshbuf_put_u32(modified, c->self)) != 0 ||
        !          2514:                    (r = sshbuf_putb(modified, original)) != 0) {
        !          2515:                        error("%s: compose error %s", __func__, ssh_err(r));
        !          2516:                        channel_free(c);
        !          2517:                        goto out;
        !          2518:                }
        !          2519:                break;
        !          2520:        case SSH2_MSG_GLOBAL_REQUEST:
        !          2521:                if ((original = sshbuf_from(cp, have)) == NULL) {
        !          2522:                        error("%s: alloc", __func__);
        !          2523:                        goto out;
        !          2524:                }
        !          2525:                if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0) {
        !          2526:                        error("%s: parse error %s", __func__, ssh_err(r));
        !          2527:                        goto out;
        !          2528:                }
        !          2529:                if (strcmp(ctype, "tcpip-forward") != 0) {
        !          2530:                        error("%s: unsupported request %s", __func__, ctype);
        !          2531:                        goto out;
        !          2532:                }
        !          2533:                if ((r = sshbuf_get_u8(original, NULL)) != 0 ||
        !          2534:                    (r = sshbuf_get_cstring(original, &listen_host, NULL)) != 0 ||
        !          2535:                    (r = sshbuf_get_u32(original, &listen_port)) != 0) {
        !          2536:                        error("%s: parse error %s", __func__, ssh_err(r));
        !          2537:                        goto out;
        !          2538:                }
        !          2539:                /* Record that connection to this host/port is permitted. */
        !          2540:                permitted_opens = xreallocarray(permitted_opens,
        !          2541:                    num_permitted_opens + 1, sizeof(*permitted_opens));
        !          2542:                idx = num_permitted_opens++;
        !          2543:                permitted_opens[idx].host_to_connect = xstrdup("<mux>");
        !          2544:                permitted_opens[idx].port_to_connect = -1;
        !          2545:                permitted_opens[idx].listen_host = listen_host;
        !          2546:                permitted_opens[idx].listen_port = listen_port;
        !          2547:                permitted_opens[idx].downstream = downstream;
        !          2548:                listen_host = NULL;
        !          2549:                break;
        !          2550:        case SSH2_MSG_CHANNEL_CLOSE:
        !          2551:                if (have < 4)
        !          2552:                        break;
        !          2553:                remote_id = PEEK_U32(cp);
        !          2554:                if ((c = channel_by_remote_id(remote_id)) != NULL) {
        !          2555:                        if (c->flags & CHAN_CLOSE_RCVD)
        !          2556:                                channel_free(c);
        !          2557:                        else
        !          2558:                                c->flags |= CHAN_CLOSE_SENT;
        !          2559:                }
        !          2560:                break;
        !          2561:        }
        !          2562:        if (modified) {
        !          2563:                if ((r = sshpkt_start(ssh, type)) != 0 ||
        !          2564:                    (r = sshpkt_putb(ssh, modified)) != 0 ||
        !          2565:                    (r = sshpkt_send(ssh)) != 0) {
        !          2566:                        error("%s: send %s", __func__, ssh_err(r));
        !          2567:                        goto out;
        !          2568:                }
        !          2569:        } else {
        !          2570:                if ((r = sshpkt_start(ssh, type)) != 0 ||
        !          2571:                    (r = sshpkt_put(ssh, cp, have)) != 0 ||
        !          2572:                    (r = sshpkt_send(ssh)) != 0) {
        !          2573:                        error("%s: send %s", __func__, ssh_err(r));
        !          2574:                        goto out;
        !          2575:                }
        !          2576:        }
        !          2577:        ret = 0;
        !          2578:  out:
        !          2579:        free(ctype);
        !          2580:        free(listen_host);
        !          2581:        sshbuf_free(original);
        !          2582:        sshbuf_free(modified);
        !          2583:        return ret;
        !          2584: }
        !          2585:
        !          2586: /*
        !          2587:  * receive packets from upstream server and de-multiplex packets
        !          2588:  * to correct downstream:
        !          2589:  * implemented as a helper for channel input handlers,
        !          2590:  * replaces local (proxy) channel ID with downstream channel ID.
        !          2591:  */
        !          2592: int
        !          2593: channel_proxy_upstream(Channel *c, int type, u_int32_t seq, void *ctxt)
        !          2594: {
        !          2595:        struct ssh *ssh = active_state;
        !          2596:        struct sshbuf *b = NULL;
        !          2597:        Channel *downstream;
        !          2598:        const u_char *cp = NULL;
        !          2599:        size_t len;
        !          2600:        int r;
        !          2601:
        !          2602:        /*
        !          2603:         * When receiving packets from the peer we need to check whether we
        !          2604:         * need to forward the packets to the mux client. In this case we
        !          2605:         * restore the orignal channel id and keep track of CLOSE messages,
        !          2606:         * so we can cleanup the channel.
        !          2607:         */
        !          2608:        if (c == NULL || c->type != SSH_CHANNEL_MUX_PROXY)
        !          2609:                return 0;
        !          2610:        if ((downstream = c->mux_ctx) == NULL)
        !          2611:                return 0;
        !          2612:        switch (type) {
        !          2613:        case SSH2_MSG_CHANNEL_CLOSE:
        !          2614:        case SSH2_MSG_CHANNEL_DATA:
        !          2615:        case SSH2_MSG_CHANNEL_EOF:
        !          2616:        case SSH2_MSG_CHANNEL_EXTENDED_DATA:
        !          2617:        case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
        !          2618:        case SSH2_MSG_CHANNEL_OPEN_FAILURE:
        !          2619:        case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
        !          2620:        case SSH2_MSG_CHANNEL_SUCCESS:
        !          2621:        case SSH2_MSG_CHANNEL_FAILURE:
        !          2622:        case SSH2_MSG_CHANNEL_REQUEST:
        !          2623:                break;
        !          2624:        default:
        !          2625:                debug2("%s: channel %u: unsupported type %u", __func__,
        !          2626:                    c->self, type);
        !          2627:                return 0;
        !          2628:        }
        !          2629:        if ((b = sshbuf_new()) == NULL) {
        !          2630:                error("%s: alloc reply", __func__);
        !          2631:                goto out;
        !          2632:        }
        !          2633:        /* get remaining payload (after id) */
        !          2634:        cp = sshpkt_ptr(ssh, &len);
        !          2635:        if (cp == NULL) {
        !          2636:                error("%s: no packet", __func__);
        !          2637:                goto out;
        !          2638:        }
        !          2639:        /* translate id and send to muxclient */
        !          2640:        if ((r = sshbuf_put_u8(b, 0)) != 0 ||   /* padlen */
        !          2641:            (r = sshbuf_put_u8(b, type)) != 0 ||
        !          2642:            (r = sshbuf_put_u32(b, c->mux_downstream_id)) != 0 ||
        !          2643:            (r = sshbuf_put(b, cp, len)) != 0 ||
        !          2644:            (r = sshbuf_put_stringb(&downstream->output, b)) != 0) {
        !          2645:                error("%s: compose for muxclient %s", __func__, ssh_err(r));
        !          2646:                goto out;
        !          2647:        }
        !          2648:        /* sshbuf_dump(b, stderr); */
        !          2649:        if (ssh_packet_log_type(type))
        !          2650:                debug3("%s: channel %u: up->down: type %u", __func__, c->self,
        !          2651:                    type);
        !          2652:  out:
        !          2653:        /* update state */
        !          2654:        switch (type) {
        !          2655:        case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
        !          2656:                /* record remote_id for SSH2_MSG_CHANNEL_CLOSE */
        !          2657:                if (cp && len > 4)
        !          2658:                        c->remote_id = PEEK_U32(cp);
        !          2659:                break;
        !          2660:        case SSH2_MSG_CHANNEL_CLOSE:
        !          2661:                if (c->flags & CHAN_CLOSE_SENT)
        !          2662:                        channel_free(c);
        !          2663:                else
        !          2664:                        c->flags |= CHAN_CLOSE_RCVD;
        !          2665:                break;
        !          2666:        }
        !          2667:        sshbuf_free(b);
        !          2668:        return 1;
        !          2669: }
1.121     markus   2670:
                   2671: /* -- protocol input */
1.249     djm      2672:
                   2673: /* ARGSUSED */
1.339     markus   2674: int
1.154     markus   2675: channel_input_data(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2676: {
1.37      markus   2677:        int id;
1.332     djm      2678:        const u_char *data;
1.309     djm      2679:        u_int data_len, win_len;
1.41      markus   2680:        Channel *c;
1.25      markus   2681:
                   2682:        /* Get the channel number and verify it. */
1.37      markus   2683:        id = packet_get_int();
1.41      markus   2684:        c = channel_lookup(id);
                   2685:        if (c == NULL)
1.37      markus   2686:                packet_disconnect("Received data for nonexistent channel %d.", id);
1.354   ! markus   2687:        if (channel_proxy_upstream(c, type, seq, ctxt))
        !          2688:                return 0;
1.25      markus   2689:
                   2690:        /* Ignore any data for non-open channels (might happen on close) */
1.41      markus   2691:        if (c->type != SSH_CHANNEL_OPEN &&
                   2692:            c->type != SSH_CHANNEL_X11_OPEN)
1.339     markus   2693:                return 0;
1.37      markus   2694:
1.25      markus   2695:        /* Get the data. */
1.274     markus   2696:        data = packet_get_string_ptr(&data_len);
1.309     djm      2697:        win_len = data_len;
                   2698:        if (c->datagram)
                   2699:                win_len += 4;  /* string length header */
1.200     markus   2700:
                   2701:        /*
                   2702:         * Ignore data for protocol > 1.3 if output end is no longer open.
                   2703:         * For protocol 2 the sending side is reducing its window as it sends
                   2704:         * data, so we must 'fake' consumption of the data in order to ensure
                   2705:         * that window updates are sent back.  Otherwise the connection might
                   2706:         * deadlock.
                   2707:         */
                   2708:        if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
                   2709:                if (compat20) {
1.309     djm      2710:                        c->local_window -= win_len;
                   2711:                        c->local_consumed += win_len;
1.200     markus   2712:                }
1.339     markus   2713:                return 0;
1.200     markus   2714:        }
1.41      markus   2715:
1.143     deraadt  2716:        if (compat20) {
1.309     djm      2717:                if (win_len > c->local_maxpacket) {
1.188     itojun   2718:                        logit("channel %d: rcvd big packet %d, maxpack %d",
1.309     djm      2719:                            c->self, win_len, c->local_maxpacket);
1.44      markus   2720:                }
1.309     djm      2721:                if (win_len > c->local_window) {
1.188     itojun   2722:                        logit("channel %d: rcvd too much data %d, win %d",
1.309     djm      2723:                            c->self, win_len, c->local_window);
1.339     markus   2724:                        return 0;
1.44      markus   2725:                }
1.309     djm      2726:                c->local_window -= win_len;
1.44      markus   2727:        }
1.228     reyk     2728:        if (c->datagram)
                   2729:                buffer_put_string(&c->output, data, data_len);
                   2730:        else
                   2731:                buffer_append(&c->output, data, data_len);
1.274     markus   2732:        packet_check_eom();
1.339     markus   2733:        return 0;
1.1       deraadt  2734: }
1.121     markus   2735:
1.249     djm      2736: /* ARGSUSED */
1.339     markus   2737: int
1.154     markus   2738: channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
1.44      markus   2739: {
                   2740:        int id;
                   2741:        char *data;
1.177     markus   2742:        u_int data_len, tcode;
1.44      markus   2743:        Channel *c;
                   2744:
                   2745:        /* Get the channel number and verify it. */
                   2746:        id = packet_get_int();
                   2747:        c = channel_lookup(id);
                   2748:
                   2749:        if (c == NULL)
                   2750:                packet_disconnect("Received extended_data for bad channel %d.", id);
1.354   ! markus   2751:        if (channel_proxy_upstream(c, type, seq, ctxt))
        !          2752:                return 0;
1.44      markus   2753:        if (c->type != SSH_CHANNEL_OPEN) {
1.188     itojun   2754:                logit("channel %d: ext data for non open", id);
1.339     markus   2755:                return 0;
1.172     markus   2756:        }
                   2757:        if (c->flags & CHAN_EOF_RCVD) {
                   2758:                if (datafellows & SSH_BUG_EXTEOF)
                   2759:                        debug("channel %d: accepting ext data after eof", id);
                   2760:                else
                   2761:                        packet_disconnect("Received extended_data after EOF "
                   2762:                            "on channel %d.", id);
1.44      markus   2763:        }
                   2764:        tcode = packet_get_int();
                   2765:        if (c->efd == -1 ||
                   2766:            c->extended_usage != CHAN_EXTENDED_WRITE ||
                   2767:            tcode != SSH2_EXTENDED_DATA_STDERR) {
1.188     itojun   2768:                logit("channel %d: bad ext data", c->self);
1.339     markus   2769:                return 0;
1.44      markus   2770:        }
                   2771:        data = packet_get_string(&data_len);
1.152     markus   2772:        packet_check_eom();
1.44      markus   2773:        if (data_len > c->local_window) {
1.188     itojun   2774:                logit("channel %d: rcvd too much extended_data %d, win %d",
1.44      markus   2775:                    c->self, data_len, c->local_window);
1.321     djm      2776:                free(data);
1.339     markus   2777:                return 0;
1.44      markus   2778:        }
1.70      markus   2779:        debug2("channel %d: rcvd ext data %d", c->self, data_len);
1.44      markus   2780:        c->local_window -= data_len;
                   2781:        buffer_append(&c->extended, data, data_len);
1.321     djm      2782:        free(data);
1.339     markus   2783:        return 0;
1.44      markus   2784: }
                   2785:
1.249     djm      2786: /* ARGSUSED */
1.339     markus   2787: int
1.154     markus   2788: channel_input_ieof(int type, u_int32_t seq, void *ctxt)
1.41      markus   2789: {
                   2790:        int id;
                   2791:        Channel *c;
                   2792:
                   2793:        id = packet_get_int();
1.152     markus   2794:        packet_check_eom();
1.41      markus   2795:        c = channel_lookup(id);
                   2796:        if (c == NULL)
                   2797:                packet_disconnect("Received ieof for nonexistent channel %d.", id);
1.354   ! markus   2798:        if (channel_proxy_upstream(c, type, seq, ctxt))
        !          2799:                return 0;
1.41      markus   2800:        chan_rcvd_ieof(c);
1.133     markus   2801:
                   2802:        /* XXX force input close */
1.156     markus   2803:        if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
1.133     markus   2804:                debug("channel %d: FORCE input drain", c->self);
                   2805:                c->istate = CHAN_INPUT_WAIT_DRAIN;
1.161     markus   2806:                if (buffer_len(&c->input) == 0)
                   2807:                        chan_ibuf_empty(c);
1.133     markus   2808:        }
1.339     markus   2809:        return 0;
1.41      markus   2810: }
1.1       deraadt  2811:
1.249     djm      2812: /* ARGSUSED */
1.339     markus   2813: int
1.154     markus   2814: channel_input_close(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2815: {
1.41      markus   2816:        int id;
                   2817:        Channel *c;
1.1       deraadt  2818:
1.41      markus   2819:        id = packet_get_int();
1.152     markus   2820:        packet_check_eom();
1.41      markus   2821:        c = channel_lookup(id);
                   2822:        if (c == NULL)
                   2823:                packet_disconnect("Received close for nonexistent channel %d.", id);
1.354   ! markus   2824:        if (channel_proxy_upstream(c, type, seq, ctxt))
        !          2825:                return 0;
1.27      markus   2826:        /*
                   2827:         * Send a confirmation that we have closed the channel and no more
                   2828:         * data is coming for it.
                   2829:         */
1.25      markus   2830:        packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1.41      markus   2831:        packet_put_int(c->remote_id);
1.25      markus   2832:        packet_send();
                   2833:
1.27      markus   2834:        /*
                   2835:         * If the channel is in closed state, we have sent a close request,
                   2836:         * and the other side will eventually respond with a confirmation.
                   2837:         * Thus, we cannot free the channel here, because then there would be
                   2838:         * no-one to receive the confirmation.  The channel gets freed when
                   2839:         * the confirmation arrives.
                   2840:         */
1.41      markus   2841:        if (c->type != SSH_CHANNEL_CLOSED) {
1.27      markus   2842:                /*
                   2843:                 * Not a closed channel - mark it as draining, which will
                   2844:                 * cause it to be freed later.
                   2845:                 */
1.158     markus   2846:                buffer_clear(&c->input);
1.41      markus   2847:                c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1.25      markus   2848:        }
1.339     markus   2849:        return 0;
1.1       deraadt  2850: }
                   2851:
1.41      markus   2852: /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1.249     djm      2853: /* ARGSUSED */
1.339     markus   2854: int
1.154     markus   2855: channel_input_oclose(int type, u_int32_t seq, void *ctxt)
1.41      markus   2856: {
                   2857:        int id = packet_get_int();
                   2858:        Channel *c = channel_lookup(id);
1.151     markus   2859:
1.41      markus   2860:        if (c == NULL)
                   2861:                packet_disconnect("Received oclose for nonexistent channel %d.", id);
1.354   ! markus   2862:        if (channel_proxy_upstream(c, type, seq, ctxt))
        !          2863:                return 0;
        !          2864:        packet_check_eom();
1.41      markus   2865:        chan_rcvd_oclose(c);
1.339     markus   2866:        return 0;
1.41      markus   2867: }
1.1       deraadt  2868:
1.249     djm      2869: /* ARGSUSED */
1.339     markus   2870: int
1.154     markus   2871: channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2872: {
1.41      markus   2873:        int id = packet_get_int();
                   2874:        Channel *c = channel_lookup(id);
1.1       deraadt  2875:
1.41      markus   2876:        if (c == NULL)
                   2877:                packet_disconnect("Received close confirmation for "
                   2878:                    "out-of-range channel %d.", id);
1.354   ! markus   2879:        if (channel_proxy_upstream(c, type, seq, ctxt))
        !          2880:                return 0;
        !          2881:        packet_check_eom();
1.323     dtucker  2882:        if (c->type != SSH_CHANNEL_CLOSED && c->type != SSH_CHANNEL_ABANDONED)
1.41      markus   2883:                packet_disconnect("Received close confirmation for "
                   2884:                    "non-closed channel %d (type %d).", id, c->type);
1.113     markus   2885:        channel_free(c);
1.339     markus   2886:        return 0;
1.1       deraadt  2887: }
                   2888:
1.249     djm      2889: /* ARGSUSED */
1.339     markus   2890: int
1.154     markus   2891: channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2892: {
1.41      markus   2893:        int id, remote_id;
                   2894:        Channel *c;
1.1       deraadt  2895:
1.41      markus   2896:        id = packet_get_int();
                   2897:        c = channel_lookup(id);
1.25      markus   2898:
1.354   ! markus   2899:        if (c==NULL)
        !          2900:                packet_disconnect("Received open confirmation for "
        !          2901:                    "unknown channel %d.", id);
        !          2902:        if (channel_proxy_upstream(c, type, seq, ctxt))
        !          2903:                return 0;
        !          2904:        if (c->type != SSH_CHANNEL_OPENING)
1.41      markus   2905:                packet_disconnect("Received open confirmation for "
                   2906:                    "non-opening channel %d.", id);
                   2907:        remote_id = packet_get_int();
1.27      markus   2908:        /* Record the remote channel number and mark that the channel is now open. */
1.41      markus   2909:        c->remote_id = remote_id;
                   2910:        c->type = SSH_CHANNEL_OPEN;
1.44      markus   2911:
                   2912:        if (compat20) {
                   2913:                c->remote_window = packet_get_int();
                   2914:                c->remote_maxpacket = packet_get_int();
1.275     djm      2915:                if (c->open_confirm) {
1.70      markus   2916:                        debug2("callback start");
1.304     djm      2917:                        c->open_confirm(c->self, 1, c->open_confirm_ctx);
1.70      markus   2918:                        debug2("callback done");
1.44      markus   2919:                }
1.194     markus   2920:                debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
1.44      markus   2921:                    c->remote_window, c->remote_maxpacket);
                   2922:        }
1.152     markus   2923:        packet_check_eom();
1.339     markus   2924:        return 0;
1.1       deraadt  2925: }
                   2926:
1.127     itojun   2927: static char *
1.114     markus   2928: reason2txt(int reason)
                   2929: {
1.143     deraadt  2930:        switch (reason) {
1.114     markus   2931:        case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
                   2932:                return "administratively prohibited";
                   2933:        case SSH2_OPEN_CONNECT_FAILED:
                   2934:                return "connect failed";
                   2935:        case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
                   2936:                return "unknown channel type";
                   2937:        case SSH2_OPEN_RESOURCE_SHORTAGE:
                   2938:                return "resource shortage";
                   2939:        }
1.117     stevesk  2940:        return "unknown reason";
1.114     markus   2941: }
                   2942:
1.249     djm      2943: /* ARGSUSED */
1.339     markus   2944: int
1.154     markus   2945: channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2946: {
1.86      markus   2947:        int id, reason;
                   2948:        char *msg = NULL, *lang = NULL;
1.41      markus   2949:        Channel *c;
                   2950:
                   2951:        id = packet_get_int();
                   2952:        c = channel_lookup(id);
1.25      markus   2953:
1.354   ! markus   2954:        if (c==NULL)
        !          2955:                packet_disconnect("Received open failure for "
        !          2956:                    "unknown channel %d.", id);
        !          2957:        if (channel_proxy_upstream(c, type, seq, ctxt))
        !          2958:                return 0;
        !          2959:        if (c->type != SSH_CHANNEL_OPENING)
1.41      markus   2960:                packet_disconnect("Received open failure for "
                   2961:                    "non-opening channel %d.", id);
1.44      markus   2962:        if (compat20) {
1.86      markus   2963:                reason = packet_get_int();
1.110     markus   2964:                if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1.86      markus   2965:                        msg  = packet_get_string(NULL);
                   2966:                        lang = packet_get_string(NULL);
                   2967:                }
1.188     itojun   2968:                logit("channel %d: open failed: %s%s%s", id,
1.114     markus   2969:                    reason2txt(reason), msg ? ": ": "", msg ? msg : "");
1.321     djm      2970:                free(msg);
                   2971:                free(lang);
1.304     djm      2972:                if (c->open_confirm) {
                   2973:                        debug2("callback start");
                   2974:                        c->open_confirm(c->self, 0, c->open_confirm_ctx);
                   2975:                        debug2("callback done");
                   2976:                }
1.44      markus   2977:        }
1.152     markus   2978:        packet_check_eom();
1.291     djm      2979:        /* Schedule the channel for cleanup/deletion. */
                   2980:        chan_mark_dead(c);
1.339     markus   2981:        return 0;
1.44      markus   2982: }
                   2983:
1.249     djm      2984: /* ARGSUSED */
1.339     markus   2985: int
1.154     markus   2986: channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
1.121     markus   2987: {
                   2988:        Channel *c;
1.178     markus   2989:        int id;
1.346     djm      2990:        u_int adjust, tmp;
1.121     markus   2991:
                   2992:        if (!compat20)
1.339     markus   2993:                return 0;
1.121     markus   2994:
                   2995:        /* Get the channel number and verify it. */
                   2996:        id = packet_get_int();
                   2997:        c = channel_lookup(id);
1.1       deraadt  2998:
1.229     markus   2999:        if (c == NULL) {
                   3000:                logit("Received window adjust for non-open channel %d.", id);
1.339     markus   3001:                return 0;
1.121     markus   3002:        }
1.354   ! markus   3003:        if (channel_proxy_upstream(c, type, seq, ctxt))
        !          3004:                return 0;
1.121     markus   3005:        adjust = packet_get_int();
1.152     markus   3006:        packet_check_eom();
1.178     markus   3007:        debug2("channel %d: rcvd adjust %u", id, adjust);
1.346     djm      3008:        if ((tmp = c->remote_window + adjust) < c->remote_window)
                   3009:                fatal("channel %d: adjust %u overflows remote window %u",
                   3010:                    id, adjust, c->remote_window);
                   3011:        c->remote_window = tmp;
1.339     markus   3012:        return 0;
1.121     markus   3013: }
1.1       deraadt  3014:
1.249     djm      3015: /* ARGSUSED */
1.339     markus   3016: int
1.154     markus   3017: channel_input_port_open(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  3018: {
1.121     markus   3019:        Channel *c = NULL;
                   3020:        u_short host_port;
                   3021:        char *host, *originator_string;
1.276     djm      3022:        int remote_id;
1.121     markus   3023:
                   3024:        remote_id = packet_get_int();
                   3025:        host = packet_get_string(NULL);
                   3026:        host_port = packet_get_int();
1.25      markus   3027:
1.121     markus   3028:        if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
                   3029:                originator_string = packet_get_string(NULL);
                   3030:        } else {
                   3031:                originator_string = xstrdup("unknown (remote did not supply name)");
                   3032:        }
1.152     markus   3033:        packet_check_eom();
1.336     millert  3034:        c = channel_connect_to_port(host, host_port,
1.276     djm      3035:            "connected socket", originator_string);
1.321     djm      3036:        free(originator_string);
                   3037:        free(host);
1.121     markus   3038:        if (c == NULL) {
                   3039:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   3040:                packet_put_int(remote_id);
                   3041:                packet_send();
1.276     djm      3042:        } else
                   3043:                c->remote_id = remote_id;
1.339     markus   3044:        return 0;
1.1       deraadt  3045: }
                   3046:
1.275     djm      3047: /* ARGSUSED */
1.339     markus   3048: int
1.275     djm      3049: channel_input_status_confirm(int type, u_int32_t seq, void *ctxt)
                   3050: {
                   3051:        Channel *c;
                   3052:        struct channel_confirm *cc;
1.289     markus   3053:        int id;
1.275     djm      3054:
                   3055:        /* Reset keepalive timeout */
1.296     andreas  3056:        packet_set_alive_timeouts(0);
1.275     djm      3057:
1.289     markus   3058:        id = packet_get_int();
                   3059:        debug2("channel_input_status_confirm: type %d id %d", type, id);
1.275     djm      3060:
1.289     markus   3061:        if ((c = channel_lookup(id)) == NULL) {
                   3062:                logit("channel_input_status_confirm: %d: unknown", id);
1.339     markus   3063:                return 0;
1.275     djm      3064:        }
1.354   ! markus   3065:        if (channel_proxy_upstream(c, type, seq, ctxt))
        !          3066:                return 0;
        !          3067:        packet_check_eom();
1.275     djm      3068:        if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
1.339     markus   3069:                return 0;
1.275     djm      3070:        cc->cb(type, c, cc->ctx);
                   3071:        TAILQ_REMOVE(&c->status_confirms, cc, entry);
1.329     tedu     3072:        explicit_bzero(cc, sizeof(*cc));
1.321     djm      3073:        free(cc);
1.339     markus   3074:        return 0;
1.275     djm      3075: }
1.121     markus   3076:
                   3077: /* -- tcp forwarding */
1.135     markus   3078:
                   3079: void
                   3080: channel_set_af(int af)
                   3081: {
                   3082:        IPv4or6 = af;
                   3083: }
1.121     markus   3084:
1.312     djm      3085:
                   3086: /*
                   3087:  * Determine whether or not a port forward listens to loopback, the
                   3088:  * specified address or wildcard. On the client, a specified bind
                   3089:  * address will always override gateway_ports. On the server, a
                   3090:  * gateway_ports of 1 (``yes'') will override the client's specification
                   3091:  * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
                   3092:  * will bind to whatever address the client asked for.
                   3093:  *
                   3094:  * Special-case listen_addrs are:
                   3095:  *
                   3096:  * "0.0.0.0"               -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
                   3097:  * "" (empty string), "*"  -> wildcard v4/v6
                   3098:  * "localhost"             -> loopback v4/v6
1.334     djm      3099:  * "127.0.0.1" / "::1"     -> accepted even if gateway_ports isn't set
1.312     djm      3100:  */
                   3101: static const char *
                   3102: channel_fwd_bind_addr(const char *listen_addr, int *wildcardp,
1.336     millert  3103:     int is_client, struct ForwardOptions *fwd_opts)
1.312     djm      3104: {
                   3105:        const char *addr = NULL;
                   3106:        int wildcard = 0;
                   3107:
                   3108:        if (listen_addr == NULL) {
                   3109:                /* No address specified: default to gateway_ports setting */
1.336     millert  3110:                if (fwd_opts->gateway_ports)
1.312     djm      3111:                        wildcard = 1;
1.336     millert  3112:        } else if (fwd_opts->gateway_ports || is_client) {
1.312     djm      3113:                if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
                   3114:                    strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
                   3115:                    *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
1.336     millert  3116:                    (!is_client && fwd_opts->gateway_ports == 1)) {
1.312     djm      3117:                        wildcard = 1;
1.326     djm      3118:                        /*
                   3119:                         * Notify client if they requested a specific listen
                   3120:                         * address and it was overridden.
                   3121:                         */
                   3122:                        if (*listen_addr != '\0' &&
                   3123:                            strcmp(listen_addr, "0.0.0.0") != 0 &&
                   3124:                            strcmp(listen_addr, "*") != 0) {
                   3125:                                packet_send_debug("Forwarding listen address "
                   3126:                                    "\"%s\" overridden by server "
                   3127:                                    "GatewayPorts", listen_addr);
                   3128:                        }
1.334     djm      3129:                } else if (strcmp(listen_addr, "localhost") != 0 ||
                   3130:                    strcmp(listen_addr, "127.0.0.1") == 0 ||
                   3131:                    strcmp(listen_addr, "::1") == 0) {
                   3132:                        /* Accept localhost address when GatewayPorts=yes */
                   3133:                        addr = listen_addr;
1.326     djm      3134:                }
1.334     djm      3135:        } else if (strcmp(listen_addr, "127.0.0.1") == 0 ||
                   3136:            strcmp(listen_addr, "::1") == 0) {
                   3137:                /*
                   3138:                 * If a specific IPv4/IPv6 localhost address has been
                   3139:                 * requested then accept it even if gateway_ports is in
                   3140:                 * effect. This allows the client to prefer IPv4 or IPv6.
                   3141:                 */
                   3142:                addr = listen_addr;
1.312     djm      3143:        }
                   3144:        if (wildcardp != NULL)
                   3145:                *wildcardp = wildcard;
                   3146:        return addr;
                   3147: }
                   3148:
1.160     markus   3149: static int
1.336     millert  3150: channel_setup_fwd_listener_tcpip(int type, struct Forward *fwd,
                   3151:     int *allocated_listen_port, struct ForwardOptions *fwd_opts)
1.25      markus   3152: {
1.113     markus   3153:        Channel *c;
1.226     djm      3154:        int sock, r, success = 0, wildcard = 0, is_client;
1.35      markus   3155:        struct addrinfo hints, *ai, *aitop;
1.212     djm      3156:        const char *host, *addr;
1.35      markus   3157:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1.295     djm      3158:        in_port_t *lport_p;
1.25      markus   3159:
1.212     djm      3160:        is_client = (type == SSH_CHANNEL_PORT_LISTENER);
1.87      markus   3161:
1.344     millert  3162:        if (is_client && fwd->connect_path != NULL) {
                   3163:                host = fwd->connect_path;
                   3164:        } else {
                   3165:                host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
                   3166:                    fwd->listen_host : fwd->connect_host;
                   3167:                if (host == NULL) {
                   3168:                        error("No forward host name.");
                   3169:                        return 0;
                   3170:                }
                   3171:                if (strlen(host) >= NI_MAXHOST) {
                   3172:                        error("Forward host name too long.");
                   3173:                        return 0;
                   3174:                }
1.87      markus   3175:        }
1.25      markus   3176:
1.312     djm      3177:        /* Determine the bind address, cf. channel_fwd_bind_addr() comment */
1.336     millert  3178:        addr = channel_fwd_bind_addr(fwd->listen_host, &wildcard,
                   3179:            is_client, fwd_opts);
                   3180:        debug3("%s: type %d wildcard %d addr %s", __func__,
1.212     djm      3181:            type, wildcard, (addr == NULL) ? "NULL" : addr);
                   3182:
                   3183:        /*
1.35      markus   3184:         * getaddrinfo returns a loopback address if the hostname is
                   3185:         * set to NULL and hints.ai_flags is not AI_PASSIVE
1.28      markus   3186:         */
1.35      markus   3187:        memset(&hints, 0, sizeof(hints));
                   3188:        hints.ai_family = IPv4or6;
1.212     djm      3189:        hints.ai_flags = wildcard ? AI_PASSIVE : 0;
1.35      markus   3190:        hints.ai_socktype = SOCK_STREAM;
1.336     millert  3191:        snprintf(strport, sizeof strport, "%d", fwd->listen_port);
1.212     djm      3192:        if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
                   3193:                if (addr == NULL) {
                   3194:                        /* This really shouldn't happen */
                   3195:                        packet_disconnect("getaddrinfo: fatal error: %s",
1.271     dtucker  3196:                            ssh_gai_strerror(r));
1.212     djm      3197:                } else {
1.336     millert  3198:                        error("%s: getaddrinfo(%.64s): %s", __func__, addr,
1.271     dtucker  3199:                            ssh_gai_strerror(r));
1.212     djm      3200:                }
1.218     markus   3201:                return 0;
1.212     djm      3202:        }
1.295     djm      3203:        if (allocated_listen_port != NULL)
                   3204:                *allocated_listen_port = 0;
1.35      markus   3205:        for (ai = aitop; ai; ai = ai->ai_next) {
1.295     djm      3206:                switch (ai->ai_family) {
                   3207:                case AF_INET:
                   3208:                        lport_p = &((struct sockaddr_in *)ai->ai_addr)->
                   3209:                            sin_port;
                   3210:                        break;
                   3211:                case AF_INET6:
                   3212:                        lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
                   3213:                            sin6_port;
                   3214:                        break;
                   3215:                default:
1.35      markus   3216:                        continue;
1.295     djm      3217:                }
                   3218:                /*
                   3219:                 * If allocating a port for -R forwards, then use the
                   3220:                 * same port for all address families.
                   3221:                 */
1.336     millert  3222:                if (type == SSH_CHANNEL_RPORT_LISTENER && fwd->listen_port == 0 &&
1.295     djm      3223:                    allocated_listen_port != NULL && *allocated_listen_port > 0)
                   3224:                        *lport_p = htons(*allocated_listen_port);
                   3225:
1.35      markus   3226:                if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
                   3227:                    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1.336     millert  3228:                        error("%s: getnameinfo failed", __func__);
1.35      markus   3229:                        continue;
                   3230:                }
                   3231:                /* Create a port to listen for the host. */
1.300     dtucker  3232:                sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1.35      markus   3233:                if (sock < 0) {
                   3234:                        /* this is no error since kernel may not support ipv6 */
                   3235:                        verbose("socket: %.100s", strerror(errno));
                   3236:                        continue;
                   3237:                }
1.226     djm      3238:
                   3239:                channel_set_reuseaddr(sock);
1.182     stevesk  3240:
1.295     djm      3241:                debug("Local forwarding listening on %s port %s.",
                   3242:                    ntop, strport);
1.35      markus   3243:
                   3244:                /* Bind the socket to the address. */
                   3245:                if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   3246:                        /* address can be in use ipv6 address is already bound */
                   3247:                        verbose("bind: %.100s", strerror(errno));
                   3248:                        close(sock);
                   3249:                        continue;
                   3250:                }
                   3251:                /* Start listening for connections on the socket. */
1.199     markus   3252:                if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1.35      markus   3253:                        error("listen: %.100s", strerror(errno));
                   3254:                        close(sock);
                   3255:                        continue;
                   3256:                }
1.295     djm      3257:
                   3258:                /*
1.336     millert  3259:                 * fwd->listen_port == 0 requests a dynamically allocated port -
1.295     djm      3260:                 * record what we got.
                   3261:                 */
1.336     millert  3262:                if (type == SSH_CHANNEL_RPORT_LISTENER && fwd->listen_port == 0 &&
1.295     djm      3263:                    allocated_listen_port != NULL &&
                   3264:                    *allocated_listen_port == 0) {
1.350     djm      3265:                        *allocated_listen_port = get_local_port(sock);
1.295     djm      3266:                        debug("Allocated listen port %d",
                   3267:                            *allocated_listen_port);
                   3268:                }
                   3269:
1.35      markus   3270:                /* Allocate a channel number for the socket. */
1.121     markus   3271:                c = channel_new("port listener", type, sock, sock, -1,
1.51      markus   3272:                    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1.190     markus   3273:                    0, "port listener", 1);
1.293     djm      3274:                c->path = xstrdup(host);
1.336     millert  3275:                c->host_port = fwd->connect_port;
1.312     djm      3276:                c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
1.336     millert  3277:                if (fwd->listen_port == 0 && allocated_listen_port != NULL &&
1.315     markus   3278:                    !(datafellows & SSH_BUG_DYNAMIC_RPORT))
                   3279:                        c->listening_port = *allocated_listen_port;
                   3280:                else
1.336     millert  3281:                        c->listening_port = fwd->listen_port;
1.35      markus   3282:                success = 1;
                   3283:        }
                   3284:        if (success == 0)
1.336     millert  3285:                error("%s: cannot listen to port: %d", __func__,
                   3286:                    fwd->listen_port);
1.35      markus   3287:        freeaddrinfo(aitop);
1.87      markus   3288:        return success;
1.25      markus   3289: }
1.1       deraadt  3290:
1.336     millert  3291: static int
                   3292: channel_setup_fwd_listener_streamlocal(int type, struct Forward *fwd,
                   3293:     struct ForwardOptions *fwd_opts)
                   3294: {
                   3295:        struct sockaddr_un sunaddr;
                   3296:        const char *path;
                   3297:        Channel *c;
                   3298:        int port, sock;
                   3299:        mode_t omask;
                   3300:
                   3301:        switch (type) {
                   3302:        case SSH_CHANNEL_UNIX_LISTENER:
                   3303:                if (fwd->connect_path != NULL) {
                   3304:                        if (strlen(fwd->connect_path) > sizeof(sunaddr.sun_path)) {
                   3305:                                error("Local connecting path too long: %s",
                   3306:                                    fwd->connect_path);
                   3307:                                return 0;
                   3308:                        }
                   3309:                        path = fwd->connect_path;
                   3310:                        port = PORT_STREAMLOCAL;
                   3311:                } else {
                   3312:                        if (fwd->connect_host == NULL) {
                   3313:                                error("No forward host name.");
                   3314:                                return 0;
                   3315:                        }
                   3316:                        if (strlen(fwd->connect_host) >= NI_MAXHOST) {
                   3317:                                error("Forward host name too long.");
                   3318:                                return 0;
                   3319:                        }
                   3320:                        path = fwd->connect_host;
                   3321:                        port = fwd->connect_port;
                   3322:                }
                   3323:                break;
                   3324:        case SSH_CHANNEL_RUNIX_LISTENER:
                   3325:                path = fwd->listen_path;
                   3326:                port = PORT_STREAMLOCAL;
                   3327:                break;
                   3328:        default:
                   3329:                error("%s: unexpected channel type %d", __func__, type);
                   3330:                return 0;
                   3331:        }
                   3332:
                   3333:        if (fwd->listen_path == NULL) {
                   3334:                error("No forward path name.");
                   3335:                return 0;
                   3336:        }
                   3337:        if (strlen(fwd->listen_path) > sizeof(sunaddr.sun_path)) {
                   3338:                error("Local listening path too long: %s", fwd->listen_path);
                   3339:                return 0;
                   3340:        }
                   3341:
                   3342:        debug3("%s: type %d path %s", __func__, type, fwd->listen_path);
                   3343:
                   3344:        /* Start a Unix domain listener. */
                   3345:        omask = umask(fwd_opts->streamlocal_bind_mask);
                   3346:        sock = unix_listener(fwd->listen_path, SSH_LISTEN_BACKLOG,
                   3347:            fwd_opts->streamlocal_bind_unlink);
                   3348:        umask(omask);
                   3349:        if (sock < 0)
                   3350:                return 0;
                   3351:
                   3352:        debug("Local forwarding listening on path %s.", fwd->listen_path);
                   3353:
                   3354:        /* Allocate a channel number for the socket. */
                   3355:        c = channel_new("unix listener", type, sock, sock, -1,
                   3356:            CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
                   3357:            0, "unix listener", 1);
                   3358:        c->path = xstrdup(path);
                   3359:        c->host_port = port;
                   3360:        c->listening_port = PORT_STREAMLOCAL;
                   3361:        c->listening_addr = xstrdup(fwd->listen_path);
                   3362:        return 1;
                   3363: }
                   3364:
                   3365: static int
                   3366: channel_cancel_rport_listener_tcpip(const char *host, u_short port)
1.202     djm      3367: {
1.209     avsm     3368:        u_int i;
                   3369:        int found = 0;
1.202     djm      3370:
1.213     deraadt  3371:        for (i = 0; i < channels_alloc; i++) {
1.202     djm      3372:                Channel *c = channels[i];
1.312     djm      3373:                if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
                   3374:                        continue;
                   3375:                if (strcmp(c->path, host) == 0 && c->listening_port == port) {
                   3376:                        debug2("%s: close channel %d", __func__, i);
                   3377:                        channel_free(c);
                   3378:                        found = 1;
                   3379:                }
                   3380:        }
                   3381:
                   3382:        return (found);
                   3383: }
                   3384:
1.336     millert  3385: static int
                   3386: channel_cancel_rport_listener_streamlocal(const char *path)
                   3387: {
                   3388:        u_int i;
                   3389:        int found = 0;
                   3390:
                   3391:        for (i = 0; i < channels_alloc; i++) {
                   3392:                Channel *c = channels[i];
                   3393:                if (c == NULL || c->type != SSH_CHANNEL_RUNIX_LISTENER)
                   3394:                        continue;
                   3395:                if (c->path == NULL)
                   3396:                        continue;
                   3397:                if (strcmp(c->path, path) == 0) {
                   3398:                        debug2("%s: close channel %d", __func__, i);
                   3399:                        channel_free(c);
                   3400:                        found = 1;
                   3401:                }
                   3402:        }
                   3403:
                   3404:        return (found);
                   3405: }
                   3406:
1.312     djm      3407: int
1.336     millert  3408: channel_cancel_rport_listener(struct Forward *fwd)
                   3409: {
                   3410:        if (fwd->listen_path != NULL)
                   3411:                return channel_cancel_rport_listener_streamlocal(fwd->listen_path);
                   3412:        else
                   3413:                return channel_cancel_rport_listener_tcpip(fwd->listen_host, fwd->listen_port);
                   3414: }
                   3415:
                   3416: static int
                   3417: channel_cancel_lport_listener_tcpip(const char *lhost, u_short lport,
                   3418:     int cport, struct ForwardOptions *fwd_opts)
1.312     djm      3419: {
                   3420:        u_int i;
                   3421:        int found = 0;
1.336     millert  3422:        const char *addr = channel_fwd_bind_addr(lhost, NULL, 1, fwd_opts);
1.202     djm      3423:
1.312     djm      3424:        for (i = 0; i < channels_alloc; i++) {
                   3425:                Channel *c = channels[i];
                   3426:                if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
                   3427:                        continue;
1.313     markus   3428:                if (c->listening_port != lport)
1.312     djm      3429:                        continue;
1.313     markus   3430:                if (cport == CHANNEL_CANCEL_PORT_STATIC) {
                   3431:                        /* skip dynamic forwardings */
                   3432:                        if (c->host_port == 0)
                   3433:                                continue;
                   3434:                } else {
                   3435:                        if (c->host_port != cport)
                   3436:                                continue;
                   3437:                }
1.312     djm      3438:                if ((c->listening_addr == NULL && addr != NULL) ||
                   3439:                    (c->listening_addr != NULL && addr == NULL))
                   3440:                        continue;
                   3441:                if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
1.210     djm      3442:                        debug2("%s: close channel %d", __func__, i);
1.202     djm      3443:                        channel_free(c);
                   3444:                        found = 1;
                   3445:                }
                   3446:        }
                   3447:
                   3448:        return (found);
                   3449: }
                   3450:
1.336     millert  3451: static int
                   3452: channel_cancel_lport_listener_streamlocal(const char *path)
                   3453: {
                   3454:        u_int i;
                   3455:        int found = 0;
                   3456:
                   3457:        if (path == NULL) {
                   3458:                error("%s: no path specified.", __func__);
                   3459:                return 0;
                   3460:        }
                   3461:
                   3462:        for (i = 0; i < channels_alloc; i++) {
                   3463:                Channel *c = channels[i];
                   3464:                if (c == NULL || c->type != SSH_CHANNEL_UNIX_LISTENER)
                   3465:                        continue;
                   3466:                if (c->listening_addr == NULL)
                   3467:                        continue;
                   3468:                if (strcmp(c->listening_addr, path) == 0) {
                   3469:                        debug2("%s: close channel %d", __func__, i);
                   3470:                        channel_free(c);
                   3471:                        found = 1;
                   3472:                }
                   3473:        }
                   3474:
                   3475:        return (found);
                   3476: }
                   3477:
                   3478: int
                   3479: channel_cancel_lport_listener(struct Forward *fwd, int cport, struct ForwardOptions *fwd_opts)
                   3480: {
                   3481:        if (fwd->listen_path != NULL)
                   3482:                return channel_cancel_lport_listener_streamlocal(fwd->listen_path);
                   3483:        else
                   3484:                return channel_cancel_lport_listener_tcpip(fwd->listen_host, fwd->listen_port, cport, fwd_opts);
                   3485: }
                   3486:
1.160     markus   3487: /* protocol local port fwd, used by ssh (and sshd in v1) */
                   3488: int
1.336     millert  3489: channel_setup_local_fwd_listener(struct Forward *fwd, struct ForwardOptions *fwd_opts)
1.160     markus   3490: {
1.336     millert  3491:        if (fwd->listen_path != NULL) {
                   3492:                return channel_setup_fwd_listener_streamlocal(
                   3493:                    SSH_CHANNEL_UNIX_LISTENER, fwd, fwd_opts);
                   3494:        } else {
                   3495:                return channel_setup_fwd_listener_tcpip(SSH_CHANNEL_PORT_LISTENER,
                   3496:                    fwd, NULL, fwd_opts);
                   3497:        }
1.160     markus   3498: }
                   3499:
                   3500: /* protocol v2 remote port fwd, used by sshd */
                   3501: int
1.336     millert  3502: channel_setup_remote_fwd_listener(struct Forward *fwd,
                   3503:     int *allocated_listen_port, struct ForwardOptions *fwd_opts)
1.160     markus   3504: {
1.336     millert  3505:        if (fwd->listen_path != NULL) {
                   3506:                return channel_setup_fwd_listener_streamlocal(
                   3507:                    SSH_CHANNEL_RUNIX_LISTENER, fwd, fwd_opts);
                   3508:        } else {
                   3509:                return channel_setup_fwd_listener_tcpip(
                   3510:                    SSH_CHANNEL_RPORT_LISTENER, fwd, allocated_listen_port,
                   3511:                    fwd_opts);
                   3512:        }
1.160     markus   3513: }
                   3514:
1.27      markus   3515: /*
1.312     djm      3516:  * Translate the requested rfwd listen host to something usable for
                   3517:  * this server.
                   3518:  */
                   3519: static const char *
                   3520: channel_rfwd_bind_host(const char *listen_host)
                   3521: {
                   3522:        if (listen_host == NULL) {
                   3523:                if (datafellows & SSH_BUG_RFWD_ADDR)
                   3524:                        return "127.0.0.1";
                   3525:                else
                   3526:                        return "localhost";
                   3527:        } else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
                   3528:                if (datafellows & SSH_BUG_RFWD_ADDR)
                   3529:                        return "0.0.0.0";
                   3530:                else
                   3531:                        return "";
                   3532:        } else
                   3533:                return listen_host;
                   3534: }
                   3535:
                   3536: /*
1.27      markus   3537:  * Initiate forwarding of connections to port "port" on remote host through
                   3538:  * the secure channel to host:port from local side.
1.315     markus   3539:  * Returns handle (index) for updating the dynamic listen port with
                   3540:  * channel_update_permitted_opens().
1.27      markus   3541:  */
1.253     markus   3542: int
1.336     millert  3543: channel_request_remote_forwarding(struct Forward *fwd)
1.25      markus   3544: {
1.315     markus   3545:        int type, success = 0, idx = -1;
1.73      markus   3546:
1.25      markus   3547:        /* Send the forward request to the remote side. */
1.44      markus   3548:        if (compat20) {
                   3549:                packet_start(SSH2_MSG_GLOBAL_REQUEST);
1.336     millert  3550:                if (fwd->listen_path != NULL) {
                   3551:                    packet_put_cstring("streamlocal-forward@openssh.com");
                   3552:                    packet_put_char(1);         /* boolean: want reply */
                   3553:                    packet_put_cstring(fwd->listen_path);
                   3554:                } else {
                   3555:                    packet_put_cstring("tcpip-forward");
                   3556:                    packet_put_char(1);         /* boolean: want reply */
                   3557:                    packet_put_cstring(channel_rfwd_bind_host(fwd->listen_host));
                   3558:                    packet_put_int(fwd->listen_port);
                   3559:                }
1.73      markus   3560:                packet_send();
                   3561:                packet_write_wait();
                   3562:                /* Assume that server accepts the request */
                   3563:                success = 1;
1.336     millert  3564:        } else if (fwd->listen_path == NULL) {
1.44      markus   3565:                packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1.336     millert  3566:                packet_put_int(fwd->listen_port);
                   3567:                packet_put_cstring(fwd->connect_host);
                   3568:                packet_put_int(fwd->connect_port);
1.44      markus   3569:                packet_send();
                   3570:                packet_write_wait();
1.73      markus   3571:
                   3572:                /* Wait for response from the remote side. */
1.153     markus   3573:                type = packet_read();
1.73      markus   3574:                switch (type) {
                   3575:                case SSH_SMSG_SUCCESS:
                   3576:                        success = 1;
                   3577:                        break;
                   3578:                case SSH_SMSG_FAILURE:
                   3579:                        break;
                   3580:                default:
                   3581:                        /* Unknown packet */
                   3582:                        packet_disconnect("Protocol error for port forward request:"
                   3583:                            "received packet type %d.", type);
                   3584:                }
1.336     millert  3585:        } else {
                   3586:                logit("Warning: Server does not support remote stream local forwarding.");
1.73      markus   3587:        }
                   3588:        if (success) {
1.305     djm      3589:                /* Record that connection to this host/port is permitted. */
1.342     deraadt  3590:                permitted_opens = xreallocarray(permitted_opens,
1.305     djm      3591:                    num_permitted_opens + 1, sizeof(*permitted_opens));
1.315     markus   3592:                idx = num_permitted_opens++;
1.336     millert  3593:                if (fwd->connect_path != NULL) {
                   3594:                        permitted_opens[idx].host_to_connect =
                   3595:                            xstrdup(fwd->connect_path);
                   3596:                        permitted_opens[idx].port_to_connect =
                   3597:                            PORT_STREAMLOCAL;
                   3598:                } else {
                   3599:                        permitted_opens[idx].host_to_connect =
                   3600:                            xstrdup(fwd->connect_host);
                   3601:                        permitted_opens[idx].port_to_connect =
                   3602:                            fwd->connect_port;
                   3603:                }
                   3604:                if (fwd->listen_path != NULL) {
                   3605:                        permitted_opens[idx].listen_host = NULL;
                   3606:                        permitted_opens[idx].listen_path =
                   3607:                            xstrdup(fwd->listen_path);
                   3608:                        permitted_opens[idx].listen_port = PORT_STREAMLOCAL;
                   3609:                } else {
                   3610:                        permitted_opens[idx].listen_host =
                   3611:                            fwd->listen_host ? xstrdup(fwd->listen_host) : NULL;
                   3612:                        permitted_opens[idx].listen_path = NULL;
                   3613:                        permitted_opens[idx].listen_port = fwd->listen_port;
                   3614:                }
1.354   ! markus   3615:                permitted_opens[idx].downstream = NULL;
1.44      markus   3616:        }
1.315     markus   3617:        return (idx);
1.1       deraadt  3618: }
                   3619:
1.333     markus   3620: static int
                   3621: open_match(ForwardPermission *allowed_open, const char *requestedhost,
1.336     millert  3622:     int requestedport)
1.333     markus   3623: {
                   3624:        if (allowed_open->host_to_connect == NULL)
                   3625:                return 0;
                   3626:        if (allowed_open->port_to_connect != FWD_PERMIT_ANY_PORT &&
                   3627:            allowed_open->port_to_connect != requestedport)
                   3628:                return 0;
1.351     dtucker  3629:        if (strcmp(allowed_open->host_to_connect, FWD_PERMIT_ANY_HOST) != 0 &&
                   3630:            strcmp(allowed_open->host_to_connect, requestedhost) != 0)
1.333     markus   3631:                return 0;
                   3632:        return 1;
                   3633: }
                   3634:
                   3635: /*
1.336     millert  3636:  * Note that in the listen host/port case
1.333     markus   3637:  * we don't support FWD_PERMIT_ANY_PORT and
                   3638:  * need to translate between the configured-host (listen_host)
                   3639:  * and what we've sent to the remote server (channel_rfwd_bind_host)
                   3640:  */
                   3641: static int
1.336     millert  3642: open_listen_match_tcpip(ForwardPermission *allowed_open,
                   3643:     const char *requestedhost, u_short requestedport, int translate)
1.333     markus   3644: {
                   3645:        const char *allowed_host;
                   3646:
                   3647:        if (allowed_open->host_to_connect == NULL)
                   3648:                return 0;
                   3649:        if (allowed_open->listen_port != requestedport)
                   3650:                return 0;
1.335     djm      3651:        if (!translate && allowed_open->listen_host == NULL &&
                   3652:            requestedhost == NULL)
                   3653:                return 1;
1.333     markus   3654:        allowed_host = translate ?
                   3655:            channel_rfwd_bind_host(allowed_open->listen_host) :
                   3656:            allowed_open->listen_host;
                   3657:        if (allowed_host == NULL ||
                   3658:            strcmp(allowed_host, requestedhost) != 0)
                   3659:                return 0;
                   3660:        return 1;
                   3661: }
                   3662:
1.336     millert  3663: static int
                   3664: open_listen_match_streamlocal(ForwardPermission *allowed_open,
                   3665:     const char *requestedpath)
                   3666: {
                   3667:        if (allowed_open->host_to_connect == NULL)
                   3668:                return 0;
                   3669:        if (allowed_open->listen_port != PORT_STREAMLOCAL)
                   3670:                return 0;
                   3671:        if (allowed_open->listen_path == NULL ||
                   3672:            strcmp(allowed_open->listen_path, requestedpath) != 0)
                   3673:                return 0;
                   3674:        return 1;
                   3675: }
                   3676:
1.27      markus   3677: /*
1.208     deraadt  3678:  * Request cancellation of remote forwarding of connection host:port from
1.202     djm      3679:  * local side.
                   3680:  */
1.336     millert  3681: static int
                   3682: channel_request_rforward_cancel_tcpip(const char *host, u_short port)
1.202     djm      3683: {
                   3684:        int i;
                   3685:
                   3686:        if (!compat20)
1.312     djm      3687:                return -1;
1.202     djm      3688:
                   3689:        for (i = 0; i < num_permitted_opens; i++) {
1.336     millert  3690:                if (open_listen_match_tcpip(&permitted_opens[i], host, port, 0))
1.202     djm      3691:                        break;
                   3692:        }
                   3693:        if (i >= num_permitted_opens) {
                   3694:                debug("%s: requested forward not found", __func__);
1.312     djm      3695:                return -1;
1.202     djm      3696:        }
                   3697:        packet_start(SSH2_MSG_GLOBAL_REQUEST);
                   3698:        packet_put_cstring("cancel-tcpip-forward");
                   3699:        packet_put_char(0);
1.312     djm      3700:        packet_put_cstring(channel_rfwd_bind_host(host));
1.202     djm      3701:        packet_put_int(port);
                   3702:        packet_send();
                   3703:
1.336     millert  3704:        permitted_opens[i].listen_port = 0;
1.333     markus   3705:        permitted_opens[i].port_to_connect = 0;
1.336     millert  3706:        free(permitted_opens[i].host_to_connect);
                   3707:        permitted_opens[i].host_to_connect = NULL;
                   3708:        free(permitted_opens[i].listen_host);
                   3709:        permitted_opens[i].listen_host = NULL;
                   3710:        permitted_opens[i].listen_path = NULL;
1.354   ! markus   3711:        permitted_opens[i].downstream = NULL;
1.336     millert  3712:
                   3713:        return 0;
                   3714: }
                   3715:
                   3716: /*
                   3717:  * Request cancellation of remote forwarding of Unix domain socket
                   3718:  * path from local side.
                   3719:  */
                   3720: static int
                   3721: channel_request_rforward_cancel_streamlocal(const char *path)
                   3722: {
                   3723:        int i;
                   3724:
                   3725:        if (!compat20)
                   3726:                return -1;
                   3727:
                   3728:        for (i = 0; i < num_permitted_opens; i++) {
                   3729:                if (open_listen_match_streamlocal(&permitted_opens[i], path))
                   3730:                        break;
                   3731:        }
                   3732:        if (i >= num_permitted_opens) {
                   3733:                debug("%s: requested forward not found", __func__);
                   3734:                return -1;
                   3735:        }
                   3736:        packet_start(SSH2_MSG_GLOBAL_REQUEST);
                   3737:        packet_put_cstring("cancel-streamlocal-forward@openssh.com");
                   3738:        packet_put_char(0);
                   3739:        packet_put_cstring(path);
                   3740:        packet_send();
                   3741:
1.202     djm      3742:        permitted_opens[i].listen_port = 0;
1.336     millert  3743:        permitted_opens[i].port_to_connect = 0;
1.321     djm      3744:        free(permitted_opens[i].host_to_connect);
1.202     djm      3745:        permitted_opens[i].host_to_connect = NULL;
1.333     markus   3746:        permitted_opens[i].listen_host = NULL;
1.336     millert  3747:        free(permitted_opens[i].listen_path);
                   3748:        permitted_opens[i].listen_path = NULL;
1.354   ! markus   3749:        permitted_opens[i].downstream = NULL;
1.312     djm      3750:
                   3751:        return 0;
1.202     djm      3752: }
                   3753:
                   3754: /*
1.336     millert  3755:  * Request cancellation of remote forwarding of a connection from local side.
                   3756:  */
                   3757: int
                   3758: channel_request_rforward_cancel(struct Forward *fwd)
                   3759: {
                   3760:        if (fwd->listen_path != NULL) {
                   3761:                return (channel_request_rforward_cancel_streamlocal(
                   3762:                    fwd->listen_path));
                   3763:        } else {
                   3764:                return (channel_request_rforward_cancel_tcpip(fwd->listen_host,
                   3765:                    fwd->listen_port ? fwd->listen_port : fwd->allocated_port));
                   3766:        }
                   3767: }
                   3768:
                   3769: /*
1.27      markus   3770:  * This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
                   3771:  * listening for the port, and sends back a success reply (or disconnect
1.253     markus   3772:  * message if there was an error).
1.27      markus   3773:  */
1.253     markus   3774: int
1.336     millert  3775: channel_input_port_forward_request(int is_root, struct ForwardOptions *fwd_opts)
1.1       deraadt  3776: {
1.253     markus   3777:        int success = 0;
1.336     millert  3778:        struct Forward fwd;
1.1       deraadt  3779:
1.25      markus   3780:        /* Get arguments from the packet. */
1.336     millert  3781:        memset(&fwd, 0, sizeof(fwd));
                   3782:        fwd.listen_port = packet_get_int();
                   3783:        fwd.connect_host = packet_get_string(NULL);
                   3784:        fwd.connect_port = packet_get_int();
1.25      markus   3785:
1.27      markus   3786:        /*
                   3787:         * Check that an unprivileged user is not trying to forward a
                   3788:         * privileged port.
                   3789:         */
1.336     millert  3790:        if (fwd.listen_port < IPPORT_RESERVED && !is_root)
1.192     markus   3791:                packet_disconnect(
                   3792:                    "Requested forwarding of port %d but user is not root.",
1.336     millert  3793:                    fwd.listen_port);
                   3794:        if (fwd.connect_port == 0)
1.192     markus   3795:                packet_disconnect("Dynamic forwarding denied.");
                   3796:
1.73      markus   3797:        /* Initiate forwarding */
1.336     millert  3798:        success = channel_setup_local_fwd_listener(&fwd, fwd_opts);
1.25      markus   3799:
                   3800:        /* Free the argument string. */
1.336     millert  3801:        free(fwd.connect_host);
1.253     markus   3802:
                   3803:        return (success ? 0 : -1);
1.1       deraadt  3804: }
                   3805:
1.99      markus   3806: /*
                   3807:  * Permits opening to any host/port if permitted_opens[] is empty.  This is
                   3808:  * usually called by the server, because the user could connect to any port
                   3809:  * anyway, and the server has no way to know but to trust the client anyway.
                   3810:  */
                   3811: void
1.142     itojun   3812: channel_permit_all_opens(void)
1.99      markus   3813: {
                   3814:        if (num_permitted_opens == 0)
                   3815:                all_opens_permitted = 1;
                   3816: }
                   3817:
1.101     markus   3818: void
1.99      markus   3819: channel_add_permitted_opens(char *host, int port)
                   3820: {
                   3821:        debug("allow port forwarding to host %s port %d", host, port);
                   3822:
1.342     deraadt  3823:        permitted_opens = xreallocarray(permitted_opens,
1.305     djm      3824:            num_permitted_opens + 1, sizeof(*permitted_opens));
1.99      markus   3825:        permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
                   3826:        permitted_opens[num_permitted_opens].port_to_connect = port;
1.333     markus   3827:        permitted_opens[num_permitted_opens].listen_host = NULL;
1.336     millert  3828:        permitted_opens[num_permitted_opens].listen_path = NULL;
1.333     markus   3829:        permitted_opens[num_permitted_opens].listen_port = 0;
1.354   ! markus   3830:        permitted_opens[num_permitted_opens].downstream = NULL;
1.99      markus   3831:        num_permitted_opens++;
                   3832:
                   3833:        all_opens_permitted = 0;
1.315     markus   3834: }
                   3835:
                   3836: /*
                   3837:  * Update the listen port for a dynamic remote forward, after
                   3838:  * the actual 'newport' has been allocated. If 'newport' < 0 is
                   3839:  * passed then they entry will be invalidated.
                   3840:  */
                   3841: void
                   3842: channel_update_permitted_opens(int idx, int newport)
                   3843: {
                   3844:        if (idx < 0 || idx >= num_permitted_opens) {
                   3845:                debug("channel_update_permitted_opens: index out of range:"
                   3846:                    " %d num_permitted_opens %d", idx, num_permitted_opens);
                   3847:                return;
                   3848:        }
                   3849:        debug("%s allowed port %d for forwarding to host %s port %d",
                   3850:            newport > 0 ? "Updating" : "Removing",
                   3851:            newport,
                   3852:            permitted_opens[idx].host_to_connect,
                   3853:            permitted_opens[idx].port_to_connect);
                   3854:        if (newport >= 0)  {
                   3855:                permitted_opens[idx].listen_port =
                   3856:                    (datafellows & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
                   3857:        } else {
                   3858:                permitted_opens[idx].listen_port = 0;
                   3859:                permitted_opens[idx].port_to_connect = 0;
1.321     djm      3860:                free(permitted_opens[idx].host_to_connect);
1.315     markus   3861:                permitted_opens[idx].host_to_connect = NULL;
1.333     markus   3862:                free(permitted_opens[idx].listen_host);
                   3863:                permitted_opens[idx].listen_host = NULL;
1.336     millert  3864:                free(permitted_opens[idx].listen_path);
                   3865:                permitted_opens[idx].listen_path = NULL;
1.315     markus   3866:        }
1.99      markus   3867: }
                   3868:
1.258     dtucker  3869: int
1.257     dtucker  3870: channel_add_adm_permitted_opens(char *host, int port)
                   3871: {
1.258     dtucker  3872:        debug("config allows port forwarding to host %s port %d", host, port);
1.257     dtucker  3873:
1.342     deraadt  3874:        permitted_adm_opens = xreallocarray(permitted_adm_opens,
1.305     djm      3875:            num_adm_permitted_opens + 1, sizeof(*permitted_adm_opens));
1.257     dtucker  3876:        permitted_adm_opens[num_adm_permitted_opens].host_to_connect
                   3877:             = xstrdup(host);
                   3878:        permitted_adm_opens[num_adm_permitted_opens].port_to_connect = port;
1.333     markus   3879:        permitted_adm_opens[num_adm_permitted_opens].listen_host = NULL;
1.336     millert  3880:        permitted_adm_opens[num_adm_permitted_opens].listen_path = NULL;
1.333     markus   3881:        permitted_adm_opens[num_adm_permitted_opens].listen_port = 0;
1.258     dtucker  3882:        return ++num_adm_permitted_opens;
1.257     dtucker  3883: }
                   3884:
                   3885: void
1.316     dtucker  3886: channel_disable_adm_local_opens(void)
                   3887: {
1.319     djm      3888:        channel_clear_adm_permitted_opens();
1.343     dtucker  3889:        permitted_adm_opens = xcalloc(sizeof(*permitted_adm_opens), 1);
1.319     djm      3890:        permitted_adm_opens[num_adm_permitted_opens].host_to_connect = NULL;
                   3891:        num_adm_permitted_opens = 1;
1.316     dtucker  3892: }
                   3893:
                   3894: void
1.99      markus   3895: channel_clear_permitted_opens(void)
                   3896: {
                   3897:        int i;
                   3898:
1.333     markus   3899:        for (i = 0; i < num_permitted_opens; i++) {
1.321     djm      3900:                free(permitted_opens[i].host_to_connect);
1.333     markus   3901:                free(permitted_opens[i].listen_host);
1.336     millert  3902:                free(permitted_opens[i].listen_path);
1.333     markus   3903:        }
1.321     djm      3904:        free(permitted_opens);
                   3905:        permitted_opens = NULL;
1.99      markus   3906:        num_permitted_opens = 0;
1.257     dtucker  3907: }
                   3908:
                   3909: void
                   3910: channel_clear_adm_permitted_opens(void)
                   3911: {
                   3912:        int i;
1.99      markus   3913:
1.333     markus   3914:        for (i = 0; i < num_adm_permitted_opens; i++) {
1.321     djm      3915:                free(permitted_adm_opens[i].host_to_connect);
1.333     markus   3916:                free(permitted_adm_opens[i].listen_host);
1.336     millert  3917:                free(permitted_adm_opens[i].listen_path);
1.333     markus   3918:        }
1.321     djm      3919:        free(permitted_adm_opens);
                   3920:        permitted_adm_opens = NULL;
1.257     dtucker  3921:        num_adm_permitted_opens = 0;
1.278     dtucker  3922: }
                   3923:
                   3924: void
                   3925: channel_print_adm_permitted_opens(void)
                   3926: {
1.286     djm      3927:        int i;
1.278     dtucker  3928:
1.290     stevesk  3929:        printf("permitopen");
1.288     stevesk  3930:        if (num_adm_permitted_opens == 0) {
1.290     stevesk  3931:                printf(" any\n");
1.288     stevesk  3932:                return;
                   3933:        }
1.278     dtucker  3934:        for (i = 0; i < num_adm_permitted_opens; i++)
1.316     dtucker  3935:                if (permitted_adm_opens[i].host_to_connect == NULL)
                   3936:                        printf(" none");
                   3937:                else
1.278     dtucker  3938:                        printf(" %s:%d", permitted_adm_opens[i].host_to_connect,
                   3939:                            permitted_adm_opens[i].port_to_connect);
1.290     stevesk  3940:        printf("\n");
1.99      markus   3941: }
                   3942:
1.314     dtucker  3943: /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
                   3944: int
                   3945: permitopen_port(const char *p)
                   3946: {
                   3947:        int port;
                   3948:
                   3949:        if (strcmp(p, "*") == 0)
                   3950:                return FWD_PERMIT_ANY_PORT;
                   3951:        if ((port = a2port(p)) > 0)
                   3952:                return port;
                   3953:        return -1;
                   3954: }
                   3955:
1.276     djm      3956: /* Try to start non-blocking connect to next host in cctx list */
1.127     itojun   3957: static int
1.276     djm      3958: connect_next(struct channel_connect *cctx)
1.41      markus   3959: {
1.276     djm      3960:        int sock, saved_errno;
1.336     millert  3961:        struct sockaddr_un *sunaddr;
1.352     deraadt  3962:        char ntop[NI_MAXHOST], strport[MAXIMUM(NI_MAXSERV,sizeof(sunaddr->sun_path))];
1.41      markus   3963:
1.276     djm      3964:        for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
1.336     millert  3965:                switch (cctx->ai->ai_family) {
                   3966:                case AF_UNIX:
                   3967:                        /* unix:pathname instead of host:port */
                   3968:                        sunaddr = (struct sockaddr_un *)cctx->ai->ai_addr;
                   3969:                        strlcpy(ntop, "unix", sizeof(ntop));
                   3970:                        strlcpy(strport, sunaddr->sun_path, sizeof(strport));
                   3971:                        break;
                   3972:                case AF_INET:
                   3973:                case AF_INET6:
                   3974:                        if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
                   3975:                            ntop, sizeof(ntop), strport, sizeof(strport),
                   3976:                            NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
                   3977:                                error("connect_next: getnameinfo failed");
                   3978:                                continue;
                   3979:                        }
                   3980:                        break;
                   3981:                default:
1.41      markus   3982:                        continue;
                   3983:                }
1.300     dtucker  3984:                if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
                   3985:                    cctx->ai->ai_protocol)) == -1) {
1.276     djm      3986:                        if (cctx->ai->ai_next == NULL)
1.186     djm      3987:                                error("socket: %.100s", strerror(errno));
                   3988:                        else
                   3989:                                verbose("socket: %.100s", strerror(errno));
1.41      markus   3990:                        continue;
                   3991:                }
1.205     djm      3992:                if (set_nonblock(sock) == -1)
                   3993:                        fatal("%s: set_nonblock(%d)", __func__, sock);
1.276     djm      3994:                if (connect(sock, cctx->ai->ai_addr,
                   3995:                    cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
                   3996:                        debug("connect_next: host %.100s ([%.100s]:%s): "
                   3997:                            "%.100s", cctx->host, ntop, strport,
1.41      markus   3998:                            strerror(errno));
1.276     djm      3999:                        saved_errno = errno;
1.41      markus   4000:                        close(sock);
1.276     djm      4001:                        errno = saved_errno;
1.89      stevesk  4002:                        continue;       /* fail -- try next */
1.41      markus   4003:                }
1.336     millert  4004:                if (cctx->ai->ai_family != AF_UNIX)
                   4005:                        set_nodelay(sock);
1.276     djm      4006:                debug("connect_next: host %.100s ([%.100s]:%s) "
                   4007:                    "in progress, fd=%d", cctx->host, ntop, strport, sock);
                   4008:                cctx->ai = cctx->ai->ai_next;
                   4009:                return sock;
                   4010:        }
                   4011:        return -1;
                   4012: }
1.41      markus   4013:
1.276     djm      4014: static void
                   4015: channel_connect_ctx_free(struct channel_connect *cctx)
                   4016: {
1.321     djm      4017:        free(cctx->host);
1.336     millert  4018:        if (cctx->aitop) {
                   4019:                if (cctx->aitop->ai_family == AF_UNIX)
                   4020:                        free(cctx->aitop);
                   4021:                else
                   4022:                        freeaddrinfo(cctx->aitop);
                   4023:        }
1.329     tedu     4024:        memset(cctx, 0, sizeof(*cctx));
1.276     djm      4025: }
                   4026:
1.336     millert  4027: /* Return CONNECTING channel to remote host:port or local socket path */
1.276     djm      4028: static Channel *
1.336     millert  4029: connect_to(const char *name, int port, char *ctype, char *rname)
1.276     djm      4030: {
                   4031:        struct addrinfo hints;
                   4032:        int gaierr;
                   4033:        int sock = -1;
                   4034:        char strport[NI_MAXSERV];
                   4035:        struct channel_connect cctx;
                   4036:        Channel *c;
                   4037:
1.284     djm      4038:        memset(&cctx, 0, sizeof(cctx));
1.336     millert  4039:
                   4040:        if (port == PORT_STREAMLOCAL) {
                   4041:                struct sockaddr_un *sunaddr;
                   4042:                struct addrinfo *ai;
                   4043:
                   4044:                if (strlen(name) > sizeof(sunaddr->sun_path)) {
                   4045:                        error("%.100s: %.100s", name, strerror(ENAMETOOLONG));
                   4046:                        return (NULL);
                   4047:                }
                   4048:
                   4049:                /*
                   4050:                 * Fake up a struct addrinfo for AF_UNIX connections.
                   4051:                 * channel_connect_ctx_free() must check ai_family
                   4052:                 * and use free() not freeaddirinfo() for AF_UNIX.
                   4053:                 */
                   4054:                ai = xmalloc(sizeof(*ai) + sizeof(*sunaddr));
                   4055:                memset(ai, 0, sizeof(*ai) + sizeof(*sunaddr));
                   4056:                ai->ai_addr = (struct sockaddr *)(ai + 1);
                   4057:                ai->ai_addrlen = sizeof(*sunaddr);
                   4058:                ai->ai_family = AF_UNIX;
                   4059:                ai->ai_socktype = SOCK_STREAM;
                   4060:                ai->ai_protocol = PF_UNSPEC;
                   4061:                sunaddr = (struct sockaddr_un *)ai->ai_addr;
                   4062:                sunaddr->sun_family = AF_UNIX;
                   4063:                strlcpy(sunaddr->sun_path, name, sizeof(sunaddr->sun_path));
                   4064:                cctx.aitop = ai;
                   4065:        } else {
                   4066:                memset(&hints, 0, sizeof(hints));
                   4067:                hints.ai_family = IPv4or6;
                   4068:                hints.ai_socktype = SOCK_STREAM;
                   4069:                snprintf(strport, sizeof strport, "%d", port);
                   4070:                if ((gaierr = getaddrinfo(name, strport, &hints, &cctx.aitop)) != 0) {
                   4071:                        error("connect_to %.100s: unknown host (%s)", name,
                   4072:                            ssh_gai_strerror(gaierr));
                   4073:                        return NULL;
                   4074:                }
1.41      markus   4075:        }
1.276     djm      4076:
1.336     millert  4077:        cctx.host = xstrdup(name);
1.276     djm      4078:        cctx.port = port;
                   4079:        cctx.ai = cctx.aitop;
                   4080:
                   4081:        if ((sock = connect_next(&cctx)) == -1) {
                   4082:                error("connect to %.100s port %d failed: %s",
1.336     millert  4083:                    name, port, strerror(errno));
1.276     djm      4084:                channel_connect_ctx_free(&cctx);
                   4085:                return NULL;
1.41      markus   4086:        }
1.276     djm      4087:        c = channel_new(ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
                   4088:            CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
                   4089:        c->connect_ctx = cctx;
                   4090:        return c;
1.41      markus   4091: }
1.99      markus   4092:
1.354   ! markus   4093: /*
        !          4094:  * returns either the newly connected channel or the downstream channel
        !          4095:  * that needs to deal with this connection.
        !          4096:  */
1.276     djm      4097: Channel *
1.333     markus   4098: channel_connect_by_listen_address(const char *listen_host,
                   4099:     u_short listen_port, char *ctype, char *rname)
1.73      markus   4100: {
                   4101:        int i;
1.99      markus   4102:
1.276     djm      4103:        for (i = 0; i < num_permitted_opens; i++) {
1.336     millert  4104:                if (open_listen_match_tcpip(&permitted_opens[i], listen_host,
1.333     markus   4105:                    listen_port, 1)) {
1.354   ! markus   4106:                        if (permitted_opens[i].downstream)
        !          4107:                                return permitted_opens[i].downstream;
1.99      markus   4108:                        return connect_to(
1.73      markus   4109:                            permitted_opens[i].host_to_connect,
1.276     djm      4110:                            permitted_opens[i].port_to_connect, ctype, rname);
                   4111:                }
                   4112:        }
1.74      markus   4113:        error("WARNING: Server requests forwarding for unknown listen_port %d",
                   4114:            listen_port);
1.276     djm      4115:        return NULL;
1.73      markus   4116: }
                   4117:
1.336     millert  4118: Channel *
                   4119: channel_connect_by_listen_path(const char *path, char *ctype, char *rname)
                   4120: {
                   4121:        int i;
                   4122:
                   4123:        for (i = 0; i < num_permitted_opens; i++) {
                   4124:                if (open_listen_match_streamlocal(&permitted_opens[i], path)) {
                   4125:                        return connect_to(
                   4126:                            permitted_opens[i].host_to_connect,
                   4127:                            permitted_opens[i].port_to_connect, ctype, rname);
                   4128:                }
                   4129:        }
                   4130:        error("WARNING: Server requests forwarding for unknown path %.100s",
                   4131:            path);
                   4132:        return NULL;
                   4133: }
                   4134:
1.99      markus   4135: /* Check if connecting to that port is permitted and connect. */
1.276     djm      4136: Channel *
1.336     millert  4137: channel_connect_to_port(const char *host, u_short port, char *ctype, char *rname)
1.99      markus   4138: {
1.257     dtucker  4139:        int i, permit, permit_adm = 1;
1.99      markus   4140:
                   4141:        permit = all_opens_permitted;
                   4142:        if (!permit) {
                   4143:                for (i = 0; i < num_permitted_opens; i++)
1.333     markus   4144:                        if (open_match(&permitted_opens[i], host, port)) {
1.99      markus   4145:                                permit = 1;
1.333     markus   4146:                                break;
                   4147:                        }
1.257     dtucker  4148:        }
1.99      markus   4149:
1.257     dtucker  4150:        if (num_adm_permitted_opens > 0) {
                   4151:                permit_adm = 0;
                   4152:                for (i = 0; i < num_adm_permitted_opens; i++)
1.333     markus   4153:                        if (open_match(&permitted_adm_opens[i], host, port)) {
1.257     dtucker  4154:                                permit_adm = 1;
1.333     markus   4155:                                break;
                   4156:                        }
1.99      markus   4157:        }
1.257     dtucker  4158:
                   4159:        if (!permit || !permit_adm) {
1.188     itojun   4160:                logit("Received request to connect to host %.100s port %d, "
1.99      markus   4161:                    "but the request was denied.", host, port);
1.276     djm      4162:                return NULL;
1.99      markus   4163:        }
1.276     djm      4164:        return connect_to(host, port, ctype, rname);
1.336     millert  4165: }
                   4166:
                   4167: /* Check if connecting to that path is permitted and connect. */
                   4168: Channel *
                   4169: channel_connect_to_path(const char *path, char *ctype, char *rname)
                   4170: {
                   4171:        int i, permit, permit_adm = 1;
                   4172:
                   4173:        permit = all_opens_permitted;
                   4174:        if (!permit) {
                   4175:                for (i = 0; i < num_permitted_opens; i++)
                   4176:                        if (open_match(&permitted_opens[i], path, PORT_STREAMLOCAL)) {
                   4177:                                permit = 1;
                   4178:                                break;
                   4179:                        }
                   4180:        }
                   4181:
                   4182:        if (num_adm_permitted_opens > 0) {
                   4183:                permit_adm = 0;
                   4184:                for (i = 0; i < num_adm_permitted_opens; i++)
                   4185:                        if (open_match(&permitted_adm_opens[i], path, PORT_STREAMLOCAL)) {
                   4186:                                permit_adm = 1;
                   4187:                                break;
                   4188:                        }
                   4189:        }
                   4190:
                   4191:        if (!permit || !permit_adm) {
                   4192:                logit("Received request to connect to path %.100s, "
                   4193:                    "but the request was denied.", path);
                   4194:                return NULL;
                   4195:        }
                   4196:        return connect_to(path, PORT_STREAMLOCAL, ctype, rname);
1.204     djm      4197: }
                   4198:
                   4199: void
                   4200: channel_send_window_changes(void)
                   4201: {
1.209     avsm     4202:        u_int i;
1.204     djm      4203:        struct winsize ws;
                   4204:
                   4205:        for (i = 0; i < channels_alloc; i++) {
1.213     deraadt  4206:                if (channels[i] == NULL || !channels[i]->client_tty ||
1.204     djm      4207:                    channels[i]->type != SSH_CHANNEL_OPEN)
                   4208:                        continue;
                   4209:                if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
                   4210:                        continue;
                   4211:                channel_request_start(i, "window-change", 0);
1.238     deraadt  4212:                packet_put_int((u_int)ws.ws_col);
                   4213:                packet_put_int((u_int)ws.ws_row);
                   4214:                packet_put_int((u_int)ws.ws_xpixel);
                   4215:                packet_put_int((u_int)ws.ws_ypixel);
1.204     djm      4216:                packet_send();
                   4217:        }
1.99      markus   4218: }
                   4219:
1.121     markus   4220: /* -- X11 forwarding */
1.1       deraadt  4221:
1.27      markus   4222: /*
                   4223:  * Creates an internet domain socket for listening for X11 connections.
1.176     deraadt  4224:  * Returns 0 and a suitable display number for the DISPLAY variable
                   4225:  * stored in display_numberp , or -1 if an error occurs.
1.27      markus   4226:  */
1.141     stevesk  4227: int
1.163     stevesk  4228: x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
1.222     djm      4229:     int single_connection, u_int *display_numberp, int **chanids)
1.1       deraadt  4230: {
1.149     markus   4231:        Channel *nc = NULL;
1.31      markus   4232:        int display_number, sock;
                   4233:        u_short port;
1.35      markus   4234:        struct addrinfo hints, *ai, *aitop;
                   4235:        char strport[NI_MAXSERV];
                   4236:        int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
1.25      markus   4237:
1.224     markus   4238:        if (chanids == NULL)
                   4239:                return -1;
                   4240:
1.33      markus   4241:        for (display_number = x11_display_offset;
1.148     deraadt  4242:            display_number < MAX_DISPLAYS;
                   4243:            display_number++) {
1.25      markus   4244:                port = 6000 + display_number;
1.35      markus   4245:                memset(&hints, 0, sizeof(hints));
                   4246:                hints.ai_family = IPv4or6;
1.163     stevesk  4247:                hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
1.35      markus   4248:                hints.ai_socktype = SOCK_STREAM;
                   4249:                snprintf(strport, sizeof strport, "%d", port);
                   4250:                if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
1.271     dtucker  4251:                        error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
1.141     stevesk  4252:                        return -1;
1.25      markus   4253:                }
1.35      markus   4254:                for (ai = aitop; ai; ai = ai->ai_next) {
                   4255:                        if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   4256:                                continue;
1.300     dtucker  4257:                        sock = socket(ai->ai_family, ai->ai_socktype,
                   4258:                            ai->ai_protocol);
1.35      markus   4259:                        if (sock < 0) {
                   4260:                                error("socket: %.100s", strerror(errno));
1.203     markus   4261:                                freeaddrinfo(aitop);
1.141     stevesk  4262:                                return -1;
1.35      markus   4263:                        }
1.226     djm      4264:                        channel_set_reuseaddr(sock);
1.35      markus   4265:                        if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1.194     markus   4266:                                debug2("bind port %d: %.100s", port, strerror(errno));
1.35      markus   4267:                                close(sock);
1.183     itojun   4268:
1.35      markus   4269:                                for (n = 0; n < num_socks; n++) {
                   4270:                                        close(socks[n]);
                   4271:                                }
                   4272:                                num_socks = 0;
                   4273:                                break;
                   4274:                        }
                   4275:                        socks[num_socks++] = sock;
                   4276:                        if (num_socks == NUM_SOCKS)
                   4277:                                break;
1.25      markus   4278:                }
1.83      stevesk  4279:                freeaddrinfo(aitop);
1.35      markus   4280:                if (num_socks > 0)
                   4281:                        break;
1.25      markus   4282:        }
                   4283:        if (display_number >= MAX_DISPLAYS) {
                   4284:                error("Failed to allocate internet-domain X11 display socket.");
1.141     stevesk  4285:                return -1;
1.25      markus   4286:        }
                   4287:        /* Start listening for connections on the socket. */
1.35      markus   4288:        for (n = 0; n < num_socks; n++) {
                   4289:                sock = socks[n];
1.199     markus   4290:                if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1.35      markus   4291:                        error("listen: %.100s", strerror(errno));
                   4292:                        close(sock);
1.141     stevesk  4293:                        return -1;
1.35      markus   4294:                }
1.25      markus   4295:        }
1.35      markus   4296:
                   4297:        /* Allocate a channel for each socket. */
1.242     djm      4298:        *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
1.35      markus   4299:        for (n = 0; n < num_socks; n++) {
                   4300:                sock = socks[n];
1.149     markus   4301:                nc = channel_new("x11 listener",
1.51      markus   4302:                    SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
                   4303:                    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
1.190     markus   4304:                    0, "X11 inet listener", 1);
1.167     markus   4305:                nc->single_connection = single_connection;
1.224     markus   4306:                (*chanids)[n] = nc->self;
1.35      markus   4307:        }
1.224     markus   4308:        (*chanids)[n] = -1;
1.1       deraadt  4309:
1.141     stevesk  4310:        /* Return the display number for the DISPLAY environment variable. */
1.176     deraadt  4311:        *display_numberp = display_number;
                   4312:        return (0);
1.1       deraadt  4313: }
                   4314:
1.127     itojun   4315: static int
1.77      markus   4316: connect_local_xsocket(u_int dnr)
1.1       deraadt  4317: {
1.25      markus   4318:        int sock;
                   4319:        struct sockaddr_un addr;
                   4320:
1.147     stevesk  4321:        sock = socket(AF_UNIX, SOCK_STREAM, 0);
                   4322:        if (sock < 0)
                   4323:                error("socket: %.100s", strerror(errno));
                   4324:        memset(&addr, 0, sizeof(addr));
                   4325:        addr.sun_family = AF_UNIX;
                   4326:        snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
1.239     deraadt  4327:        if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
1.147     stevesk  4328:                return sock;
                   4329:        close(sock);
1.25      markus   4330:        error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
                   4331:        return -1;
1.1       deraadt  4332: }
                   4333:
1.51      markus   4334: int
                   4335: x11_connect_display(void)
1.1       deraadt  4336: {
1.248     deraadt  4337:        u_int display_number;
1.25      markus   4338:        const char *display;
1.51      markus   4339:        char buf[1024], *cp;
1.35      markus   4340:        struct addrinfo hints, *ai, *aitop;
                   4341:        char strport[NI_MAXSERV];
1.248     deraadt  4342:        int gaierr, sock = 0;
1.25      markus   4343:
                   4344:        /* Try to open a socket for the local X server. */
                   4345:        display = getenv("DISPLAY");
                   4346:        if (!display) {
                   4347:                error("DISPLAY not set.");
1.51      markus   4348:                return -1;
1.25      markus   4349:        }
1.27      markus   4350:        /*
                   4351:         * Now we decode the value of the DISPLAY variable and make a
                   4352:         * connection to the real X server.
                   4353:         */
                   4354:
                   4355:        /*
                   4356:         * Check if it is a unix domain socket.  Unix domain displays are in
                   4357:         * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
                   4358:         */
1.25      markus   4359:        if (strncmp(display, "unix:", 5) == 0 ||
                   4360:            display[0] == ':') {
                   4361:                /* Connect to the unix domain socket. */
1.248     deraadt  4362:                if (sscanf(strrchr(display, ':') + 1, "%u", &display_number) != 1) {
1.25      markus   4363:                        error("Could not parse display number from DISPLAY: %.100s",
1.148     deraadt  4364:                            display);
1.51      markus   4365:                        return -1;
1.25      markus   4366:                }
                   4367:                /* Create a socket. */
                   4368:                sock = connect_local_xsocket(display_number);
                   4369:                if (sock < 0)
1.51      markus   4370:                        return -1;
1.25      markus   4371:
                   4372:                /* OK, we now have a connection to the display. */
1.51      markus   4373:                return sock;
1.25      markus   4374:        }
1.27      markus   4375:        /*
                   4376:         * Connect to an inet socket.  The DISPLAY value is supposedly
                   4377:         * hostname:d[.s], where hostname may also be numeric IP address.
                   4378:         */
1.145     stevesk  4379:        strlcpy(buf, display, sizeof(buf));
1.25      markus   4380:        cp = strchr(buf, ':');
                   4381:        if (!cp) {
                   4382:                error("Could not find ':' in DISPLAY: %.100s", display);
1.51      markus   4383:                return -1;
1.25      markus   4384:        }
                   4385:        *cp = 0;
1.27      markus   4386:        /* buf now contains the host name.  But first we parse the display number. */
1.248     deraadt  4387:        if (sscanf(cp + 1, "%u", &display_number) != 1) {
1.25      markus   4388:                error("Could not parse display number from DISPLAY: %.100s",
1.148     deraadt  4389:                    display);
1.51      markus   4390:                return -1;
1.25      markus   4391:        }
1.35      markus   4392:
                   4393:        /* Look up the host address */
                   4394:        memset(&hints, 0, sizeof(hints));
                   4395:        hints.ai_family = IPv4or6;
                   4396:        hints.ai_socktype = SOCK_STREAM;
1.248     deraadt  4397:        snprintf(strport, sizeof strport, "%u", 6000 + display_number);
1.35      markus   4398:        if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
1.271     dtucker  4399:                error("%.100s: unknown host. (%s)", buf,
                   4400:                ssh_gai_strerror(gaierr));
1.51      markus   4401:                return -1;
1.25      markus   4402:        }
1.35      markus   4403:        for (ai = aitop; ai; ai = ai->ai_next) {
                   4404:                /* Create a socket. */
1.300     dtucker  4405:                sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1.35      markus   4406:                if (sock < 0) {
1.194     markus   4407:                        debug2("socket: %.100s", strerror(errno));
1.41      markus   4408:                        continue;
                   4409:                }
                   4410:                /* Connect it to the display. */
                   4411:                if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1.248     deraadt  4412:                        debug2("connect %.100s port %u: %.100s", buf,
1.41      markus   4413:                            6000 + display_number, strerror(errno));
                   4414:                        close(sock);
                   4415:                        continue;
                   4416:                }
                   4417:                /* Success */
                   4418:                break;
1.35      markus   4419:        }
                   4420:        freeaddrinfo(aitop);
                   4421:        if (!ai) {
1.248     deraadt  4422:                error("connect %.100s port %u: %.100s", buf, 6000 + display_number,
1.35      markus   4423:                    strerror(errno));
1.51      markus   4424:                return -1;
1.25      markus   4425:        }
1.162     stevesk  4426:        set_nodelay(sock);
1.51      markus   4427:        return sock;
                   4428: }
                   4429:
                   4430: /*
                   4431:  * This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
                   4432:  * the remote channel number.  We should do whatever we want, and respond
                   4433:  * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
                   4434:  */
                   4435:
1.259     stevesk  4436: /* ARGSUSED */
1.339     markus   4437: int
1.154     markus   4438: x11_input_open(int type, u_int32_t seq, void *ctxt)
1.51      markus   4439: {
1.113     markus   4440:        Channel *c = NULL;
                   4441:        int remote_id, sock = 0;
1.51      markus   4442:        char *remote_host;
1.25      markus   4443:
1.113     markus   4444:        debug("Received X11 open request.");
1.51      markus   4445:
1.113     markus   4446:        remote_id = packet_get_int();
1.121     markus   4447:
                   4448:        if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
1.113     markus   4449:                remote_host = packet_get_string(NULL);
1.51      markus   4450:        } else {
                   4451:                remote_host = xstrdup("unknown (remote did not supply name)");
                   4452:        }
1.152     markus   4453:        packet_check_eom();
1.25      markus   4454:
1.51      markus   4455:        /* Obtain a connection to the real X display. */
                   4456:        sock = x11_connect_display();
1.113     markus   4457:        if (sock != -1) {
                   4458:                /* Allocate a channel for this connection. */
                   4459:                c = channel_new("connected x11 socket",
                   4460:                    SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
                   4461:                    remote_host, 1);
1.167     markus   4462:                c->remote_id = remote_id;
                   4463:                c->force_drain = 1;
1.113     markus   4464:        }
1.321     djm      4465:        free(remote_host);
1.113     markus   4466:        if (c == NULL) {
1.51      markus   4467:                /* Send refusal to the remote host. */
                   4468:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1.113     markus   4469:                packet_put_int(remote_id);
1.51      markus   4470:        } else {
                   4471:                /* Send a confirmation to the remote host. */
                   4472:                packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1.113     markus   4473:                packet_put_int(remote_id);
                   4474:                packet_put_int(c->self);
1.51      markus   4475:        }
1.113     markus   4476:        packet_send();
1.339     markus   4477:        return 0;
1.72      markus   4478: }
                   4479:
                   4480: /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
1.259     stevesk  4481: /* ARGSUSED */
1.339     markus   4482: int
1.154     markus   4483: deny_input_open(int type, u_int32_t seq, void *ctxt)
1.72      markus   4484: {
                   4485:        int rchan = packet_get_int();
1.180     deraadt  4486:
1.143     deraadt  4487:        switch (type) {
1.72      markus   4488:        case SSH_SMSG_AGENT_OPEN:
                   4489:                error("Warning: ssh server tried agent forwarding.");
                   4490:                break;
                   4491:        case SSH_SMSG_X11_OPEN:
                   4492:                error("Warning: ssh server tried X11 forwarding.");
                   4493:                break;
                   4494:        default:
1.154     markus   4495:                error("deny_input_open: type %d", type);
1.72      markus   4496:                break;
                   4497:        }
1.230     stevesk  4498:        error("Warning: this is probably a break-in attempt by a malicious server.");
1.72      markus   4499:        packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   4500:        packet_put_int(rchan);
                   4501:        packet_send();
1.339     markus   4502:        return 0;
1.1       deraadt  4503: }
                   4504:
1.27      markus   4505: /*
                   4506:  * Requests forwarding of X11 connections, generates fake authentication
                   4507:  * data, and enables authentication spoofing.
1.121     markus   4508:  * This should be called in the client only.
1.27      markus   4509:  */
1.49      markus   4510: void
1.215     djm      4511: x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
1.311     djm      4512:     const char *proto, const char *data, int want_reply)
1.1       deraadt  4513: {
1.77      markus   4514:        u_int data_len = (u_int) strlen(data) / 2;
1.219     djm      4515:        u_int i, value;
1.25      markus   4516:        char *new_data;
                   4517:        int screen_number;
                   4518:        const char *cp;
                   4519:
1.220     markus   4520:        if (x11_saved_display == NULL)
                   4521:                x11_saved_display = xstrdup(disp);
                   4522:        else if (strcmp(disp, x11_saved_display) != 0) {
1.219     djm      4523:                error("x11_request_forwarding_with_spoofing: different "
                   4524:                    "$DISPLAY already forwarded");
                   4525:                return;
                   4526:        }
                   4527:
1.266     djm      4528:        cp = strchr(disp, ':');
1.25      markus   4529:        if (cp)
                   4530:                cp = strchr(cp, '.');
                   4531:        if (cp)
1.245     deraadt  4532:                screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
1.25      markus   4533:        else
                   4534:                screen_number = 0;
                   4535:
1.219     djm      4536:        if (x11_saved_proto == NULL) {
                   4537:                /* Save protocol name. */
                   4538:                x11_saved_proto = xstrdup(proto);
1.353     natano   4539:
                   4540:                /* Extract real authentication data. */
1.219     djm      4541:                x11_saved_data = xmalloc(data_len);
                   4542:                for (i = 0; i < data_len; i++) {
                   4543:                        if (sscanf(data + 2 * i, "%2x", &value) != 1)
                   4544:                                fatal("x11_request_forwarding: bad "
                   4545:                                    "authentication data: %.100s", data);
                   4546:                        x11_saved_data[i] = value;
                   4547:                }
                   4548:                x11_saved_data_len = data_len;
1.353     natano   4549:
                   4550:                /* Generate fake data of the same length. */
                   4551:                x11_fake_data = xmalloc(data_len);
                   4552:                arc4random_buf(x11_fake_data, data_len);
1.219     djm      4553:                x11_fake_data_len = data_len;
1.25      markus   4554:        }
                   4555:
                   4556:        /* Convert the fake data into hex. */
1.219     djm      4557:        new_data = tohex(x11_fake_data, data_len);
1.25      markus   4558:
                   4559:        /* Send the request packet. */
1.51      markus   4560:        if (compat20) {
1.311     djm      4561:                channel_request_start(client_session_id, "x11-req", want_reply);
1.51      markus   4562:                packet_put_char(0);     /* XXX bool single connection */
                   4563:        } else {
                   4564:                packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
                   4565:        }
                   4566:        packet_put_cstring(proto);
                   4567:        packet_put_cstring(new_data);
1.25      markus   4568:        packet_put_int(screen_number);
                   4569:        packet_send();
                   4570:        packet_write_wait();
1.321     djm      4571:        free(new_data);
1.1       deraadt  4572: }
                   4573:
1.121     markus   4574:
                   4575: /* -- agent forwarding */
                   4576:
1.1       deraadt  4577: /* Sends a message to the server to request authentication fd forwarding. */
                   4578:
1.49      markus   4579: void
1.142     itojun   4580: auth_request_forwarding(void)
1.1       deraadt  4581: {
1.25      markus   4582:        packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
                   4583:        packet_send();
                   4584:        packet_write_wait();
1.1       deraadt  4585: }