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

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