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

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