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

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