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

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