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

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