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

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