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

1.260   ! stevesk     1: /* $OpenBSD: channels.c,v 1.259 2006/07/21 21:13:30 stevesk 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:
                     42: #include "includes.h"
1.234     stevesk    43:
                     44: #include <sys/ioctl.h>
1.235     stevesk    45: #include <sys/types.h>
                     46: #include <sys/un.h>
1.251     stevesk    47: #include <sys/socket.h>
                     48:
                     49: #include <netinet/in.h>
                     50: #include <arpa/inet.h>
1.233     stevesk    51:
1.254     stevesk    52: #include <errno.h>
1.255     stevesk    53: #include <netdb.h>
1.260   ! stevesk    54: #include <string.h>
1.233     stevesk    55: #include <termios.h>
1.256     stevesk    56: #include <unistd.h>
1.1       deraadt    57:
                     58: #include "ssh.h"
1.82      markus     59: #include "ssh1.h"
                     60: #include "ssh2.h"
1.1       deraadt    61: #include "packet.h"
                     62: #include "xmalloc.h"
1.82      markus     63: #include "log.h"
                     64: #include "misc.h"
1.14      markus     65: #include "channels.h"
                     66: #include "compat.h"
1.82      markus     67: #include "canohost.h"
1.64      markus     68: #include "key.h"
                     69: #include "authfd.h"
1.147     stevesk    70: #include "pathnames.h"
1.193     markus     71: #include "bufaux.h"
1.1       deraadt    72:
1.121     markus     73: /* -- channel core */
1.12      markus     74:
1.27      markus     75: /*
                     76:  * Pointer to an array containing all allocated channels.  The array is
                     77:  * dynamically extended as needed.
                     78:  */
1.113     markus     79: static Channel **channels = NULL;
1.1       deraadt    80:
1.27      markus     81: /*
                     82:  * Size of the channel array.  All slots of the array must always be
1.113     markus     83:  * initialized (at least the type field); unused slots set to NULL
1.27      markus     84:  */
1.209     avsm       85: static u_int channels_alloc = 0;
1.1       deraadt    86:
1.27      markus     87: /*
                     88:  * Maximum file descriptor value used in any of the channels.  This is
1.113     markus     89:  * updated in channel_new.
1.27      markus     90:  */
1.84      markus     91: static int channel_max_fd = 0;
1.1       deraadt    92:
                     93:
1.121     markus     94: /* -- tcp forwarding */
1.1       deraadt    95:
1.27      markus     96: /*
                     97:  * Data structure for storing which hosts are permitted for forward requests.
                     98:  * The local sides of any remote forwards are stored in this array to prevent
                     99:  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
                    100:  * network (which might be behind a firewall).
                    101:  */
1.25      markus    102: typedef struct {
1.41      markus    103:        char *host_to_connect;          /* Connect to 'host'. */
                    104:        u_short port_to_connect;        /* Connect to 'port'. */
                    105:        u_short listen_port;            /* Remote side should listen port number. */
1.1       deraadt   106: } ForwardPermission;
                    107:
1.257     dtucker   108: /* List of all permitted host/port pairs to connect by the user. */
1.1       deraadt   109: static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
1.121     markus    110:
1.257     dtucker   111: /* List of all permitted host/port pairs to connect by the admin. */
                    112: static ForwardPermission permitted_adm_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
                    113:
                    114: /* Number of permitted host/port pairs in the array permitted by the user. */
1.1       deraadt   115: static int num_permitted_opens = 0;
1.257     dtucker   116:
                    117: /* Number of permitted host/port pair in the array permitted by the admin. */
                    118: static int num_adm_permitted_opens = 0;
                    119:
1.27      markus    120: /*
                    121:  * If this is true, all opens are permitted.  This is the case on the server
                    122:  * on which we have to trust the client anyway, and the user could do
                    123:  * anything after logging in anyway.
                    124:  */
1.1       deraadt   125: static int all_opens_permitted = 0;
                    126:
1.121     markus    127:
                    128: /* -- X11 forwarding */
                    129:
                    130: /* Maximum number of fake X11 displays to try. */
                    131: #define MAX_DISPLAYS  1000
                    132:
1.219     djm       133: /* Saved X11 local (client) display. */
                    134: static char *x11_saved_display = NULL;
                    135:
1.121     markus    136: /* Saved X11 authentication protocol name. */
                    137: static char *x11_saved_proto = NULL;
                    138:
                    139: /* Saved X11 authentication data.  This is the real data. */
                    140: static char *x11_saved_data = NULL;
                    141: static u_int x11_saved_data_len = 0;
                    142:
                    143: /*
                    144:  * Fake X11 authentication data.  This is what the server will be sending us;
                    145:  * we should replace any occurrences of this by the real data.
                    146:  */
1.240     deraadt   147: static u_char *x11_fake_data = NULL;
1.121     markus    148: static u_int x11_fake_data_len;
                    149:
                    150:
                    151: /* -- agent forwarding */
                    152:
                    153: #define        NUM_SOCKS       10
                    154:
1.82      markus    155: /* AF_UNSPEC or AF_INET or AF_INET6 */
1.135     markus    156: static int IPv4or6 = AF_UNSPEC;
1.1       deraadt   157:
1.121     markus    158: /* helper */
1.127     itojun    159: static void port_open_helper(Channel *c, char *rtype);
1.103     markus    160:
1.121     markus    161: /* -- channel core */
1.41      markus    162:
                    163: Channel *
1.229     markus    164: channel_by_id(int id)
1.41      markus    165: {
                    166:        Channel *c;
1.113     markus    167:
1.209     avsm      168:        if (id < 0 || (u_int)id >= channels_alloc) {
1.229     markus    169:                logit("channel_by_id: %d: bad id", id);
1.41      markus    170:                return NULL;
                    171:        }
1.113     markus    172:        c = channels[id];
                    173:        if (c == NULL) {
1.229     markus    174:                logit("channel_by_id: %d: bad id: channel free", id);
1.41      markus    175:                return NULL;
                    176:        }
                    177:        return c;
1.55      markus    178: }
                    179:
1.27      markus    180: /*
1.229     markus    181:  * Returns the channel if it is allowed to receive protocol messages.
                    182:  * Private channels, like listening sockets, may not receive messages.
                    183:  */
                    184: Channel *
                    185: channel_lookup(int id)
                    186: {
                    187:        Channel *c;
                    188:
                    189:        if ((c = channel_by_id(id)) == NULL)
                    190:                return (NULL);
                    191:
1.237     deraadt   192:        switch (c->type) {
1.229     markus    193:        case SSH_CHANNEL_X11_OPEN:
                    194:        case SSH_CHANNEL_LARVAL:
                    195:        case SSH_CHANNEL_CONNECTING:
                    196:        case SSH_CHANNEL_DYNAMIC:
                    197:        case SSH_CHANNEL_OPENING:
                    198:        case SSH_CHANNEL_OPEN:
                    199:        case SSH_CHANNEL_INPUT_DRAINING:
                    200:        case SSH_CHANNEL_OUTPUT_DRAINING:
                    201:                return (c);
                    202:        }
                    203:        logit("Non-public channel %d, type %d.", id, c->type);
                    204:        return (NULL);
                    205: }
                    206:
                    207: /*
1.55      markus    208:  * Register filedescriptors for a channel, used when allocating a channel or
1.52      markus    209:  * when the channel consumer/producer is ready, e.g. shell exec'd
1.27      markus    210:  */
1.127     itojun    211: static void
1.71      markus    212: channel_register_fds(Channel *c, int rfd, int wfd, int efd,
                    213:     int extusage, int nonblock)
1.1       deraadt   214: {
1.25      markus    215:        /* Update the maximum file descriptor value. */
1.84      markus    216:        channel_max_fd = MAX(channel_max_fd, rfd);
                    217:        channel_max_fd = MAX(channel_max_fd, wfd);
                    218:        channel_max_fd = MAX(channel_max_fd, efd);
                    219:
1.27      markus    220:        /* XXX set close-on-exec -markus */
1.55      markus    221:
1.52      markus    222:        c->rfd = rfd;
                    223:        c->wfd = wfd;
                    224:        c->sock = (rfd == wfd) ? rfd : -1;
1.204     djm       225:        c->ctl_fd = -1; /* XXX: set elsewhere */
1.52      markus    226:        c->efd = efd;
                    227:        c->extended_usage = extusage;
1.71      markus    228:
1.91      markus    229:        /* XXX ugly hack: nonblock is only set by the server */
                    230:        if (nonblock && isatty(c->rfd)) {
1.194     markus    231:                debug2("channel %d: rfd %d isatty", c->self, c->rfd);
1.91      markus    232:                c->isatty = 1;
                    233:                if (!isatty(c->wfd)) {
1.94      markus    234:                        error("channel %d: wfd %d is not a tty?",
1.91      markus    235:                            c->self, c->wfd);
                    236:                }
                    237:        } else {
                    238:                c->isatty = 0;
                    239:        }
                    240:
1.71      markus    241:        /* enable nonblocking mode */
                    242:        if (nonblock) {
                    243:                if (rfd != -1)
                    244:                        set_nonblock(rfd);
                    245:                if (wfd != -1)
                    246:                        set_nonblock(wfd);
                    247:                if (efd != -1)
                    248:                        set_nonblock(efd);
                    249:        }
1.52      markus    250: }
                    251:
                    252: /*
                    253:  * Allocate a new channel object and set its type and socket. This will cause
                    254:  * remote_name to be freed.
                    255:  */
1.113     markus    256: Channel *
1.52      markus    257: channel_new(char *ctype, int type, int rfd, int wfd, int efd,
1.178     markus    258:     u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
1.52      markus    259: {
1.209     avsm      260:        int found;
                    261:        u_int i;
1.52      markus    262:        Channel *c;
1.25      markus    263:
                    264:        /* Do initial allocation if this is the first call. */
                    265:        if (channels_alloc == 0) {
                    266:                channels_alloc = 10;
1.242     djm       267:                channels = xcalloc(channels_alloc, sizeof(Channel *));
1.25      markus    268:                for (i = 0; i < channels_alloc; i++)
1.113     markus    269:                        channels[i] = NULL;
1.25      markus    270:        }
                    271:        /* Try to find a free slot where to put the new channel. */
                    272:        for (found = -1, i = 0; i < channels_alloc; i++)
1.113     markus    273:                if (channels[i] == NULL) {
1.25      markus    274:                        /* Found a free slot. */
1.209     avsm      275:                        found = (int)i;
1.25      markus    276:                        break;
                    277:                }
1.209     avsm      278:        if (found < 0) {
1.27      markus    279:                /* There are no free slots.  Take last+1 slot and expand the array.  */
1.25      markus    280:                found = channels_alloc;
1.179     markus    281:                if (channels_alloc > 10000)
                    282:                        fatal("channel_new: internal error: channels_alloc %d "
                    283:                            "too big.", channels_alloc);
1.243     djm       284:                channels = xrealloc(channels, channels_alloc + 10,
                    285:                    sizeof(Channel *));
1.195     markus    286:                channels_alloc += 10;
1.70      markus    287:                debug2("channel: expanding %d", channels_alloc);
1.25      markus    288:                for (i = found; i < channels_alloc; i++)
1.113     markus    289:                        channels[i] = NULL;
1.25      markus    290:        }
1.113     markus    291:        /* Initialize and return new channel. */
1.242     djm       292:        c = channels[found] = xcalloc(1, sizeof(Channel));
1.25      markus    293:        buffer_init(&c->input);
                    294:        buffer_init(&c->output);
1.41      markus    295:        buffer_init(&c->extended);
1.159     markus    296:        c->ostate = CHAN_OUTPUT_OPEN;
                    297:        c->istate = CHAN_INPUT_OPEN;
                    298:        c->flags = 0;
1.71      markus    299:        channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
1.25      markus    300:        c->self = found;
                    301:        c->type = type;
1.41      markus    302:        c->ctype = ctype;
1.51      markus    303:        c->local_window = window;
                    304:        c->local_window_max = window;
                    305:        c->local_consumed = 0;
                    306:        c->local_maxpacket = maxpack;
1.25      markus    307:        c->remote_id = -1;
1.190     markus    308:        c->remote_name = xstrdup(remote_name);
1.41      markus    309:        c->remote_window = 0;
                    310:        c->remote_maxpacket = 0;
1.133     markus    311:        c->force_drain = 0;
1.149     markus    312:        c->single_connection = 0;
1.131     markus    313:        c->detach_user = NULL;
1.225     djm       314:        c->detach_close = 0;
1.165     markus    315:        c->confirm = NULL;
1.204     djm       316:        c->confirm_ctx = NULL;
1.65      markus    317:        c->input_filter = NULL;
1.231     reyk      318:        c->output_filter = NULL;
1.25      markus    319:        debug("channel %d: new [%s]", found, remote_name);
1.113     markus    320:        return c;
1.1       deraadt   321: }
1.52      markus    322:
1.132     markus    323: static int
                    324: channel_find_maxfd(void)
                    325: {
1.209     avsm      326:        u_int i;
                    327:        int max = 0;
1.132     markus    328:        Channel *c;
                    329:
                    330:        for (i = 0; i < channels_alloc; i++) {
                    331:                c = channels[i];
                    332:                if (c != NULL) {
                    333:                        max = MAX(max, c->rfd);
                    334:                        max = MAX(max, c->wfd);
                    335:                        max = MAX(max, c->efd);
                    336:                }
                    337:        }
                    338:        return max;
                    339: }
                    340:
                    341: int
                    342: channel_close_fd(int *fdp)
                    343: {
                    344:        int ret = 0, fd = *fdp;
                    345:
                    346:        if (fd != -1) {
                    347:                ret = close(fd);
                    348:                *fdp = -1;
                    349:                if (fd == channel_max_fd)
                    350:                        channel_max_fd = channel_find_maxfd();
                    351:        }
                    352:        return ret;
                    353: }
                    354:
1.52      markus    355: /* Close all channel fd/socket. */
1.127     itojun    356: static void
1.52      markus    357: channel_close_fds(Channel *c)
                    358: {
1.204     djm       359:        debug3("channel %d: close_fds r %d w %d e %d c %d",
                    360:            c->self, c->rfd, c->wfd, c->efd, c->ctl_fd);
1.118     markus    361:
1.132     markus    362:        channel_close_fd(&c->sock);
1.204     djm       363:        channel_close_fd(&c->ctl_fd);
1.132     markus    364:        channel_close_fd(&c->rfd);
                    365:        channel_close_fd(&c->wfd);
                    366:        channel_close_fd(&c->efd);
1.121     markus    367: }
                    368:
                    369: /* Free the channel and close its fd/socket. */
                    370: void
                    371: channel_free(Channel *c)
                    372: {
                    373:        char *s;
1.209     avsm      374:        u_int i, n;
1.121     markus    375:
                    376:        for (n = 0, i = 0; i < channels_alloc; i++)
                    377:                if (channels[i])
                    378:                        n++;
1.209     avsm      379:        debug("channel %d: free: %s, nchannels %u", c->self,
1.121     markus    380:            c->remote_name ? c->remote_name : "???", n);
                    381:
                    382:        s = channel_open_message();
1.194     markus    383:        debug3("channel %d: status: %s", c->self, s);
1.121     markus    384:        xfree(s);
                    385:
                    386:        if (c->sock != -1)
                    387:                shutdown(c->sock, SHUT_RDWR);
1.204     djm       388:        if (c->ctl_fd != -1)
                    389:                shutdown(c->ctl_fd, SHUT_RDWR);
1.121     markus    390:        channel_close_fds(c);
                    391:        buffer_free(&c->input);
                    392:        buffer_free(&c->output);
                    393:        buffer_free(&c->extended);
                    394:        if (c->remote_name) {
                    395:                xfree(c->remote_name);
                    396:                c->remote_name = NULL;
                    397:        }
                    398:        channels[c->self] = NULL;
                    399:        xfree(c);
                    400: }
                    401:
                    402: void
1.126     markus    403: channel_free_all(void)
1.121     markus    404: {
1.209     avsm      405:        u_int i;
1.121     markus    406:
1.126     markus    407:        for (i = 0; i < channels_alloc; i++)
                    408:                if (channels[i] != NULL)
                    409:                        channel_free(channels[i]);
1.131     markus    410: }
                    411:
1.121     markus    412: /*
                    413:  * Closes the sockets/fds of all channels.  This is used to close extra file
                    414:  * descriptors after a fork.
                    415:  */
                    416: void
1.142     itojun    417: channel_close_all(void)
1.121     markus    418: {
1.209     avsm      419:        u_int i;
1.121     markus    420:
                    421:        for (i = 0; i < channels_alloc; i++)
                    422:                if (channels[i] != NULL)
                    423:                        channel_close_fds(channels[i]);
                    424: }
                    425:
                    426: /*
1.131     markus    427:  * Stop listening to channels.
                    428:  */
                    429: void
                    430: channel_stop_listening(void)
                    431: {
1.209     avsm      432:        u_int i;
1.131     markus    433:        Channel *c;
                    434:
                    435:        for (i = 0; i < channels_alloc; i++) {
                    436:                c = channels[i];
                    437:                if (c != NULL) {
                    438:                        switch (c->type) {
                    439:                        case SSH_CHANNEL_AUTH_SOCKET:
                    440:                        case SSH_CHANNEL_PORT_LISTENER:
                    441:                        case SSH_CHANNEL_RPORT_LISTENER:
                    442:                        case SSH_CHANNEL_X11_LISTENER:
1.132     markus    443:                                channel_close_fd(&c->sock);
1.131     markus    444:                                channel_free(c);
                    445:                                break;
                    446:                        }
                    447:                }
                    448:        }
                    449: }
                    450:
                    451: /*
1.121     markus    452:  * Returns true if no channel has too much buffered data, and false if one or
                    453:  * more channel is overfull.
                    454:  */
                    455: int
1.142     itojun    456: channel_not_very_much_buffered_data(void)
1.121     markus    457: {
                    458:        u_int i;
                    459:        Channel *c;
                    460:
                    461:        for (i = 0; i < channels_alloc; i++) {
                    462:                c = channels[i];
                    463:                if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
1.136     markus    464: #if 0
                    465:                        if (!compat20 &&
                    466:                            buffer_len(&c->input) > packet_get_maxsize()) {
1.185     markus    467:                                debug2("channel %d: big input buffer %d",
1.121     markus    468:                                    c->self, buffer_len(&c->input));
                    469:                                return 0;
                    470:                        }
1.136     markus    471: #endif
1.121     markus    472:                        if (buffer_len(&c->output) > packet_get_maxsize()) {
1.191     markus    473:                                debug2("channel %d: big output buffer %u > %u",
1.136     markus    474:                                    c->self, buffer_len(&c->output),
                    475:                                    packet_get_maxsize());
1.121     markus    476:                                return 0;
                    477:                        }
                    478:                }
                    479:        }
                    480:        return 1;
                    481: }
                    482:
                    483: /* Returns true if any channel is still open. */
                    484: int
1.142     itojun    485: channel_still_open(void)
1.121     markus    486: {
1.209     avsm      487:        u_int i;
1.121     markus    488:        Channel *c;
                    489:
                    490:        for (i = 0; i < channels_alloc; i++) {
                    491:                c = channels[i];
                    492:                if (c == NULL)
                    493:                        continue;
                    494:                switch (c->type) {
                    495:                case SSH_CHANNEL_X11_LISTENER:
                    496:                case SSH_CHANNEL_PORT_LISTENER:
                    497:                case SSH_CHANNEL_RPORT_LISTENER:
                    498:                case SSH_CHANNEL_CLOSED:
                    499:                case SSH_CHANNEL_AUTH_SOCKET:
                    500:                case SSH_CHANNEL_DYNAMIC:
                    501:                case SSH_CHANNEL_CONNECTING:
                    502:                case SSH_CHANNEL_ZOMBIE:
                    503:                        continue;
                    504:                case SSH_CHANNEL_LARVAL:
                    505:                        if (!compat20)
                    506:                                fatal("cannot happen: SSH_CHANNEL_LARVAL");
                    507:                        continue;
                    508:                case SSH_CHANNEL_OPENING:
                    509:                case SSH_CHANNEL_OPEN:
                    510:                case SSH_CHANNEL_X11_OPEN:
                    511:                        return 1;
                    512:                case SSH_CHANNEL_INPUT_DRAINING:
                    513:                case SSH_CHANNEL_OUTPUT_DRAINING:
                    514:                        if (!compat13)
                    515:                                fatal("cannot happen: OUT_DRAIN");
                    516:                        return 1;
                    517:                default:
                    518:                        fatal("channel_still_open: bad channel type %d", c->type);
                    519:                        /* NOTREACHED */
                    520:                }
                    521:        }
                    522:        return 0;
                    523: }
                    524:
                    525: /* Returns the id of an open channel suitable for keepaliving */
                    526: int
1.142     itojun    527: channel_find_open(void)
1.121     markus    528: {
1.209     avsm      529:        u_int i;
1.121     markus    530:        Channel *c;
                    531:
                    532:        for (i = 0; i < channels_alloc; i++) {
                    533:                c = channels[i];
1.206     djm       534:                if (c == NULL || c->remote_id < 0)
1.121     markus    535:                        continue;
                    536:                switch (c->type) {
                    537:                case SSH_CHANNEL_CLOSED:
                    538:                case SSH_CHANNEL_DYNAMIC:
                    539:                case SSH_CHANNEL_X11_LISTENER:
                    540:                case SSH_CHANNEL_PORT_LISTENER:
                    541:                case SSH_CHANNEL_RPORT_LISTENER:
                    542:                case SSH_CHANNEL_OPENING:
                    543:                case SSH_CHANNEL_CONNECTING:
                    544:                case SSH_CHANNEL_ZOMBIE:
                    545:                        continue;
                    546:                case SSH_CHANNEL_LARVAL:
                    547:                case SSH_CHANNEL_AUTH_SOCKET:
                    548:                case SSH_CHANNEL_OPEN:
                    549:                case SSH_CHANNEL_X11_OPEN:
                    550:                        return i;
                    551:                case SSH_CHANNEL_INPUT_DRAINING:
                    552:                case SSH_CHANNEL_OUTPUT_DRAINING:
                    553:                        if (!compat13)
                    554:                                fatal("cannot happen: OUT_DRAIN");
                    555:                        return i;
                    556:                default:
                    557:                        fatal("channel_find_open: bad channel type %d", c->type);
                    558:                        /* NOTREACHED */
                    559:                }
                    560:        }
                    561:        return -1;
                    562: }
                    563:
                    564:
                    565: /*
                    566:  * Returns a message describing the currently open forwarded connections,
                    567:  * suitable for sending to the client.  The message contains crlf pairs for
                    568:  * newlines.
                    569:  */
                    570: char *
1.142     itojun    571: channel_open_message(void)
1.121     markus    572: {
                    573:        Buffer buffer;
                    574:        Channel *c;
                    575:        char buf[1024], *cp;
1.209     avsm      576:        u_int i;
1.121     markus    577:
                    578:        buffer_init(&buffer);
                    579:        snprintf(buf, sizeof buf, "The following connections are open:\r\n");
                    580:        buffer_append(&buffer, buf, strlen(buf));
                    581:        for (i = 0; i < channels_alloc; i++) {
                    582:                c = channels[i];
                    583:                if (c == NULL)
                    584:                        continue;
                    585:                switch (c->type) {
                    586:                case SSH_CHANNEL_X11_LISTENER:
                    587:                case SSH_CHANNEL_PORT_LISTENER:
                    588:                case SSH_CHANNEL_RPORT_LISTENER:
                    589:                case SSH_CHANNEL_CLOSED:
                    590:                case SSH_CHANNEL_AUTH_SOCKET:
                    591:                case SSH_CHANNEL_ZOMBIE:
                    592:                        continue;
                    593:                case SSH_CHANNEL_LARVAL:
                    594:                case SSH_CHANNEL_OPENING:
                    595:                case SSH_CHANNEL_CONNECTING:
                    596:                case SSH_CHANNEL_DYNAMIC:
                    597:                case SSH_CHANNEL_OPEN:
                    598:                case SSH_CHANNEL_X11_OPEN:
                    599:                case SSH_CHANNEL_INPUT_DRAINING:
                    600:                case SSH_CHANNEL_OUTPUT_DRAINING:
1.204     djm       601:                        snprintf(buf, sizeof buf,
                    602:                            "  #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d cfd %d)\r\n",
1.121     markus    603:                            c->self, c->remote_name,
                    604:                            c->type, c->remote_id,
                    605:                            c->istate, buffer_len(&c->input),
                    606:                            c->ostate, buffer_len(&c->output),
1.204     djm       607:                            c->rfd, c->wfd, c->ctl_fd);
1.121     markus    608:                        buffer_append(&buffer, buf, strlen(buf));
                    609:                        continue;
                    610:                default:
                    611:                        fatal("channel_open_message: bad channel type %d", c->type);
                    612:                        /* NOTREACHED */
                    613:                }
                    614:        }
                    615:        buffer_append(&buffer, "\0", 1);
                    616:        cp = xstrdup(buffer_ptr(&buffer));
                    617:        buffer_free(&buffer);
                    618:        return cp;
                    619: }
                    620:
                    621: void
                    622: channel_send_open(int id)
                    623: {
                    624:        Channel *c = channel_lookup(id);
1.180     deraadt   625:
1.121     markus    626:        if (c == NULL) {
1.188     itojun    627:                logit("channel_send_open: %d: bad id", id);
1.121     markus    628:                return;
                    629:        }
1.184     markus    630:        debug2("channel %d: send open", id);
1.121     markus    631:        packet_start(SSH2_MSG_CHANNEL_OPEN);
                    632:        packet_put_cstring(c->ctype);
                    633:        packet_put_int(c->self);
                    634:        packet_put_int(c->local_window);
                    635:        packet_put_int(c->local_maxpacket);
                    636:        packet_send();
                    637: }
                    638:
                    639: void
1.184     markus    640: channel_request_start(int id, char *service, int wantconfirm)
1.121     markus    641: {
1.184     markus    642:        Channel *c = channel_lookup(id);
1.180     deraadt   643:
1.121     markus    644:        if (c == NULL) {
1.188     itojun    645:                logit("channel_request_start: %d: unknown channel id", id);
1.121     markus    646:                return;
                    647:        }
1.204     djm       648:        debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
1.121     markus    649:        packet_start(SSH2_MSG_CHANNEL_REQUEST);
                    650:        packet_put_int(c->remote_id);
                    651:        packet_put_cstring(service);
                    652:        packet_put_char(wantconfirm);
                    653: }
1.241     deraadt   654:
1.121     markus    655: void
1.204     djm       656: channel_register_confirm(int id, channel_callback_fn *fn, void *ctx)
1.121     markus    657: {
                    658:        Channel *c = channel_lookup(id);
1.180     deraadt   659:
1.121     markus    660:        if (c == NULL) {
1.188     itojun    661:                logit("channel_register_comfirm: %d: bad id", id);
1.121     markus    662:                return;
                    663:        }
1.165     markus    664:        c->confirm = fn;
1.204     djm       665:        c->confirm_ctx = ctx;
1.121     markus    666: }
1.241     deraadt   667:
1.121     markus    668: void
1.225     djm       669: channel_register_cleanup(int id, channel_callback_fn *fn, int do_close)
1.121     markus    670: {
1.229     markus    671:        Channel *c = channel_by_id(id);
1.180     deraadt   672:
1.121     markus    673:        if (c == NULL) {
1.188     itojun    674:                logit("channel_register_cleanup: %d: bad id", id);
1.121     markus    675:                return;
                    676:        }
1.131     markus    677:        c->detach_user = fn;
1.225     djm       678:        c->detach_close = do_close;
1.121     markus    679: }
1.241     deraadt   680:
1.121     markus    681: void
                    682: channel_cancel_cleanup(int id)
                    683: {
1.229     markus    684:        Channel *c = channel_by_id(id);
1.180     deraadt   685:
1.121     markus    686:        if (c == NULL) {
1.188     itojun    687:                logit("channel_cancel_cleanup: %d: bad id", id);
1.121     markus    688:                return;
1.52      markus    689:        }
1.131     markus    690:        c->detach_user = NULL;
1.225     djm       691:        c->detach_close = 0;
1.121     markus    692: }
1.241     deraadt   693:
1.121     markus    694: void
1.231     reyk      695: channel_register_filter(int id, channel_infilter_fn *ifn,
                    696:     channel_outfilter_fn *ofn)
1.121     markus    697: {
                    698:        Channel *c = channel_lookup(id);
1.180     deraadt   699:
1.121     markus    700:        if (c == NULL) {
1.188     itojun    701:                logit("channel_register_filter: %d: bad id", id);
1.121     markus    702:                return;
1.52      markus    703:        }
1.231     reyk      704:        c->input_filter = ifn;
                    705:        c->output_filter = ofn;
1.52      markus    706: }
                    707:
1.49      markus    708: void
1.121     markus    709: channel_set_fds(int id, int rfd, int wfd, int efd,
1.168     markus    710:     int extusage, int nonblock, u_int window_max)
1.1       deraadt   711: {
1.121     markus    712:        Channel *c = channel_lookup(id);
1.180     deraadt   713:
1.121     markus    714:        if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
                    715:                fatal("channel_activate for non-larval channel %d.", id);
                    716:        channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
                    717:        c->type = SSH_CHANNEL_OPEN;
1.168     markus    718:        c->local_window = c->local_window_max = window_max;
1.121     markus    719:        packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
                    720:        packet_put_int(c->remote_id);
                    721:        packet_put_int(c->local_window);
                    722:        packet_send();
1.1       deraadt   723: }
                    724:
1.27      markus    725: /*
1.41      markus    726:  * 'channel_pre*' are called just before select() to add any bits relevant to
                    727:  * channels in the select bitmasks.
                    728:  */
                    729: /*
                    730:  * 'channel_post*': perform any appropriate operations for channels which
                    731:  * have events pending.
1.27      markus    732:  */
1.237     deraadt   733: typedef void chan_fn(Channel *c, fd_set *readset, fd_set *writeset);
1.41      markus    734: chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
                    735: chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
                    736:
1.259     stevesk   737: /* ARGSUSED */
1.127     itojun    738: static void
1.237     deraadt   739: channel_pre_listener(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    740: {
                    741:        FD_SET(c->sock, readset);
                    742: }
                    743:
1.259     stevesk   744: /* ARGSUSED */
1.127     itojun    745: static void
1.237     deraadt   746: channel_pre_connecting(Channel *c, fd_set *readset, fd_set *writeset)
1.75      markus    747: {
                    748:        debug3("channel %d: waiting for connection", c->self);
                    749:        FD_SET(c->sock, writeset);
                    750: }
                    751:
1.127     itojun    752: static void
1.237     deraadt   753: channel_pre_open_13(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    754: {
                    755:        if (buffer_len(&c->input) < packet_get_maxsize())
                    756:                FD_SET(c->sock, readset);
                    757:        if (buffer_len(&c->output) > 0)
                    758:                FD_SET(c->sock, writeset);
                    759: }
1.1       deraadt   760:
1.127     itojun    761: static void
1.237     deraadt   762: channel_pre_open(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    763: {
1.157     markus    764:        u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
1.41      markus    765:
1.44      markus    766:        if (c->istate == CHAN_INPUT_OPEN &&
1.157     markus    767:            limit > 0 &&
1.250     djm       768:            buffer_len(&c->input) < limit &&
                    769:            buffer_check_alloc(&c->input, CHAN_RBUF))
1.44      markus    770:                FD_SET(c->rfd, readset);
                    771:        if (c->ostate == CHAN_OUTPUT_OPEN ||
                    772:            c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
                    773:                if (buffer_len(&c->output) > 0) {
                    774:                        FD_SET(c->wfd, writeset);
                    775:                } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1.172     markus    776:                        if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
1.223     djm       777:                                debug2("channel %d: obuf_empty delayed efd %d/(%d)",
                    778:                                    c->self, c->efd, buffer_len(&c->extended));
1.172     markus    779:                        else
                    780:                                chan_obuf_empty(c);
1.44      markus    781:                }
                    782:        }
                    783:        /** XXX check close conditions, too */
1.157     markus    784:        if (compat20 && c->efd != -1) {
1.44      markus    785:                if (c->extended_usage == CHAN_EXTENDED_WRITE &&
                    786:                    buffer_len(&c->extended) > 0)
                    787:                        FD_SET(c->efd, writeset);
1.172     markus    788:                else if (!(c->flags & CHAN_EOF_SENT) &&
                    789:                    c->extended_usage == CHAN_EXTENDED_READ &&
1.44      markus    790:                    buffer_len(&c->extended) < c->remote_window)
                    791:                        FD_SET(c->efd, readset);
                    792:        }
1.204     djm       793:        /* XXX: What about efd? races? */
1.208     deraadt   794:        if (compat20 && c->ctl_fd != -1 &&
1.204     djm       795:            c->istate == CHAN_INPUT_OPEN && c->ostate == CHAN_OUTPUT_OPEN)
                    796:                FD_SET(c->ctl_fd, readset);
1.44      markus    797: }
                    798:
1.259     stevesk   799: /* ARGSUSED */
1.127     itojun    800: static void
1.237     deraadt   801: channel_pre_input_draining(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    802: {
                    803:        if (buffer_len(&c->input) == 0) {
                    804:                packet_start(SSH_MSG_CHANNEL_CLOSE);
                    805:                packet_put_int(c->remote_id);
                    806:                packet_send();
                    807:                c->type = SSH_CHANNEL_CLOSED;
1.194     markus    808:                debug2("channel %d: closing after input drain.", c->self);
1.41      markus    809:        }
                    810: }
                    811:
1.259     stevesk   812: /* ARGSUSED */
1.127     itojun    813: static void
1.237     deraadt   814: channel_pre_output_draining(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    815: {
                    816:        if (buffer_len(&c->output) == 0)
1.113     markus    817:                chan_mark_dead(c);
1.49      markus    818:        else
1.41      markus    819:                FD_SET(c->sock, writeset);
                    820: }
                    821:
                    822: /*
                    823:  * This is a special state for X11 authentication spoofing.  An opened X11
                    824:  * connection (when authentication spoofing is being done) remains in this
                    825:  * state until the first packet has been completely read.  The authentication
                    826:  * data in that packet is then substituted by the real data if it matches the
                    827:  * fake data, and the channel is put into normal mode.
1.51      markus    828:  * XXX All this happens at the client side.
1.121     markus    829:  * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
1.41      markus    830:  */
1.127     itojun    831: static int
1.121     markus    832: x11_open_helper(Buffer *b)
1.1       deraadt   833: {
1.77      markus    834:        u_char *ucp;
                    835:        u_int proto_len, data_len;
1.25      markus    836:
1.41      markus    837:        /* Check if the fixed size part of the packet is in buffer. */
1.121     markus    838:        if (buffer_len(b) < 12)
1.41      markus    839:                return 0;
                    840:
                    841:        /* Parse the lengths of variable-length fields. */
1.155     stevesk   842:        ucp = buffer_ptr(b);
1.41      markus    843:        if (ucp[0] == 0x42) {   /* Byte order MSB first. */
                    844:                proto_len = 256 * ucp[6] + ucp[7];
                    845:                data_len = 256 * ucp[8] + ucp[9];
                    846:        } else if (ucp[0] == 0x6c) {    /* Byte order LSB first. */
                    847:                proto_len = ucp[6] + 256 * ucp[7];
                    848:                data_len = ucp[8] + 256 * ucp[9];
                    849:        } else {
1.194     markus    850:                debug2("Initial X11 packet contains bad byte order byte: 0x%x",
1.148     deraadt   851:                    ucp[0]);
1.41      markus    852:                return -1;
                    853:        }
                    854:
                    855:        /* Check if the whole packet is in buffer. */
1.121     markus    856:        if (buffer_len(b) <
1.41      markus    857:            12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
                    858:                return 0;
                    859:
                    860:        /* Check if authentication protocol matches. */
                    861:        if (proto_len != strlen(x11_saved_proto) ||
                    862:            memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
1.194     markus    863:                debug2("X11 connection uses different authentication protocol.");
1.41      markus    864:                return -1;
                    865:        }
                    866:        /* Check if authentication data matches our fake data. */
                    867:        if (data_len != x11_fake_data_len ||
                    868:            memcmp(ucp + 12 + ((proto_len + 3) & ~3),
                    869:                x11_fake_data, x11_fake_data_len) != 0) {
1.194     markus    870:                debug2("X11 auth data does not match fake data.");
1.41      markus    871:                return -1;
                    872:        }
                    873:        /* Check fake data length */
                    874:        if (x11_fake_data_len != x11_saved_data_len) {
                    875:                error("X11 fake_data_len %d != saved_data_len %d",
                    876:                    x11_fake_data_len, x11_saved_data_len);
                    877:                return -1;
                    878:        }
                    879:        /*
                    880:         * Received authentication protocol and data match
                    881:         * our fake data. Substitute the fake data with real
                    882:         * data.
                    883:         */
                    884:        memcpy(ucp + 12 + ((proto_len + 3) & ~3),
                    885:            x11_saved_data, x11_saved_data_len);
                    886:        return 1;
                    887: }
                    888:
1.127     itojun    889: static void
1.237     deraadt   890: channel_pre_x11_open_13(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    891: {
1.121     markus    892:        int ret = x11_open_helper(&c->output);
1.180     deraadt   893:
1.41      markus    894:        if (ret == 1) {
                    895:                /* Start normal processing for the channel. */
                    896:                c->type = SSH_CHANNEL_OPEN;
1.47      markus    897:                channel_pre_open_13(c, readset, writeset);
1.41      markus    898:        } else if (ret == -1) {
                    899:                /*
                    900:                 * We have received an X11 connection that has bad
                    901:                 * authentication information.
                    902:                 */
1.188     itojun    903:                logit("X11 connection rejected because of wrong authentication.");
1.41      markus    904:                buffer_clear(&c->input);
                    905:                buffer_clear(&c->output);
1.132     markus    906:                channel_close_fd(&c->sock);
1.41      markus    907:                c->sock = -1;
                    908:                c->type = SSH_CHANNEL_CLOSED;
                    909:                packet_start(SSH_MSG_CHANNEL_CLOSE);
                    910:                packet_put_int(c->remote_id);
                    911:                packet_send();
                    912:        }
                    913: }
1.25      markus    914:
1.127     itojun    915: static void
1.237     deraadt   916: channel_pre_x11_open(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus    917: {
1.121     markus    918:        int ret = x11_open_helper(&c->output);
1.133     markus    919:
                    920:        /* c->force_drain = 1; */
                    921:
1.41      markus    922:        if (ret == 1) {
                    923:                c->type = SSH_CHANNEL_OPEN;
1.157     markus    924:                channel_pre_open(c, readset, writeset);
1.41      markus    925:        } else if (ret == -1) {
1.188     itojun    926:                logit("X11 connection rejected because of wrong authentication.");
1.194     markus    927:                debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
1.156     markus    928:                chan_read_failed(c);
                    929:                buffer_clear(&c->input);
                    930:                chan_ibuf_empty(c);
                    931:                buffer_clear(&c->output);
                    932:                /* for proto v1, the peer will send an IEOF */
                    933:                if (compat20)
                    934:                        chan_write_failed(c);
                    935:                else
                    936:                        c->type = SSH_CHANNEL_OPEN;
1.194     markus    937:                debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
1.41      markus    938:        }
                    939: }
1.25      markus    940:
1.104     markus    941: /* try to decode a socks4 header */
1.259     stevesk   942: /* ARGSUSED */
1.127     itojun    943: static int
1.237     deraadt   944: channel_decode_socks4(Channel *c, fd_set *readset, fd_set *writeset)
1.103     markus    945: {
1.181     markus    946:        char *p, *host;
1.217     djm       947:        u_int len, have, i, found;
1.148     deraadt   948:        char username[256];
1.103     markus    949:        struct {
                    950:                u_int8_t version;
                    951:                u_int8_t command;
                    952:                u_int16_t dest_port;
1.104     markus    953:                struct in_addr dest_addr;
1.103     markus    954:        } s4_req, s4_rsp;
                    955:
1.104     markus    956:        debug2("channel %d: decode socks4", c->self);
1.109     markus    957:
                    958:        have = buffer_len(&c->input);
                    959:        len = sizeof(s4_req);
                    960:        if (have < len)
                    961:                return 0;
                    962:        p = buffer_ptr(&c->input);
                    963:        for (found = 0, i = len; i < have; i++) {
                    964:                if (p[i] == '\0') {
                    965:                        found = 1;
                    966:                        break;
                    967:                }
                    968:                if (i > 1024) {
                    969:                        /* the peer is probably sending garbage */
                    970:                        debug("channel %d: decode socks4: too long",
                    971:                            c->self);
                    972:                        return -1;
                    973:                }
                    974:        }
                    975:        if (!found)
                    976:                return 0;
1.103     markus    977:        buffer_get(&c->input, (char *)&s4_req.version, 1);
                    978:        buffer_get(&c->input, (char *)&s4_req.command, 1);
                    979:        buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
1.104     markus    980:        buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
1.109     markus    981:        have = buffer_len(&c->input);
1.103     markus    982:        p = buffer_ptr(&c->input);
                    983:        len = strlen(p);
1.106     markus    984:        debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1.103     markus    985:        if (len > have)
1.104     markus    986:                fatal("channel %d: decode socks4: len %d > have %d",
1.103     markus    987:                    c->self, len, have);
                    988:        strlcpy(username, p, sizeof(username));
                    989:        buffer_consume(&c->input, len);
                    990:        buffer_consume(&c->input, 1);           /* trailing '\0' */
                    991:
1.104     markus    992:        host = inet_ntoa(s4_req.dest_addr);
1.103     markus    993:        strlcpy(c->path, host, sizeof(c->path));
                    994:        c->host_port = ntohs(s4_req.dest_port);
1.148     deraadt   995:
1.194     markus    996:        debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1.106     markus    997:            c->self, host, c->host_port, s4_req.command);
1.103     markus    998:
1.104     markus    999:        if (s4_req.command != 1) {
                   1000:                debug("channel %d: cannot handle: socks4 cn %d",
                   1001:                    c->self, s4_req.command);
                   1002:                return -1;
1.103     markus   1003:        }
1.104     markus   1004:        s4_rsp.version = 0;                     /* vn: 0 for reply */
                   1005:        s4_rsp.command = 90;                    /* cd: req granted */
1.103     markus   1006:        s4_rsp.dest_port = 0;                   /* ignored */
1.104     markus   1007:        s4_rsp.dest_addr.s_addr = INADDR_ANY;   /* ignored */
1.246     deraadt  1008:        buffer_append(&c->output, &s4_rsp, sizeof(s4_rsp));
1.104     markus   1009:        return 1;
                   1010: }
                   1011:
1.193     markus   1012: /* try to decode a socks5 header */
                   1013: #define SSH_SOCKS5_AUTHDONE    0x1000
                   1014: #define SSH_SOCKS5_NOAUTH      0x00
                   1015: #define SSH_SOCKS5_IPV4                0x01
                   1016: #define SSH_SOCKS5_DOMAIN      0x03
                   1017: #define SSH_SOCKS5_IPV6                0x04
                   1018: #define SSH_SOCKS5_CONNECT     0x01
                   1019: #define SSH_SOCKS5_SUCCESS     0x00
                   1020:
1.259     stevesk  1021: /* ARGSUSED */
1.193     markus   1022: static int
1.237     deraadt  1023: channel_decode_socks5(Channel *c, fd_set *readset, fd_set *writeset)
1.193     markus   1024: {
                   1025:        struct {
                   1026:                u_int8_t version;
                   1027:                u_int8_t command;
                   1028:                u_int8_t reserved;
                   1029:                u_int8_t atyp;
                   1030:        } s5_req, s5_rsp;
                   1031:        u_int16_t dest_port;
                   1032:        u_char *p, dest_addr[255+1];
1.252     djm      1033:        u_int have, need, i, found, nmethods, addrlen, af;
1.193     markus   1034:
                   1035:        debug2("channel %d: decode socks5", c->self);
                   1036:        p = buffer_ptr(&c->input);
                   1037:        if (p[0] != 0x05)
                   1038:                return -1;
                   1039:        have = buffer_len(&c->input);
                   1040:        if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
                   1041:                /* format: ver | nmethods | methods */
1.198     djm      1042:                if (have < 2)
1.193     markus   1043:                        return 0;
                   1044:                nmethods = p[1];
                   1045:                if (have < nmethods + 2)
                   1046:                        return 0;
                   1047:                /* look for method: "NO AUTHENTICATION REQUIRED" */
                   1048:                for (found = 0, i = 2 ; i < nmethods + 2; i++) {
                   1049:                        if (p[i] == SSH_SOCKS5_NOAUTH ) {
                   1050:                                found = 1;
                   1051:                                break;
                   1052:                        }
                   1053:                }
                   1054:                if (!found) {
                   1055:                        debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
                   1056:                            c->self);
                   1057:                        return -1;
                   1058:                }
                   1059:                buffer_consume(&c->input, nmethods + 2);
                   1060:                buffer_put_char(&c->output, 0x05);              /* version */
                   1061:                buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
                   1062:                FD_SET(c->sock, writeset);
                   1063:                c->flags |= SSH_SOCKS5_AUTHDONE;
                   1064:                debug2("channel %d: socks5 auth done", c->self);
                   1065:                return 0;                               /* need more */
                   1066:        }
                   1067:        debug2("channel %d: socks5 post auth", c->self);
                   1068:        if (have < sizeof(s5_req)+1)
                   1069:                return 0;                       /* need more */
1.247     deraadt  1070:        memcpy(&s5_req, p, sizeof(s5_req));
1.193     markus   1071:        if (s5_req.version != 0x05 ||
                   1072:            s5_req.command != SSH_SOCKS5_CONNECT ||
                   1073:            s5_req.reserved != 0x00) {
1.194     markus   1074:                debug2("channel %d: only socks5 connect supported", c->self);
1.193     markus   1075:                return -1;
                   1076:        }
1.213     deraadt  1077:        switch (s5_req.atyp){
1.193     markus   1078:        case SSH_SOCKS5_IPV4:
                   1079:                addrlen = 4;
                   1080:                af = AF_INET;
                   1081:                break;
                   1082:        case SSH_SOCKS5_DOMAIN:
                   1083:                addrlen = p[sizeof(s5_req)];
                   1084:                af = -1;
                   1085:                break;
                   1086:        case SSH_SOCKS5_IPV6:
                   1087:                addrlen = 16;
                   1088:                af = AF_INET6;
                   1089:                break;
                   1090:        default:
1.194     markus   1091:                debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1.193     markus   1092:                return -1;
                   1093:        }
1.252     djm      1094:        need = sizeof(s5_req) + addrlen + 2;
                   1095:        if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
                   1096:                need++;
                   1097:        if (have < need)
1.193     markus   1098:                return 0;
                   1099:        buffer_consume(&c->input, sizeof(s5_req));
                   1100:        if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
                   1101:                buffer_consume(&c->input, 1);    /* host string length */
                   1102:        buffer_get(&c->input, (char *)&dest_addr, addrlen);
                   1103:        buffer_get(&c->input, (char *)&dest_port, 2);
                   1104:        dest_addr[addrlen] = '\0';
                   1105:        if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1.201     deraadt  1106:                strlcpy(c->path, (char *)dest_addr, sizeof(c->path));
1.193     markus   1107:        else if (inet_ntop(af, dest_addr, c->path, sizeof(c->path)) == NULL)
                   1108:                return -1;
                   1109:        c->host_port = ntohs(dest_port);
1.198     djm      1110:
1.194     markus   1111:        debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1.193     markus   1112:            c->self, c->path, c->host_port, s5_req.command);
                   1113:
                   1114:        s5_rsp.version = 0x05;
                   1115:        s5_rsp.command = SSH_SOCKS5_SUCCESS;
                   1116:        s5_rsp.reserved = 0;                    /* ignored */
                   1117:        s5_rsp.atyp = SSH_SOCKS5_IPV4;
                   1118:        ((struct in_addr *)&dest_addr)->s_addr = INADDR_ANY;
                   1119:        dest_port = 0;                          /* ignored */
                   1120:
1.246     deraadt  1121:        buffer_append(&c->output, &s5_rsp, sizeof(s5_rsp));
                   1122:        buffer_append(&c->output, &dest_addr, sizeof(struct in_addr));
                   1123:        buffer_append(&c->output, &dest_port, sizeof(dest_port));
1.193     markus   1124:        return 1;
                   1125: }
                   1126:
1.104     markus   1127: /* dynamic port forwarding */
1.127     itojun   1128: static void
1.237     deraadt  1129: channel_pre_dynamic(Channel *c, fd_set *readset, fd_set *writeset)
1.104     markus   1130: {
                   1131:        u_char *p;
1.217     djm      1132:        u_int have;
                   1133:        int ret;
1.103     markus   1134:
1.104     markus   1135:        have = buffer_len(&c->input);
1.137     markus   1136:        c->delayed = 0;
1.104     markus   1137:        debug2("channel %d: pre_dynamic: have %d", c->self, have);
1.105     markus   1138:        /* buffer_dump(&c->input); */
1.104     markus   1139:        /* check if the fixed size part of the packet is in buffer. */
1.193     markus   1140:        if (have < 3) {
1.104     markus   1141:                /* need more */
                   1142:                FD_SET(c->sock, readset);
                   1143:                return;
                   1144:        }
                   1145:        /* try to guess the protocol */
                   1146:        p = buffer_ptr(&c->input);
                   1147:        switch (p[0]) {
                   1148:        case 0x04:
                   1149:                ret = channel_decode_socks4(c, readset, writeset);
1.193     markus   1150:                break;
                   1151:        case 0x05:
                   1152:                ret = channel_decode_socks5(c, readset, writeset);
1.104     markus   1153:                break;
                   1154:        default:
                   1155:                ret = -1;
                   1156:                break;
                   1157:        }
                   1158:        if (ret < 0) {
1.113     markus   1159:                chan_mark_dead(c);
1.104     markus   1160:        } else if (ret == 0) {
                   1161:                debug2("channel %d: pre_dynamic: need more", c->self);
                   1162:                /* need more */
                   1163:                FD_SET(c->sock, readset);
                   1164:        } else {
                   1165:                /* switch to the next state */
                   1166:                c->type = SSH_CHANNEL_OPENING;
                   1167:                port_open_helper(c, "direct-tcpip");
                   1168:        }
1.103     markus   1169: }
                   1170:
1.41      markus   1171: /* This is our fake X11 server socket. */
1.259     stevesk  1172: /* ARGSUSED */
1.127     itojun   1173: static void
1.237     deraadt  1174: channel_post_x11_listener(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1175: {
1.113     markus   1176:        Channel *nc;
1.41      markus   1177:        struct sockaddr addr;
1.162     stevesk  1178:        int newsock;
1.41      markus   1179:        socklen_t addrlen;
1.85      markus   1180:        char buf[16384], *remote_ipaddr;
1.51      markus   1181:        int remote_port;
1.25      markus   1182:
1.41      markus   1183:        if (FD_ISSET(c->sock, readset)) {
                   1184:                debug("X11 connection requested.");
                   1185:                addrlen = sizeof(addr);
                   1186:                newsock = accept(c->sock, &addr, &addrlen);
1.149     markus   1187:                if (c->single_connection) {
1.194     markus   1188:                        debug2("single_connection: closing X11 listener.");
1.149     markus   1189:                        channel_close_fd(&c->sock);
                   1190:                        chan_mark_dead(c);
                   1191:                }
1.41      markus   1192:                if (newsock < 0) {
                   1193:                        error("accept: %.100s", strerror(errno));
                   1194:                        return;
                   1195:                }
1.162     stevesk  1196:                set_nodelay(newsock);
1.85      markus   1197:                remote_ipaddr = get_peer_ipaddr(newsock);
1.51      markus   1198:                remote_port = get_peer_port(newsock);
1.41      markus   1199:                snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1.85      markus   1200:                    remote_ipaddr, remote_port);
1.51      markus   1201:
1.113     markus   1202:                nc = channel_new("accepted x11 socket",
1.51      markus   1203:                    SSH_CHANNEL_OPENING, newsock, newsock, -1,
1.190     markus   1204:                    c->local_window_max, c->local_maxpacket, 0, buf, 1);
1.51      markus   1205:                if (compat20) {
                   1206:                        packet_start(SSH2_MSG_CHANNEL_OPEN);
                   1207:                        packet_put_cstring("x11");
1.113     markus   1208:                        packet_put_int(nc->self);
1.149     markus   1209:                        packet_put_int(nc->local_window_max);
                   1210:                        packet_put_int(nc->local_maxpacket);
1.85      markus   1211:                        /* originator ipaddr and port */
                   1212:                        packet_put_cstring(remote_ipaddr);
1.57      markus   1213:                        if (datafellows & SSH_BUG_X11FWD) {
1.194     markus   1214:                                debug2("ssh2 x11 bug compat mode");
1.57      markus   1215:                        } else {
                   1216:                                packet_put_int(remote_port);
                   1217:                        }
1.51      markus   1218:                        packet_send();
                   1219:                } else {
                   1220:                        packet_start(SSH_SMSG_X11_OPEN);
1.113     markus   1221:                        packet_put_int(nc->self);
1.121     markus   1222:                        if (packet_get_protocol_flags() &
                   1223:                            SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1.125     markus   1224:                                packet_put_cstring(buf);
1.51      markus   1225:                        packet_send();
                   1226:                }
1.85      markus   1227:                xfree(remote_ipaddr);
1.41      markus   1228:        }
                   1229: }
1.25      markus   1230:
1.127     itojun   1231: static void
1.103     markus   1232: port_open_helper(Channel *c, char *rtype)
                   1233: {
                   1234:        int direct;
                   1235:        char buf[1024];
                   1236:        char *remote_ipaddr = get_peer_ipaddr(c->sock);
1.216     markus   1237:        int remote_port = get_peer_port(c->sock);
1.103     markus   1238:
                   1239:        direct = (strcmp(rtype, "direct-tcpip") == 0);
                   1240:
                   1241:        snprintf(buf, sizeof buf,
                   1242:            "%s: listening port %d for %.100s port %d, "
                   1243:            "connect from %.200s port %d",
                   1244:            rtype, c->listening_port, c->path, c->host_port,
                   1245:            remote_ipaddr, remote_port);
                   1246:
                   1247:        xfree(c->remote_name);
                   1248:        c->remote_name = xstrdup(buf);
                   1249:
                   1250:        if (compat20) {
                   1251:                packet_start(SSH2_MSG_CHANNEL_OPEN);
                   1252:                packet_put_cstring(rtype);
                   1253:                packet_put_int(c->self);
                   1254:                packet_put_int(c->local_window_max);
                   1255:                packet_put_int(c->local_maxpacket);
                   1256:                if (direct) {
                   1257:                        /* target host, port */
                   1258:                        packet_put_cstring(c->path);
                   1259:                        packet_put_int(c->host_port);
                   1260:                } else {
                   1261:                        /* listen address, port */
                   1262:                        packet_put_cstring(c->path);
                   1263:                        packet_put_int(c->listening_port);
                   1264:                }
                   1265:                /* originator host and port */
                   1266:                packet_put_cstring(remote_ipaddr);
1.216     markus   1267:                packet_put_int((u_int)remote_port);
1.103     markus   1268:                packet_send();
                   1269:        } else {
                   1270:                packet_start(SSH_MSG_PORT_OPEN);
                   1271:                packet_put_int(c->self);
                   1272:                packet_put_cstring(c->path);
                   1273:                packet_put_int(c->host_port);
1.121     markus   1274:                if (packet_get_protocol_flags() &
                   1275:                    SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1.103     markus   1276:                        packet_put_cstring(c->remote_name);
                   1277:                packet_send();
                   1278:        }
                   1279:        xfree(remote_ipaddr);
                   1280: }
                   1281:
1.226     djm      1282: static void
                   1283: channel_set_reuseaddr(int fd)
                   1284: {
                   1285:        int on = 1;
                   1286:
                   1287:        /*
                   1288:         * Set socket options.
                   1289:         * Allow local port reuse in TIME_WAIT.
                   1290:         */
                   1291:        if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
                   1292:                error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
                   1293: }
                   1294:
1.41      markus   1295: /*
                   1296:  * This socket is listening for connections to a forwarded TCP/IP port.
                   1297:  */
1.259     stevesk  1298: /* ARGSUSED */
1.127     itojun   1299: static void
1.237     deraadt  1300: channel_post_port_listener(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1301: {
1.103     markus   1302:        Channel *nc;
1.41      markus   1303:        struct sockaddr addr;
1.113     markus   1304:        int newsock, nextstate;
1.41      markus   1305:        socklen_t addrlen;
1.103     markus   1306:        char *rtype;
1.73      markus   1307:
1.41      markus   1308:        if (FD_ISSET(c->sock, readset)) {
                   1309:                debug("Connection to port %d forwarding "
                   1310:                    "to %.100s port %d requested.",
                   1311:                    c->listening_port, c->path, c->host_port);
1.103     markus   1312:
1.137     markus   1313:                if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
                   1314:                        nextstate = SSH_CHANNEL_OPENING;
                   1315:                        rtype = "forwarded-tcpip";
                   1316:                } else {
                   1317:                        if (c->host_port == 0) {
                   1318:                                nextstate = SSH_CHANNEL_DYNAMIC;
1.138     markus   1319:                                rtype = "dynamic-tcpip";
1.137     markus   1320:                        } else {
                   1321:                                nextstate = SSH_CHANNEL_OPENING;
                   1322:                                rtype = "direct-tcpip";
                   1323:                        }
                   1324:                }
1.103     markus   1325:
1.41      markus   1326:                addrlen = sizeof(addr);
                   1327:                newsock = accept(c->sock, &addr, &addrlen);
                   1328:                if (newsock < 0) {
                   1329:                        error("accept: %.100s", strerror(errno));
                   1330:                        return;
                   1331:                }
1.169     stevesk  1332:                set_nodelay(newsock);
1.190     markus   1333:                nc = channel_new(rtype, nextstate, newsock, newsock, -1,
                   1334:                    c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1.103     markus   1335:                nc->listening_port = c->listening_port;
                   1336:                nc->host_port = c->host_port;
                   1337:                strlcpy(nc->path, c->path, sizeof(nc->path));
                   1338:
1.137     markus   1339:                if (nextstate == SSH_CHANNEL_DYNAMIC) {
                   1340:                        /*
                   1341:                         * do not call the channel_post handler until
                   1342:                         * this flag has been reset by a pre-handler.
                   1343:                         * otherwise the FD_ISSET calls might overflow
                   1344:                         */
                   1345:                        nc->delayed = 1;
                   1346:                } else {
1.103     markus   1347:                        port_open_helper(nc, rtype);
1.137     markus   1348:                }
1.41      markus   1349:        }
                   1350: }
1.25      markus   1351:
1.41      markus   1352: /*
                   1353:  * This is the authentication agent socket listening for connections from
                   1354:  * clients.
                   1355:  */
1.259     stevesk  1356: /* ARGSUSED */
1.127     itojun   1357: static void
1.237     deraadt  1358: channel_post_auth_listener(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1359: {
1.113     markus   1360:        Channel *nc;
                   1361:        int newsock;
1.41      markus   1362:        struct sockaddr addr;
                   1363:        socklen_t addrlen;
1.25      markus   1364:
1.41      markus   1365:        if (FD_ISSET(c->sock, readset)) {
                   1366:                addrlen = sizeof(addr);
                   1367:                newsock = accept(c->sock, &addr, &addrlen);
                   1368:                if (newsock < 0) {
                   1369:                        error("accept from auth socket: %.100s", strerror(errno));
                   1370:                        return;
                   1371:                }
1.113     markus   1372:                nc = channel_new("accepted auth socket",
1.73      markus   1373:                    SSH_CHANNEL_OPENING, newsock, newsock, -1,
                   1374:                    c->local_window_max, c->local_maxpacket,
1.190     markus   1375:                    0, "accepted auth socket", 1);
1.73      markus   1376:                if (compat20) {
                   1377:                        packet_start(SSH2_MSG_CHANNEL_OPEN);
                   1378:                        packet_put_cstring("auth-agent@openssh.com");
1.113     markus   1379:                        packet_put_int(nc->self);
1.73      markus   1380:                        packet_put_int(c->local_window_max);
                   1381:                        packet_put_int(c->local_maxpacket);
                   1382:                } else {
                   1383:                        packet_start(SSH_SMSG_AGENT_OPEN);
1.113     markus   1384:                        packet_put_int(nc->self);
1.73      markus   1385:                }
1.41      markus   1386:                packet_send();
                   1387:        }
                   1388: }
1.25      markus   1389:
1.259     stevesk  1390: /* ARGSUSED */
1.127     itojun   1391: static void
1.237     deraadt  1392: channel_post_connecting(Channel *c, fd_set *readset, fd_set *writeset)
1.75      markus   1393: {
1.114     markus   1394:        int err = 0;
1.129     stevesk  1395:        socklen_t sz = sizeof(err);
1.114     markus   1396:
1.75      markus   1397:        if (FD_ISSET(c->sock, writeset)) {
1.170     stevesk  1398:                if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1.114     markus   1399:                        err = errno;
                   1400:                        error("getsockopt SO_ERROR failed");
                   1401:                }
                   1402:                if (err == 0) {
                   1403:                        debug("channel %d: connected", c->self);
                   1404:                        c->type = SSH_CHANNEL_OPEN;
                   1405:                        if (compat20) {
                   1406:                                packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1407:                                packet_put_int(c->remote_id);
                   1408:                                packet_put_int(c->self);
                   1409:                                packet_put_int(c->local_window);
                   1410:                                packet_put_int(c->local_maxpacket);
                   1411:                        } else {
                   1412:                                packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1413:                                packet_put_int(c->remote_id);
                   1414:                                packet_put_int(c->self);
                   1415:                        }
1.75      markus   1416:                } else {
1.114     markus   1417:                        debug("channel %d: not connected: %s",
                   1418:                            c->self, strerror(err));
                   1419:                        if (compat20) {
                   1420:                                packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
                   1421:                                packet_put_int(c->remote_id);
                   1422:                                packet_put_int(SSH2_OPEN_CONNECT_FAILED);
                   1423:                                if (!(datafellows & SSH_BUG_OPENFAILURE)) {
                   1424:                                        packet_put_cstring(strerror(err));
                   1425:                                        packet_put_cstring("");
                   1426:                                }
1.75      markus   1427:                        } else {
1.114     markus   1428:                                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   1429:                                packet_put_int(c->remote_id);
1.75      markus   1430:                        }
1.114     markus   1431:                        chan_mark_dead(c);
1.75      markus   1432:                }
1.114     markus   1433:                packet_send();
1.75      markus   1434:        }
                   1435: }
                   1436:
1.259     stevesk  1437: /* ARGSUSED */
1.127     itojun   1438: static int
1.237     deraadt  1439: channel_handle_rfd(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1440: {
1.214     markus   1441:        char buf[CHAN_RBUF];
1.41      markus   1442:        int len;
1.25      markus   1443:
1.118     markus   1444:        if (c->rfd != -1 &&
1.41      markus   1445:            FD_ISSET(c->rfd, readset)) {
                   1446:                len = read(c->rfd, buf, sizeof(buf));
1.53      markus   1447:                if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1448:                        return 1;
1.41      markus   1449:                if (len <= 0) {
1.194     markus   1450:                        debug2("channel %d: read<=0 rfd %d len %d",
1.41      markus   1451:                            c->self, c->rfd, len);
1.104     markus   1452:                        if (c->type != SSH_CHANNEL_OPEN) {
1.194     markus   1453:                                debug2("channel %d: not open", c->self);
1.113     markus   1454:                                chan_mark_dead(c);
1.103     markus   1455:                                return -1;
1.104     markus   1456:                        } else if (compat13) {
1.158     markus   1457:                                buffer_clear(&c->output);
1.41      markus   1458:                                c->type = SSH_CHANNEL_INPUT_DRAINING;
1.194     markus   1459:                                debug2("channel %d: input draining.", c->self);
1.25      markus   1460:                        } else {
1.41      markus   1461:                                chan_read_failed(c);
1.25      markus   1462:                        }
1.41      markus   1463:                        return -1;
                   1464:                }
1.143     deraadt  1465:                if (c->input_filter != NULL) {
1.66      markus   1466:                        if (c->input_filter(c, buf, len) == -1) {
1.194     markus   1467:                                debug2("channel %d: filter stops", c->self);
1.65      markus   1468:                                chan_read_failed(c);
                   1469:                        }
1.228     reyk     1470:                } else if (c->datagram) {
                   1471:                        buffer_put_string(&c->input, buf, len);
1.65      markus   1472:                } else {
                   1473:                        buffer_append(&c->input, buf, len);
                   1474:                }
1.41      markus   1475:        }
                   1476:        return 1;
                   1477: }
1.241     deraadt  1478:
1.259     stevesk  1479: /* ARGSUSED */
1.127     itojun   1480: static int
1.237     deraadt  1481: channel_handle_wfd(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1482: {
1.95      markus   1483:        struct termios tio;
1.231     reyk     1484:        u_char *data = NULL, *buf;
1.134     markus   1485:        u_int dlen;
1.41      markus   1486:        int len;
1.25      markus   1487:
1.41      markus   1488:        /* Send buffered output data to the socket. */
1.118     markus   1489:        if (c->wfd != -1 &&
1.41      markus   1490:            FD_ISSET(c->wfd, writeset) &&
                   1491:            buffer_len(&c->output) > 0) {
1.231     reyk     1492:                if (c->output_filter != NULL) {
                   1493:                        if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
                   1494:                                debug2("channel %d: filter stops", c->self);
1.232     reyk     1495:                                if (c->type != SSH_CHANNEL_OPEN)
                   1496:                                        chan_mark_dead(c);
                   1497:                                else
                   1498:                                        chan_write_failed(c);
                   1499:                                return -1;
1.231     reyk     1500:                        }
                   1501:                } else if (c->datagram) {
                   1502:                        buf = data = buffer_get_string(&c->output, &dlen);
                   1503:                } else {
                   1504:                        buf = data = buffer_ptr(&c->output);
                   1505:                        dlen = buffer_len(&c->output);
                   1506:                }
                   1507:
1.228     reyk     1508:                if (c->datagram) {
                   1509:                        /* ignore truncated writes, datagrams might get lost */
                   1510:                        c->local_consumed += dlen + 4;
1.231     reyk     1511:                        len = write(c->wfd, buf, dlen);
1.228     reyk     1512:                        xfree(data);
                   1513:                        if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1514:                                return 1;
                   1515:                        if (len <= 0) {
                   1516:                                if (c->type != SSH_CHANNEL_OPEN)
                   1517:                                        chan_mark_dead(c);
                   1518:                                else
                   1519:                                        chan_write_failed(c);
                   1520:                                return -1;
                   1521:                        }
                   1522:                        return 1;
                   1523:                }
1.231     reyk     1524:
                   1525:                len = write(c->wfd, buf, dlen);
1.53      markus   1526:                if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1527:                        return 1;
1.41      markus   1528:                if (len <= 0) {
1.104     markus   1529:                        if (c->type != SSH_CHANNEL_OPEN) {
1.194     markus   1530:                                debug2("channel %d: not open", c->self);
1.113     markus   1531:                                chan_mark_dead(c);
1.104     markus   1532:                                return -1;
                   1533:                        } else if (compat13) {
1.158     markus   1534:                                buffer_clear(&c->output);
1.194     markus   1535:                                debug2("channel %d: input draining.", c->self);
1.41      markus   1536:                                c->type = SSH_CHANNEL_INPUT_DRAINING;
                   1537:                        } else {
                   1538:                                chan_write_failed(c);
                   1539:                        }
                   1540:                        return -1;
1.91      markus   1541:                }
1.231     reyk     1542:                if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
1.91      markus   1543:                        if (tcgetattr(c->wfd, &tio) == 0 &&
                   1544:                            !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
                   1545:                                /*
                   1546:                                 * Simulate echo to reduce the impact of
1.96      markus   1547:                                 * traffic analysis. We need to match the
1.95      markus   1548:                                 * size of a SSH2_MSG_CHANNEL_DATA message
1.231     reyk     1549:                                 * (4 byte channel id + buf)
1.91      markus   1550:                                 */
1.95      markus   1551:                                packet_send_ignore(4 + len);
1.91      markus   1552:                                packet_send();
                   1553:                        }
1.25      markus   1554:                }
1.41      markus   1555:                buffer_consume(&c->output, len);
1.44      markus   1556:                if (compat20 && len > 0) {
                   1557:                        c->local_consumed += len;
                   1558:                }
                   1559:        }
                   1560:        return 1;
                   1561: }
1.241     deraadt  1562:
1.127     itojun   1563: static int
1.237     deraadt  1564: channel_handle_efd(Channel *c, fd_set *readset, fd_set *writeset)
1.44      markus   1565: {
1.214     markus   1566:        char buf[CHAN_RBUF];
1.44      markus   1567:        int len;
                   1568:
1.45      markus   1569: /** XXX handle drain efd, too */
1.44      markus   1570:        if (c->efd != -1) {
                   1571:                if (c->extended_usage == CHAN_EXTENDED_WRITE &&
                   1572:                    FD_ISSET(c->efd, writeset) &&
                   1573:                    buffer_len(&c->extended) > 0) {
                   1574:                        len = write(c->efd, buffer_ptr(&c->extended),
                   1575:                            buffer_len(&c->extended));
1.70      markus   1576:                        debug2("channel %d: written %d to efd %d",
1.44      markus   1577:                            c->self, len, c->efd);
1.93      markus   1578:                        if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1579:                                return 1;
                   1580:                        if (len <= 0) {
                   1581:                                debug2("channel %d: closing write-efd %d",
                   1582:                                    c->self, c->efd);
1.132     markus   1583:                                channel_close_fd(&c->efd);
1.93      markus   1584:                        } else {
1.44      markus   1585:                                buffer_consume(&c->extended, len);
                   1586:                                c->local_consumed += len;
                   1587:                        }
                   1588:                } else if (c->extended_usage == CHAN_EXTENDED_READ &&
                   1589:                    FD_ISSET(c->efd, readset)) {
                   1590:                        len = read(c->efd, buf, sizeof(buf));
1.70      markus   1591:                        debug2("channel %d: read %d from efd %d",
1.148     deraadt  1592:                            c->self, len, c->efd);
1.93      markus   1593:                        if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1594:                                return 1;
                   1595:                        if (len <= 0) {
                   1596:                                debug2("channel %d: closing read-efd %d",
1.45      markus   1597:                                    c->self, c->efd);
1.132     markus   1598:                                channel_close_fd(&c->efd);
1.93      markus   1599:                        } else {
1.44      markus   1600:                                buffer_append(&c->extended, buf, len);
1.93      markus   1601:                        }
1.44      markus   1602:                }
                   1603:        }
                   1604:        return 1;
                   1605: }
1.241     deraadt  1606:
1.259     stevesk  1607: /* ARGSUSED */
1.127     itojun   1608: static int
1.237     deraadt  1609: channel_handle_ctl(Channel *c, fd_set *readset, fd_set *writeset)
1.204     djm      1610: {
                   1611:        char buf[16];
                   1612:        int len;
                   1613:
                   1614:        /* Monitor control fd to detect if the slave client exits */
                   1615:        if (c->ctl_fd != -1 && FD_ISSET(c->ctl_fd, readset)) {
                   1616:                len = read(c->ctl_fd, buf, sizeof(buf));
                   1617:                if (len < 0 && (errno == EINTR || errno == EAGAIN))
                   1618:                        return 1;
                   1619:                if (len <= 0) {
                   1620:                        debug2("channel %d: ctl read<=0", c->self);
                   1621:                        if (c->type != SSH_CHANNEL_OPEN) {
                   1622:                                debug2("channel %d: not open", c->self);
                   1623:                                chan_mark_dead(c);
                   1624:                                return -1;
                   1625:                        } else {
                   1626:                                chan_read_failed(c);
                   1627:                                chan_write_failed(c);
                   1628:                        }
                   1629:                        return -1;
                   1630:                } else
                   1631:                        fatal("%s: unexpected data on ctl fd", __func__);
                   1632:        }
                   1633:        return 1;
                   1634: }
1.241     deraadt  1635:
1.204     djm      1636: static int
1.93      markus   1637: channel_check_window(Channel *c)
1.44      markus   1638: {
1.104     markus   1639:        if (c->type == SSH_CHANNEL_OPEN &&
                   1640:            !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1.44      markus   1641:            c->local_window < c->local_window_max/2 &&
                   1642:            c->local_consumed > 0) {
                   1643:                packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
                   1644:                packet_put_int(c->remote_id);
                   1645:                packet_put_int(c->local_consumed);
                   1646:                packet_send();
1.70      markus   1647:                debug2("channel %d: window %d sent adjust %d",
1.44      markus   1648:                    c->self, c->local_window,
                   1649:                    c->local_consumed);
                   1650:                c->local_window += c->local_consumed;
                   1651:                c->local_consumed = 0;
1.1       deraadt  1652:        }
1.41      markus   1653:        return 1;
1.1       deraadt  1654: }
                   1655:
1.127     itojun   1656: static void
1.237     deraadt  1657: channel_post_open(Channel *c, fd_set *readset, fd_set *writeset)
1.41      markus   1658: {
1.137     markus   1659:        if (c->delayed)
                   1660:                return;
1.41      markus   1661:        channel_handle_rfd(c, readset, writeset);
                   1662:        channel_handle_wfd(c, readset, writeset);
1.157     markus   1663:        if (!compat20)
1.137     markus   1664:                return;
1.44      markus   1665:        channel_handle_efd(c, readset, writeset);
1.204     djm      1666:        channel_handle_ctl(c, readset, writeset);
1.93      markus   1667:        channel_check_window(c);
1.44      markus   1668: }
                   1669:
1.259     stevesk  1670: /* ARGSUSED */
1.127     itojun   1671: static void
1.237     deraadt  1672: channel_post_output_drain_13(Channel *c, fd_set *readset, fd_set *writeset)
1.1       deraadt  1673: {
1.41      markus   1674:        int len;
1.180     deraadt  1675:
1.41      markus   1676:        /* Send buffered output data to the socket. */
                   1677:        if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
                   1678:                len = write(c->sock, buffer_ptr(&c->output),
                   1679:                            buffer_len(&c->output));
                   1680:                if (len <= 0)
1.158     markus   1681:                        buffer_clear(&c->output);
1.41      markus   1682:                else
                   1683:                        buffer_consume(&c->output, len);
                   1684:        }
                   1685: }
1.25      markus   1686:
1.127     itojun   1687: static void
1.44      markus   1688: channel_handler_init_20(void)
                   1689: {
1.157     markus   1690:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open;
1.51      markus   1691:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
1.44      markus   1692:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
1.73      markus   1693:        channel_pre[SSH_CHANNEL_RPORT_LISTENER] =       &channel_pre_listener;
1.51      markus   1694:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
1.73      markus   1695:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1.75      markus   1696:        channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1.103     markus   1697:        channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1.44      markus   1698:
1.157     markus   1699:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open;
1.44      markus   1700:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
1.73      markus   1701:        channel_post[SSH_CHANNEL_RPORT_LISTENER] =      &channel_post_port_listener;
1.51      markus   1702:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
1.73      markus   1703:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1.75      markus   1704:        channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1.157     markus   1705:        channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
1.44      markus   1706: }
                   1707:
1.127     itojun   1708: static void
1.41      markus   1709: channel_handler_init_13(void)
                   1710: {
                   1711:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_13;
                   1712:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open_13;
                   1713:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
                   1714:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
                   1715:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
                   1716:        channel_pre[SSH_CHANNEL_INPUT_DRAINING] =       &channel_pre_input_draining;
                   1717:        channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] =      &channel_pre_output_draining;
1.75      markus   1718:        channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1.103     markus   1719:        channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1.25      markus   1720:
1.157     markus   1721:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open;
1.41      markus   1722:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
                   1723:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
                   1724:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
                   1725:        channel_post[SSH_CHANNEL_OUTPUT_DRAINING] =     &channel_post_output_drain_13;
1.75      markus   1726:        channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1.157     markus   1727:        channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
1.41      markus   1728: }
1.25      markus   1729:
1.127     itojun   1730: static void
1.41      markus   1731: channel_handler_init_15(void)
                   1732: {
1.157     markus   1733:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open;
1.51      markus   1734:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
1.41      markus   1735:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
                   1736:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
                   1737:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1.75      markus   1738:        channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1.103     markus   1739:        channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1.25      markus   1740:
1.41      markus   1741:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
                   1742:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
                   1743:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1.157     markus   1744:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open;
1.75      markus   1745:        channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1.157     markus   1746:        channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
1.41      markus   1747: }
1.27      markus   1748:
1.127     itojun   1749: static void
1.41      markus   1750: channel_handler_init(void)
                   1751: {
                   1752:        int i;
1.180     deraadt  1753:
1.148     deraadt  1754:        for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1.41      markus   1755:                channel_pre[i] = NULL;
                   1756:                channel_post[i] = NULL;
                   1757:        }
1.44      markus   1758:        if (compat20)
                   1759:                channel_handler_init_20();
                   1760:        else if (compat13)
1.41      markus   1761:                channel_handler_init_13();
                   1762:        else
                   1763:                channel_handler_init_15();
                   1764: }
1.25      markus   1765:
1.140     markus   1766: /* gc dead channels */
                   1767: static void
                   1768: channel_garbage_collect(Channel *c)
                   1769: {
                   1770:        if (c == NULL)
                   1771:                return;
                   1772:        if (c->detach_user != NULL) {
1.225     djm      1773:                if (!chan_is_dead(c, c->detach_close))
1.140     markus   1774:                        return;
1.194     markus   1775:                debug2("channel %d: gc: notify user", c->self);
1.140     markus   1776:                c->detach_user(c->self, NULL);
                   1777:                /* if we still have a callback */
                   1778:                if (c->detach_user != NULL)
                   1779:                        return;
1.194     markus   1780:                debug2("channel %d: gc: user detached", c->self);
1.140     markus   1781:        }
                   1782:        if (!chan_is_dead(c, 1))
                   1783:                return;
1.194     markus   1784:        debug2("channel %d: garbage collecting", c->self);
1.140     markus   1785:        channel_free(c);
                   1786: }
                   1787:
1.127     itojun   1788: static void
1.237     deraadt  1789: channel_handler(chan_fn *ftab[], fd_set *readset, fd_set *writeset)
1.41      markus   1790: {
                   1791:        static int did_init = 0;
1.209     avsm     1792:        u_int i;
1.41      markus   1793:        Channel *c;
1.25      markus   1794:
1.41      markus   1795:        if (!did_init) {
                   1796:                channel_handler_init();
                   1797:                did_init = 1;
                   1798:        }
                   1799:        for (i = 0; i < channels_alloc; i++) {
1.113     markus   1800:                c = channels[i];
                   1801:                if (c == NULL)
1.41      markus   1802:                        continue;
1.118     markus   1803:                if (ftab[c->type] != NULL)
                   1804:                        (*ftab[c->type])(c, readset, writeset);
1.140     markus   1805:                channel_garbage_collect(c);
1.1       deraadt  1806:        }
                   1807: }
                   1808:
1.121     markus   1809: /*
                   1810:  * Allocate/update select bitmasks and add any bits relevant to channels in
                   1811:  * select bitmasks.
                   1812:  */
1.49      markus   1813: void
1.100     markus   1814: channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1.209     avsm     1815:     u_int *nallocp, int rekeying)
1.41      markus   1816: {
1.243     djm      1817:        u_int n, sz, nfdset;
1.84      markus   1818:
                   1819:        n = MAX(*maxfdp, channel_max_fd);
                   1820:
1.243     djm      1821:        nfdset = howmany(n+1, NFDBITS);
                   1822:        /* Explicitly test here, because xrealloc isn't always called */
                   1823:        if (nfdset && SIZE_T_MAX / nfdset < sizeof(fd_mask))
                   1824:                fatal("channel_prepare_select: max_fd (%d) is too large", n);
                   1825:        sz = nfdset * sizeof(fd_mask);
                   1826:
1.132     markus   1827:        /* perhaps check sz < nalloc/2 and shrink? */
                   1828:        if (*readsetp == NULL || sz > *nallocp) {
1.243     djm      1829:                *readsetp = xrealloc(*readsetp, nfdset, sizeof(fd_mask));
                   1830:                *writesetp = xrealloc(*writesetp, nfdset, sizeof(fd_mask));
1.132     markus   1831:                *nallocp = sz;
1.84      markus   1832:        }
1.132     markus   1833:        *maxfdp = n;
1.84      markus   1834:        memset(*readsetp, 0, sz);
                   1835:        memset(*writesetp, 0, sz);
                   1836:
1.100     markus   1837:        if (!rekeying)
                   1838:                channel_handler(channel_pre, *readsetp, *writesetp);
1.41      markus   1839: }
                   1840:
1.121     markus   1841: /*
                   1842:  * After select, perform any appropriate operations for channels which have
                   1843:  * events pending.
                   1844:  */
1.49      markus   1845: void
1.237     deraadt  1846: channel_after_select(fd_set *readset, fd_set *writeset)
1.41      markus   1847: {
                   1848:        channel_handler(channel_post, readset, writeset);
                   1849: }
                   1850:
1.121     markus   1851:
1.84      markus   1852: /* If there is data to send to the connection, enqueue some of it now. */
1.49      markus   1853: void
1.142     itojun   1854: channel_output_poll(void)
1.1       deraadt  1855: {
1.41      markus   1856:        Channel *c;
1.209     avsm     1857:        u_int i, len;
1.1       deraadt  1858:
1.25      markus   1859:        for (i = 0; i < channels_alloc; i++) {
1.113     markus   1860:                c = channels[i];
                   1861:                if (c == NULL)
                   1862:                        continue;
1.37      markus   1863:
1.121     markus   1864:                /*
                   1865:                 * We are only interested in channels that can have buffered
                   1866:                 * incoming data.
                   1867:                 */
1.37      markus   1868:                if (compat13) {
1.41      markus   1869:                        if (c->type != SSH_CHANNEL_OPEN &&
                   1870:                            c->type != SSH_CHANNEL_INPUT_DRAINING)
1.37      markus   1871:                                continue;
                   1872:                } else {
1.41      markus   1873:                        if (c->type != SSH_CHANNEL_OPEN)
1.37      markus   1874:                                continue;
                   1875:                }
1.46      markus   1876:                if (compat20 &&
                   1877:                    (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1.93      markus   1878:                        /* XXX is this true? */
1.140     markus   1879:                        debug3("channel %d: will not send data after close", c->self);
1.44      markus   1880:                        continue;
                   1881:                }
1.25      markus   1882:
                   1883:                /* Get the amount of buffered data for this channel. */
1.93      markus   1884:                if ((c->istate == CHAN_INPUT_OPEN ||
                   1885:                    c->istate == CHAN_INPUT_WAIT_DRAIN) &&
                   1886:                    (len = buffer_len(&c->input)) > 0) {
1.228     reyk     1887:                        if (c->datagram) {
                   1888:                                if (len > 0) {
                   1889:                                        u_char *data;
                   1890:                                        u_int dlen;
                   1891:
                   1892:                                        data = buffer_get_string(&c->input,
                   1893:                                            &dlen);
                   1894:                                        packet_start(SSH2_MSG_CHANNEL_DATA);
                   1895:                                        packet_put_int(c->remote_id);
                   1896:                                        packet_put_string(data, dlen);
                   1897:                                        packet_send();
                   1898:                                        c->remote_window -= dlen + 4;
                   1899:                                        xfree(data);
                   1900:                                }
                   1901:                                continue;
                   1902:                        }
1.121     markus   1903:                        /*
                   1904:                         * Send some data for the other side over the secure
                   1905:                         * connection.
                   1906:                         */
1.44      markus   1907:                        if (compat20) {
                   1908:                                if (len > c->remote_window)
                   1909:                                        len = c->remote_window;
                   1910:                                if (len > c->remote_maxpacket)
                   1911:                                        len = c->remote_maxpacket;
1.25      markus   1912:                        } else {
1.44      markus   1913:                                if (packet_is_interactive()) {
                   1914:                                        if (len > 1024)
                   1915:                                                len = 512;
                   1916:                                } else {
                   1917:                                        /* Keep the packets at reasonable size. */
                   1918:                                        if (len > packet_get_maxsize()/2)
                   1919:                                                len = packet_get_maxsize()/2;
                   1920:                                }
1.25      markus   1921:                        }
1.41      markus   1922:                        if (len > 0) {
1.44      markus   1923:                                packet_start(compat20 ?
                   1924:                                    SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1.41      markus   1925:                                packet_put_int(c->remote_id);
                   1926:                                packet_put_string(buffer_ptr(&c->input), len);
                   1927:                                packet_send();
                   1928:                                buffer_consume(&c->input, len);
                   1929:                                c->remote_window -= len;
                   1930:                        }
                   1931:                } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1.25      markus   1932:                        if (compat13)
                   1933:                                fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1.27      markus   1934:                        /*
                   1935:                         * input-buffer is empty and read-socket shutdown:
1.172     markus   1936:                         * tell peer, that we will not send more data: send IEOF.
                   1937:                         * hack for extended data: delay EOF if EFD still in use.
1.27      markus   1938:                         */
1.172     markus   1939:                        if (CHANNEL_EFD_INPUT_ACTIVE(c))
1.223     djm      1940:                                debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
                   1941:                                    c->self, c->efd, buffer_len(&c->extended));
1.172     markus   1942:                        else
                   1943:                                chan_ibuf_empty(c);
1.25      markus   1944:                }
1.44      markus   1945:                /* Send extended data, i.e. stderr */
                   1946:                if (compat20 &&
1.172     markus   1947:                    !(c->flags & CHAN_EOF_SENT) &&
1.44      markus   1948:                    c->remote_window > 0 &&
                   1949:                    (len = buffer_len(&c->extended)) > 0 &&
                   1950:                    c->extended_usage == CHAN_EXTENDED_READ) {
1.178     markus   1951:                        debug2("channel %d: rwin %u elen %u euse %d",
1.93      markus   1952:                            c->self, c->remote_window, buffer_len(&c->extended),
                   1953:                            c->extended_usage);
1.44      markus   1954:                        if (len > c->remote_window)
                   1955:                                len = c->remote_window;
                   1956:                        if (len > c->remote_maxpacket)
                   1957:                                len = c->remote_maxpacket;
                   1958:                        packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
                   1959:                        packet_put_int(c->remote_id);
                   1960:                        packet_put_int(SSH2_EXTENDED_DATA_STDERR);
                   1961:                        packet_put_string(buffer_ptr(&c->extended), len);
                   1962:                        packet_send();
                   1963:                        buffer_consume(&c->extended, len);
                   1964:                        c->remote_window -= len;
1.93      markus   1965:                        debug2("channel %d: sent ext data %d", c->self, len);
1.44      markus   1966:                }
1.25      markus   1967:        }
1.1       deraadt  1968: }
                   1969:
1.121     markus   1970:
                   1971: /* -- protocol input */
1.249     djm      1972:
                   1973: /* ARGSUSED */
1.49      markus   1974: void
1.154     markus   1975: channel_input_data(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  1976: {
1.37      markus   1977:        int id;
1.25      markus   1978:        char *data;
1.77      markus   1979:        u_int data_len;
1.41      markus   1980:        Channel *c;
1.25      markus   1981:
                   1982:        /* Get the channel number and verify it. */
1.37      markus   1983:        id = packet_get_int();
1.41      markus   1984:        c = channel_lookup(id);
                   1985:        if (c == NULL)
1.37      markus   1986:                packet_disconnect("Received data for nonexistent channel %d.", id);
1.25      markus   1987:
                   1988:        /* Ignore any data for non-open channels (might happen on close) */
1.41      markus   1989:        if (c->type != SSH_CHANNEL_OPEN &&
                   1990:            c->type != SSH_CHANNEL_X11_OPEN)
1.37      markus   1991:                return;
                   1992:
1.25      markus   1993:        /* Get the data. */
                   1994:        data = packet_get_string(&data_len);
1.200     markus   1995:
                   1996:        /*
                   1997:         * Ignore data for protocol > 1.3 if output end is no longer open.
                   1998:         * For protocol 2 the sending side is reducing its window as it sends
                   1999:         * data, so we must 'fake' consumption of the data in order to ensure
                   2000:         * that window updates are sent back.  Otherwise the connection might
                   2001:         * deadlock.
                   2002:         */
                   2003:        if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
                   2004:                if (compat20) {
                   2005:                        c->local_window -= data_len;
                   2006:                        c->local_consumed += data_len;
                   2007:                }
                   2008:                xfree(data);
                   2009:                return;
                   2010:        }
1.41      markus   2011:
1.143     deraadt  2012:        if (compat20) {
1.44      markus   2013:                if (data_len > c->local_maxpacket) {
1.188     itojun   2014:                        logit("channel %d: rcvd big packet %d, maxpack %d",
1.44      markus   2015:                            c->self, data_len, c->local_maxpacket);
                   2016:                }
                   2017:                if (data_len > c->local_window) {
1.188     itojun   2018:                        logit("channel %d: rcvd too much data %d, win %d",
1.44      markus   2019:                            c->self, data_len, c->local_window);
                   2020:                        xfree(data);
                   2021:                        return;
                   2022:                }
                   2023:                c->local_window -= data_len;
                   2024:        }
1.152     markus   2025:        packet_check_eom();
1.228     reyk     2026:        if (c->datagram)
                   2027:                buffer_put_string(&c->output, data, data_len);
                   2028:        else
                   2029:                buffer_append(&c->output, data, data_len);
1.25      markus   2030:        xfree(data);
1.1       deraadt  2031: }
1.121     markus   2032:
1.249     djm      2033: /* ARGSUSED */
1.49      markus   2034: void
1.154     markus   2035: channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
1.44      markus   2036: {
                   2037:        int id;
                   2038:        char *data;
1.177     markus   2039:        u_int data_len, tcode;
1.44      markus   2040:        Channel *c;
                   2041:
                   2042:        /* Get the channel number and verify it. */
                   2043:        id = packet_get_int();
                   2044:        c = channel_lookup(id);
                   2045:
                   2046:        if (c == NULL)
                   2047:                packet_disconnect("Received extended_data for bad channel %d.", id);
                   2048:        if (c->type != SSH_CHANNEL_OPEN) {
1.188     itojun   2049:                logit("channel %d: ext data for non open", id);
1.44      markus   2050:                return;
1.172     markus   2051:        }
                   2052:        if (c->flags & CHAN_EOF_RCVD) {
                   2053:                if (datafellows & SSH_BUG_EXTEOF)
                   2054:                        debug("channel %d: accepting ext data after eof", id);
                   2055:                else
                   2056:                        packet_disconnect("Received extended_data after EOF "
                   2057:                            "on channel %d.", id);
1.44      markus   2058:        }
                   2059:        tcode = packet_get_int();
                   2060:        if (c->efd == -1 ||
                   2061:            c->extended_usage != CHAN_EXTENDED_WRITE ||
                   2062:            tcode != SSH2_EXTENDED_DATA_STDERR) {
1.188     itojun   2063:                logit("channel %d: bad ext data", c->self);
1.44      markus   2064:                return;
                   2065:        }
                   2066:        data = packet_get_string(&data_len);
1.152     markus   2067:        packet_check_eom();
1.44      markus   2068:        if (data_len > c->local_window) {
1.188     itojun   2069:                logit("channel %d: rcvd too much extended_data %d, win %d",
1.44      markus   2070:                    c->self, data_len, c->local_window);
                   2071:                xfree(data);
                   2072:                return;
                   2073:        }
1.70      markus   2074:        debug2("channel %d: rcvd ext data %d", c->self, data_len);
1.44      markus   2075:        c->local_window -= data_len;
                   2076:        buffer_append(&c->extended, data, data_len);
                   2077:        xfree(data);
                   2078: }
                   2079:
1.249     djm      2080: /* ARGSUSED */
1.49      markus   2081: void
1.154     markus   2082: channel_input_ieof(int type, u_int32_t seq, void *ctxt)
1.41      markus   2083: {
                   2084:        int id;
                   2085:        Channel *c;
                   2086:
                   2087:        id = packet_get_int();
1.152     markus   2088:        packet_check_eom();
1.41      markus   2089:        c = channel_lookup(id);
                   2090:        if (c == NULL)
                   2091:                packet_disconnect("Received ieof for nonexistent channel %d.", id);
                   2092:        chan_rcvd_ieof(c);
1.133     markus   2093:
                   2094:        /* XXX force input close */
1.156     markus   2095:        if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
1.133     markus   2096:                debug("channel %d: FORCE input drain", c->self);
                   2097:                c->istate = CHAN_INPUT_WAIT_DRAIN;
1.161     markus   2098:                if (buffer_len(&c->input) == 0)
                   2099:                        chan_ibuf_empty(c);
1.133     markus   2100:        }
                   2101:
1.41      markus   2102: }
1.1       deraadt  2103:
1.249     djm      2104: /* ARGSUSED */
1.49      markus   2105: void
1.154     markus   2106: channel_input_close(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2107: {
1.41      markus   2108:        int id;
                   2109:        Channel *c;
1.1       deraadt  2110:
1.41      markus   2111:        id = packet_get_int();
1.152     markus   2112:        packet_check_eom();
1.41      markus   2113:        c = channel_lookup(id);
                   2114:        if (c == NULL)
                   2115:                packet_disconnect("Received close for nonexistent channel %d.", id);
1.27      markus   2116:
                   2117:        /*
                   2118:         * Send a confirmation that we have closed the channel and no more
                   2119:         * data is coming for it.
                   2120:         */
1.25      markus   2121:        packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1.41      markus   2122:        packet_put_int(c->remote_id);
1.25      markus   2123:        packet_send();
                   2124:
1.27      markus   2125:        /*
                   2126:         * If the channel is in closed state, we have sent a close request,
                   2127:         * and the other side will eventually respond with a confirmation.
                   2128:         * Thus, we cannot free the channel here, because then there would be
                   2129:         * no-one to receive the confirmation.  The channel gets freed when
                   2130:         * the confirmation arrives.
                   2131:         */
1.41      markus   2132:        if (c->type != SSH_CHANNEL_CLOSED) {
1.27      markus   2133:                /*
                   2134:                 * Not a closed channel - mark it as draining, which will
                   2135:                 * cause it to be freed later.
                   2136:                 */
1.158     markus   2137:                buffer_clear(&c->input);
1.41      markus   2138:                c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1.25      markus   2139:        }
1.1       deraadt  2140: }
                   2141:
1.41      markus   2142: /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1.249     djm      2143: /* ARGSUSED */
1.49      markus   2144: void
1.154     markus   2145: channel_input_oclose(int type, u_int32_t seq, void *ctxt)
1.41      markus   2146: {
                   2147:        int id = packet_get_int();
                   2148:        Channel *c = channel_lookup(id);
1.151     markus   2149:
1.152     markus   2150:        packet_check_eom();
1.41      markus   2151:        if (c == NULL)
                   2152:                packet_disconnect("Received oclose for nonexistent channel %d.", id);
                   2153:        chan_rcvd_oclose(c);
                   2154: }
1.1       deraadt  2155:
1.249     djm      2156: /* ARGSUSED */
1.49      markus   2157: void
1.154     markus   2158: channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2159: {
1.41      markus   2160:        int id = packet_get_int();
                   2161:        Channel *c = channel_lookup(id);
1.1       deraadt  2162:
1.152     markus   2163:        packet_check_eom();
1.41      markus   2164:        if (c == NULL)
                   2165:                packet_disconnect("Received close confirmation for "
                   2166:                    "out-of-range channel %d.", id);
                   2167:        if (c->type != SSH_CHANNEL_CLOSED)
                   2168:                packet_disconnect("Received close confirmation for "
                   2169:                    "non-closed channel %d (type %d).", id, c->type);
1.113     markus   2170:        channel_free(c);
1.1       deraadt  2171: }
                   2172:
1.249     djm      2173: /* ARGSUSED */
1.49      markus   2174: void
1.154     markus   2175: channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2176: {
1.41      markus   2177:        int id, remote_id;
                   2178:        Channel *c;
1.1       deraadt  2179:
1.41      markus   2180:        id = packet_get_int();
                   2181:        c = channel_lookup(id);
1.25      markus   2182:
1.41      markus   2183:        if (c==NULL || c->type != SSH_CHANNEL_OPENING)
                   2184:                packet_disconnect("Received open confirmation for "
                   2185:                    "non-opening channel %d.", id);
                   2186:        remote_id = packet_get_int();
1.27      markus   2187:        /* Record the remote channel number and mark that the channel is now open. */
1.41      markus   2188:        c->remote_id = remote_id;
                   2189:        c->type = SSH_CHANNEL_OPEN;
1.44      markus   2190:
                   2191:        if (compat20) {
                   2192:                c->remote_window = packet_get_int();
                   2193:                c->remote_maxpacket = packet_get_int();
1.165     markus   2194:                if (c->confirm) {
1.70      markus   2195:                        debug2("callback start");
1.204     djm      2196:                        c->confirm(c->self, c->confirm_ctx);
1.70      markus   2197:                        debug2("callback done");
1.44      markus   2198:                }
1.194     markus   2199:                debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
1.44      markus   2200:                    c->remote_window, c->remote_maxpacket);
                   2201:        }
1.152     markus   2202:        packet_check_eom();
1.1       deraadt  2203: }
                   2204:
1.127     itojun   2205: static char *
1.114     markus   2206: reason2txt(int reason)
                   2207: {
1.143     deraadt  2208:        switch (reason) {
1.114     markus   2209:        case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
                   2210:                return "administratively prohibited";
                   2211:        case SSH2_OPEN_CONNECT_FAILED:
                   2212:                return "connect failed";
                   2213:        case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
                   2214:                return "unknown channel type";
                   2215:        case SSH2_OPEN_RESOURCE_SHORTAGE:
                   2216:                return "resource shortage";
                   2217:        }
1.117     stevesk  2218:        return "unknown reason";
1.114     markus   2219: }
                   2220:
1.249     djm      2221: /* ARGSUSED */
1.49      markus   2222: void
1.154     markus   2223: channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2224: {
1.86      markus   2225:        int id, reason;
                   2226:        char *msg = NULL, *lang = NULL;
1.41      markus   2227:        Channel *c;
                   2228:
                   2229:        id = packet_get_int();
                   2230:        c = channel_lookup(id);
1.25      markus   2231:
1.41      markus   2232:        if (c==NULL || c->type != SSH_CHANNEL_OPENING)
                   2233:                packet_disconnect("Received open failure for "
                   2234:                    "non-opening channel %d.", id);
1.44      markus   2235:        if (compat20) {
1.86      markus   2236:                reason = packet_get_int();
1.110     markus   2237:                if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1.86      markus   2238:                        msg  = packet_get_string(NULL);
                   2239:                        lang = packet_get_string(NULL);
                   2240:                }
1.188     itojun   2241:                logit("channel %d: open failed: %s%s%s", id,
1.114     markus   2242:                    reason2txt(reason), msg ? ": ": "", msg ? msg : "");
1.86      markus   2243:                if (msg != NULL)
                   2244:                        xfree(msg);
                   2245:                if (lang != NULL)
                   2246:                        xfree(lang);
1.44      markus   2247:        }
1.152     markus   2248:        packet_check_eom();
1.25      markus   2249:        /* Free the channel.  This will also close the socket. */
1.113     markus   2250:        channel_free(c);
1.44      markus   2251: }
                   2252:
1.249     djm      2253: /* ARGSUSED */
1.121     markus   2254: void
1.154     markus   2255: channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
1.121     markus   2256: {
                   2257:        Channel *c;
1.178     markus   2258:        int id;
                   2259:        u_int adjust;
1.121     markus   2260:
                   2261:        if (!compat20)
                   2262:                return;
                   2263:
                   2264:        /* Get the channel number and verify it. */
                   2265:        id = packet_get_int();
                   2266:        c = channel_lookup(id);
1.1       deraadt  2267:
1.229     markus   2268:        if (c == NULL) {
                   2269:                logit("Received window adjust for non-open channel %d.", id);
1.121     markus   2270:                return;
                   2271:        }
                   2272:        adjust = packet_get_int();
1.152     markus   2273:        packet_check_eom();
1.178     markus   2274:        debug2("channel %d: rcvd adjust %u", id, adjust);
1.121     markus   2275:        c->remote_window += adjust;
                   2276: }
1.1       deraadt  2277:
1.249     djm      2278: /* ARGSUSED */
1.121     markus   2279: void
1.154     markus   2280: channel_input_port_open(int type, u_int32_t seq, void *ctxt)
1.1       deraadt  2281: {
1.121     markus   2282:        Channel *c = NULL;
                   2283:        u_short host_port;
                   2284:        char *host, *originator_string;
                   2285:        int remote_id, sock = -1;
                   2286:
                   2287:        remote_id = packet_get_int();
                   2288:        host = packet_get_string(NULL);
                   2289:        host_port = packet_get_int();
1.25      markus   2290:
1.121     markus   2291:        if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
                   2292:                originator_string = packet_get_string(NULL);
                   2293:        } else {
                   2294:                originator_string = xstrdup("unknown (remote did not supply name)");
                   2295:        }
1.152     markus   2296:        packet_check_eom();
1.121     markus   2297:        sock = channel_connect_to(host, host_port);
                   2298:        if (sock != -1) {
                   2299:                c = channel_new("connected socket",
                   2300:                    SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
                   2301:                    originator_string, 1);
1.167     markus   2302:                c->remote_id = remote_id;
1.25      markus   2303:        }
1.190     markus   2304:        xfree(originator_string);
1.121     markus   2305:        if (c == NULL) {
                   2306:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   2307:                packet_put_int(remote_id);
                   2308:                packet_send();
                   2309:        }
                   2310:        xfree(host);
1.1       deraadt  2311: }
                   2312:
1.121     markus   2313:
                   2314: /* -- tcp forwarding */
1.135     markus   2315:
                   2316: void
                   2317: channel_set_af(int af)
                   2318: {
                   2319:        IPv4or6 = af;
                   2320: }
1.121     markus   2321:
1.160     markus   2322: static int
                   2323: channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port,
                   2324:     const char *host_to_connect, u_short port_to_connect, int gateway_ports)
1.25      markus   2325: {
1.113     markus   2326:        Channel *c;
1.226     djm      2327:        int sock, r, success = 0, wildcard = 0, is_client;
1.35      markus   2328:        struct addrinfo hints, *ai, *aitop;
1.212     djm      2329:        const char *host, *addr;
1.35      markus   2330:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1.25      markus   2331:
1.160     markus   2332:        host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
                   2333:            listen_addr : host_to_connect;
1.212     djm      2334:        is_client = (type == SSH_CHANNEL_PORT_LISTENER);
1.87      markus   2335:
1.160     markus   2336:        if (host == NULL) {
                   2337:                error("No forward host name.");
1.218     markus   2338:                return 0;
1.73      markus   2339:        }
1.113     markus   2340:        if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
1.87      markus   2341:                error("Forward host name too long.");
1.218     markus   2342:                return 0;
1.87      markus   2343:        }
1.25      markus   2344:
1.28      markus   2345:        /*
1.212     djm      2346:         * Determine whether or not a port forward listens to loopback,
1.213     deraadt  2347:         * specified address or wildcard. On the client, a specified bind
                   2348:         * address will always override gateway_ports. On the server, a
                   2349:         * gateway_ports of 1 (``yes'') will override the client's
                   2350:         * specification and force a wildcard bind, whereas a value of 2
                   2351:         * (``clientspecified'') will bind to whatever address the client
1.212     djm      2352:         * asked for.
                   2353:         *
                   2354:         * Special-case listen_addrs are:
                   2355:         *
                   2356:         * "0.0.0.0"               -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
                   2357:         * "" (empty string), "*"  -> wildcard v4/v6
                   2358:         * "localhost"             -> loopback v4/v6
                   2359:         */
                   2360:        addr = NULL;
                   2361:        if (listen_addr == NULL) {
                   2362:                /* No address specified: default to gateway_ports setting */
                   2363:                if (gateway_ports)
                   2364:                        wildcard = 1;
                   2365:        } else if (gateway_ports || is_client) {
                   2366:                if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
                   2367:                    strcmp(listen_addr, "0.0.0.0") == 0) ||
                   2368:                    *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
                   2369:                    (!is_client && gateway_ports == 1))
                   2370:                        wildcard = 1;
                   2371:                else if (strcmp(listen_addr, "localhost") != 0)
                   2372:                        addr = listen_addr;
                   2373:        }
                   2374:
                   2375:        debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
                   2376:            type, wildcard, (addr == NULL) ? "NULL" : addr);
                   2377:
                   2378:        /*
1.35      markus   2379:         * getaddrinfo returns a loopback address if the hostname is
                   2380:         * set to NULL and hints.ai_flags is not AI_PASSIVE
1.28      markus   2381:         */
1.35      markus   2382:        memset(&hints, 0, sizeof(hints));
                   2383:        hints.ai_family = IPv4or6;
1.212     djm      2384:        hints.ai_flags = wildcard ? AI_PASSIVE : 0;
1.35      markus   2385:        hints.ai_socktype = SOCK_STREAM;
1.73      markus   2386:        snprintf(strport, sizeof strport, "%d", listen_port);
1.212     djm      2387:        if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
                   2388:                if (addr == NULL) {
                   2389:                        /* This really shouldn't happen */
                   2390:                        packet_disconnect("getaddrinfo: fatal error: %s",
                   2391:                            gai_strerror(r));
                   2392:                } else {
1.218     markus   2393:                        error("channel_setup_fwd_listener: "
1.212     djm      2394:                            "getaddrinfo(%.64s): %s", addr, gai_strerror(r));
                   2395:                }
1.218     markus   2396:                return 0;
1.212     djm      2397:        }
1.35      markus   2398:
                   2399:        for (ai = aitop; ai; ai = ai->ai_next) {
                   2400:                if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   2401:                        continue;
                   2402:                if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
                   2403:                    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1.160     markus   2404:                        error("channel_setup_fwd_listener: getnameinfo failed");
1.35      markus   2405:                        continue;
                   2406:                }
                   2407:                /* Create a port to listen for the host. */
1.189     markus   2408:                sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1.35      markus   2409:                if (sock < 0) {
                   2410:                        /* this is no error since kernel may not support ipv6 */
                   2411:                        verbose("socket: %.100s", strerror(errno));
                   2412:                        continue;
                   2413:                }
1.226     djm      2414:
                   2415:                channel_set_reuseaddr(sock);
1.182     stevesk  2416:
1.35      markus   2417:                debug("Local forwarding listening on %s port %s.", ntop, strport);
                   2418:
                   2419:                /* Bind the socket to the address. */
                   2420:                if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   2421:                        /* address can be in use ipv6 address is already bound */
                   2422:                        verbose("bind: %.100s", strerror(errno));
                   2423:                        close(sock);
                   2424:                        continue;
                   2425:                }
                   2426:                /* Start listening for connections on the socket. */
1.199     markus   2427:                if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1.35      markus   2428:                        error("listen: %.100s", strerror(errno));
                   2429:                        close(sock);
                   2430:                        continue;
                   2431:                }
                   2432:                /* Allocate a channel number for the socket. */
1.121     markus   2433:                c = channel_new("port listener", type, sock, sock, -1,
1.51      markus   2434:                    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1.190     markus   2435:                    0, "port listener", 1);
1.113     markus   2436:                strlcpy(c->path, host, sizeof(c->path));
                   2437:                c->host_port = port_to_connect;
                   2438:                c->listening_port = listen_port;
1.35      markus   2439:                success = 1;
                   2440:        }
                   2441:        if (success == 0)
1.160     markus   2442:                error("channel_setup_fwd_listener: cannot listen to port: %d",
1.87      markus   2443:                    listen_port);
1.35      markus   2444:        freeaddrinfo(aitop);
1.87      markus   2445:        return success;
1.25      markus   2446: }
1.1       deraadt  2447:
1.202     djm      2448: int
                   2449: channel_cancel_rport_listener(const char *host, u_short port)
                   2450: {
1.209     avsm     2451:        u_int i;
                   2452:        int found = 0;
1.202     djm      2453:
1.213     deraadt  2454:        for (i = 0; i < channels_alloc; i++) {
1.202     djm      2455:                Channel *c = channels[i];
                   2456:
                   2457:                if (c != NULL && c->type == SSH_CHANNEL_RPORT_LISTENER &&
                   2458:                    strncmp(c->path, host, sizeof(c->path)) == 0 &&
1.208     deraadt  2459:                    c->listening_port == port) {
1.210     djm      2460:                        debug2("%s: close channel %d", __func__, i);
1.202     djm      2461:                        channel_free(c);
                   2462:                        found = 1;
                   2463:                }
                   2464:        }
                   2465:
                   2466:        return (found);
                   2467: }
                   2468:
1.160     markus   2469: /* protocol local port fwd, used by ssh (and sshd in v1) */
                   2470: int
1.212     djm      2471: channel_setup_local_fwd_listener(const char *listen_host, u_short listen_port,
1.160     markus   2472:     const char *host_to_connect, u_short port_to_connect, int gateway_ports)
                   2473: {
                   2474:        return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
1.212     djm      2475:            listen_host, listen_port, host_to_connect, port_to_connect,
                   2476:            gateway_ports);
1.160     markus   2477: }
                   2478:
                   2479: /* protocol v2 remote port fwd, used by sshd */
                   2480: int
                   2481: channel_setup_remote_fwd_listener(const char *listen_address,
                   2482:     u_short listen_port, int gateway_ports)
                   2483: {
                   2484:        return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
                   2485:            listen_address, listen_port, NULL, 0, gateway_ports);
                   2486: }
                   2487:
1.27      markus   2488: /*
                   2489:  * Initiate forwarding of connections to port "port" on remote host through
                   2490:  * the secure channel to host:port from local side.
                   2491:  */
1.1       deraadt  2492:
1.253     markus   2493: int
1.212     djm      2494: channel_request_remote_forwarding(const char *listen_host, u_short listen_port,
1.73      markus   2495:     const char *host_to_connect, u_short port_to_connect)
1.25      markus   2496: {
1.153     markus   2497:        int type, success = 0;
1.73      markus   2498:
1.25      markus   2499:        /* Record locally that connection to this host/port is permitted. */
                   2500:        if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
                   2501:                fatal("channel_request_remote_forwarding: too many forwards");
                   2502:
                   2503:        /* Send the forward request to the remote side. */
1.44      markus   2504:        if (compat20) {
1.212     djm      2505:                const char *address_to_bind;
                   2506:                if (listen_host == NULL)
                   2507:                        address_to_bind = "localhost";
                   2508:                else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0)
                   2509:                        address_to_bind = "";
                   2510:                else
                   2511:                        address_to_bind = listen_host;
                   2512:
1.44      markus   2513:                packet_start(SSH2_MSG_GLOBAL_REQUEST);
                   2514:                packet_put_cstring("tcpip-forward");
1.173     markus   2515:                packet_put_char(1);                     /* boolean: want reply */
1.44      markus   2516:                packet_put_cstring(address_to_bind);
                   2517:                packet_put_int(listen_port);
1.73      markus   2518:                packet_send();
                   2519:                packet_write_wait();
                   2520:                /* Assume that server accepts the request */
                   2521:                success = 1;
1.44      markus   2522:        } else {
                   2523:                packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1.50      markus   2524:                packet_put_int(listen_port);
                   2525:                packet_put_cstring(host_to_connect);
1.44      markus   2526:                packet_put_int(port_to_connect);
                   2527:                packet_send();
                   2528:                packet_write_wait();
1.73      markus   2529:
                   2530:                /* Wait for response from the remote side. */
1.153     markus   2531:                type = packet_read();
1.73      markus   2532:                switch (type) {
                   2533:                case SSH_SMSG_SUCCESS:
                   2534:                        success = 1;
                   2535:                        break;
                   2536:                case SSH_SMSG_FAILURE:
                   2537:                        break;
                   2538:                default:
                   2539:                        /* Unknown packet */
                   2540:                        packet_disconnect("Protocol error for port forward request:"
                   2541:                            "received packet type %d.", type);
                   2542:                }
                   2543:        }
                   2544:        if (success) {
                   2545:                permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
                   2546:                permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
                   2547:                permitted_opens[num_permitted_opens].listen_port = listen_port;
                   2548:                num_permitted_opens++;
1.44      markus   2549:        }
1.253     markus   2550:        return (success ? 0 : -1);
1.1       deraadt  2551: }
                   2552:
1.27      markus   2553: /*
1.208     deraadt  2554:  * Request cancellation of remote forwarding of connection host:port from
1.202     djm      2555:  * local side.
                   2556:  */
                   2557: void
1.212     djm      2558: channel_request_rforward_cancel(const char *host, u_short port)
1.202     djm      2559: {
                   2560:        int i;
                   2561:
                   2562:        if (!compat20)
                   2563:                return;
                   2564:
                   2565:        for (i = 0; i < num_permitted_opens; i++) {
1.208     deraadt  2566:                if (permitted_opens[i].host_to_connect != NULL &&
1.202     djm      2567:                    permitted_opens[i].listen_port == port)
                   2568:                        break;
                   2569:        }
                   2570:        if (i >= num_permitted_opens) {
                   2571:                debug("%s: requested forward not found", __func__);
                   2572:                return;
                   2573:        }
                   2574:        packet_start(SSH2_MSG_GLOBAL_REQUEST);
                   2575:        packet_put_cstring("cancel-tcpip-forward");
                   2576:        packet_put_char(0);
1.212     djm      2577:        packet_put_cstring(host == NULL ? "" : host);
1.202     djm      2578:        packet_put_int(port);
                   2579:        packet_send();
                   2580:
                   2581:        permitted_opens[i].listen_port = 0;
                   2582:        permitted_opens[i].port_to_connect = 0;
1.227     stevesk  2583:        xfree(permitted_opens[i].host_to_connect);
1.202     djm      2584:        permitted_opens[i].host_to_connect = NULL;
                   2585: }
                   2586:
                   2587: /*
1.27      markus   2588:  * This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
                   2589:  * listening for the port, and sends back a success reply (or disconnect
1.253     markus   2590:  * message if there was an error).
1.27      markus   2591:  */
1.253     markus   2592: int
1.56      markus   2593: channel_input_port_forward_request(int is_root, int gateway_ports)
1.1       deraadt  2594: {
1.31      markus   2595:        u_short port, host_port;
1.253     markus   2596:        int success = 0;
1.25      markus   2597:        char *hostname;
1.1       deraadt  2598:
1.25      markus   2599:        /* Get arguments from the packet. */
                   2600:        port = packet_get_int();
                   2601:        hostname = packet_get_string(NULL);
                   2602:        host_port = packet_get_int();
                   2603:
1.27      markus   2604:        /*
                   2605:         * Check that an unprivileged user is not trying to forward a
                   2606:         * privileged port.
                   2607:         */
1.25      markus   2608:        if (port < IPPORT_RESERVED && !is_root)
1.192     markus   2609:                packet_disconnect(
                   2610:                    "Requested forwarding of port %d but user is not root.",
                   2611:                    port);
                   2612:        if (host_port == 0)
                   2613:                packet_disconnect("Dynamic forwarding denied.");
                   2614:
1.73      markus   2615:        /* Initiate forwarding */
1.253     markus   2616:        success = channel_setup_local_fwd_listener(NULL, port, hostname,
1.212     djm      2617:            host_port, gateway_ports);
1.25      markus   2618:
                   2619:        /* Free the argument string. */
                   2620:        xfree(hostname);
1.253     markus   2621:
                   2622:        return (success ? 0 : -1);
1.1       deraadt  2623: }
                   2624:
1.99      markus   2625: /*
                   2626:  * Permits opening to any host/port if permitted_opens[] is empty.  This is
                   2627:  * usually called by the server, because the user could connect to any port
                   2628:  * anyway, and the server has no way to know but to trust the client anyway.
                   2629:  */
                   2630: void
1.142     itojun   2631: channel_permit_all_opens(void)
1.99      markus   2632: {
                   2633:        if (num_permitted_opens == 0)
                   2634:                all_opens_permitted = 1;
                   2635: }
                   2636:
1.101     markus   2637: void
1.99      markus   2638: channel_add_permitted_opens(char *host, int port)
                   2639: {
                   2640:        if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
1.253     markus   2641:                fatal("channel_add_permitted_opens: too many forwards");
1.99      markus   2642:        debug("allow port forwarding to host %s port %d", host, port);
                   2643:
                   2644:        permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
                   2645:        permitted_opens[num_permitted_opens].port_to_connect = port;
                   2646:        num_permitted_opens++;
                   2647:
                   2648:        all_opens_permitted = 0;
                   2649: }
                   2650:
1.258     dtucker  2651: int
1.257     dtucker  2652: channel_add_adm_permitted_opens(char *host, int port)
                   2653: {
                   2654:        if (num_adm_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
                   2655:                fatal("channel_add_adm_permitted_opens: too many forwards");
1.258     dtucker  2656:        debug("config allows port forwarding to host %s port %d", host, port);
1.257     dtucker  2657:
                   2658:        permitted_adm_opens[num_adm_permitted_opens].host_to_connect
                   2659:             = xstrdup(host);
                   2660:        permitted_adm_opens[num_adm_permitted_opens].port_to_connect = port;
1.258     dtucker  2661:        return ++num_adm_permitted_opens;
1.257     dtucker  2662: }
                   2663:
                   2664: void
1.99      markus   2665: channel_clear_permitted_opens(void)
                   2666: {
                   2667:        int i;
                   2668:
                   2669:        for (i = 0; i < num_permitted_opens; i++)
1.202     djm      2670:                if (permitted_opens[i].host_to_connect != NULL)
                   2671:                        xfree(permitted_opens[i].host_to_connect);
1.99      markus   2672:        num_permitted_opens = 0;
1.257     dtucker  2673: }
                   2674:
                   2675: void
                   2676: channel_clear_adm_permitted_opens(void)
                   2677: {
                   2678:        int i;
1.99      markus   2679:
1.257     dtucker  2680:        for (i = 0; i < num_adm_permitted_opens; i++)
                   2681:                if (permitted_adm_opens[i].host_to_connect != NULL)
                   2682:                        xfree(permitted_adm_opens[i].host_to_connect);
                   2683:        num_adm_permitted_opens = 0;
1.99      markus   2684: }
                   2685:
                   2686: /* return socket to remote host, port */
1.127     itojun   2687: static int
1.99      markus   2688: connect_to(const char *host, u_short port)
1.41      markus   2689: {
                   2690:        struct addrinfo hints, *ai, *aitop;
                   2691:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
                   2692:        int gaierr;
                   2693:        int sock = -1;
                   2694:
                   2695:        memset(&hints, 0, sizeof(hints));
                   2696:        hints.ai_family = IPv4or6;
                   2697:        hints.ai_socktype = SOCK_STREAM;
1.99      markus   2698:        snprintf(strport, sizeof strport, "%d", port);
1.41      markus   2699:        if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
1.99      markus   2700:                error("connect_to %.100s: unknown host (%s)", host,
                   2701:                    gai_strerror(gaierr));
1.41      markus   2702:                return -1;
                   2703:        }
                   2704:        for (ai = aitop; ai; ai = ai->ai_next) {
                   2705:                if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   2706:                        continue;
                   2707:                if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
                   2708:                    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1.99      markus   2709:                        error("connect_to: getnameinfo failed");
1.41      markus   2710:                        continue;
                   2711:                }
1.189     markus   2712:                sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1.41      markus   2713:                if (sock < 0) {
1.186     djm      2714:                        if (ai->ai_next == NULL)
                   2715:                                error("socket: %.100s", strerror(errno));
                   2716:                        else
                   2717:                                verbose("socket: %.100s", strerror(errno));
1.41      markus   2718:                        continue;
                   2719:                }
1.205     djm      2720:                if (set_nonblock(sock) == -1)
                   2721:                        fatal("%s: set_nonblock(%d)", __func__, sock);
1.75      markus   2722:                if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
                   2723:                    errno != EINPROGRESS) {
1.99      markus   2724:                        error("connect_to %.100s port %s: %.100s", ntop, strport,
1.41      markus   2725:                            strerror(errno));
                   2726:                        close(sock);
1.89      stevesk  2727:                        continue;       /* fail -- try next */
1.41      markus   2728:                }
                   2729:                break; /* success */
                   2730:
                   2731:        }
                   2732:        freeaddrinfo(aitop);
                   2733:        if (!ai) {
1.99      markus   2734:                error("connect_to %.100s port %d: failed.", host, port);
1.41      markus   2735:                return -1;
                   2736:        }
                   2737:        /* success */
1.169     stevesk  2738:        set_nodelay(sock);
1.41      markus   2739:        return sock;
                   2740: }
1.99      markus   2741:
1.73      markus   2742: int
1.130     stevesk  2743: channel_connect_by_listen_address(u_short listen_port)
1.73      markus   2744: {
                   2745:        int i;
1.99      markus   2746:
1.73      markus   2747:        for (i = 0; i < num_permitted_opens; i++)
1.202     djm      2748:                if (permitted_opens[i].host_to_connect != NULL &&
                   2749:                    permitted_opens[i].listen_port == listen_port)
1.99      markus   2750:                        return connect_to(
1.73      markus   2751:                            permitted_opens[i].host_to_connect,
                   2752:                            permitted_opens[i].port_to_connect);
1.74      markus   2753:        error("WARNING: Server requests forwarding for unknown listen_port %d",
                   2754:            listen_port);
1.73      markus   2755:        return -1;
                   2756: }
                   2757:
1.99      markus   2758: /* Check if connecting to that port is permitted and connect. */
                   2759: int
                   2760: channel_connect_to(const char *host, u_short port)
                   2761: {
1.257     dtucker  2762:        int i, permit, permit_adm = 1;
1.99      markus   2763:
                   2764:        permit = all_opens_permitted;
                   2765:        if (!permit) {
                   2766:                for (i = 0; i < num_permitted_opens; i++)
1.202     djm      2767:                        if (permitted_opens[i].host_to_connect != NULL &&
                   2768:                            permitted_opens[i].port_to_connect == port &&
1.99      markus   2769:                            strcmp(permitted_opens[i].host_to_connect, host) == 0)
                   2770:                                permit = 1;
1.257     dtucker  2771:        }
1.99      markus   2772:
1.257     dtucker  2773:        if (num_adm_permitted_opens > 0) {
                   2774:                permit_adm = 0;
                   2775:                for (i = 0; i < num_adm_permitted_opens; i++)
                   2776:                        if (permitted_adm_opens[i].host_to_connect != NULL &&
                   2777:                            permitted_adm_opens[i].port_to_connect == port &&
                   2778:                            strcmp(permitted_adm_opens[i].host_to_connect, host)
                   2779:                            == 0)
                   2780:                                permit_adm = 1;
1.99      markus   2781:        }
1.257     dtucker  2782:
                   2783:        if (!permit || !permit_adm) {
1.188     itojun   2784:                logit("Received request to connect to host %.100s port %d, "
1.99      markus   2785:                    "but the request was denied.", host, port);
                   2786:                return -1;
                   2787:        }
                   2788:        return connect_to(host, port);
1.204     djm      2789: }
                   2790:
                   2791: void
                   2792: channel_send_window_changes(void)
                   2793: {
1.209     avsm     2794:        u_int i;
1.204     djm      2795:        struct winsize ws;
                   2796:
                   2797:        for (i = 0; i < channels_alloc; i++) {
1.213     deraadt  2798:                if (channels[i] == NULL || !channels[i]->client_tty ||
1.204     djm      2799:                    channels[i]->type != SSH_CHANNEL_OPEN)
                   2800:                        continue;
                   2801:                if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
                   2802:                        continue;
                   2803:                channel_request_start(i, "window-change", 0);
1.238     deraadt  2804:                packet_put_int((u_int)ws.ws_col);
                   2805:                packet_put_int((u_int)ws.ws_row);
                   2806:                packet_put_int((u_int)ws.ws_xpixel);
                   2807:                packet_put_int((u_int)ws.ws_ypixel);
1.204     djm      2808:                packet_send();
                   2809:        }
1.99      markus   2810: }
                   2811:
1.121     markus   2812: /* -- X11 forwarding */
1.1       deraadt  2813:
1.27      markus   2814: /*
                   2815:  * Creates an internet domain socket for listening for X11 connections.
1.176     deraadt  2816:  * Returns 0 and a suitable display number for the DISPLAY variable
                   2817:  * stored in display_numberp , or -1 if an error occurs.
1.27      markus   2818:  */
1.141     stevesk  2819: int
1.163     stevesk  2820: x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
1.222     djm      2821:     int single_connection, u_int *display_numberp, int **chanids)
1.1       deraadt  2822: {
1.149     markus   2823:        Channel *nc = NULL;
1.31      markus   2824:        int display_number, sock;
                   2825:        u_short port;
1.35      markus   2826:        struct addrinfo hints, *ai, *aitop;
                   2827:        char strport[NI_MAXSERV];
                   2828:        int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
1.25      markus   2829:
1.224     markus   2830:        if (chanids == NULL)
                   2831:                return -1;
                   2832:
1.33      markus   2833:        for (display_number = x11_display_offset;
1.148     deraadt  2834:            display_number < MAX_DISPLAYS;
                   2835:            display_number++) {
1.25      markus   2836:                port = 6000 + display_number;
1.35      markus   2837:                memset(&hints, 0, sizeof(hints));
                   2838:                hints.ai_family = IPv4or6;
1.163     stevesk  2839:                hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
1.35      markus   2840:                hints.ai_socktype = SOCK_STREAM;
                   2841:                snprintf(strport, sizeof strport, "%d", port);
                   2842:                if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
                   2843:                        error("getaddrinfo: %.100s", gai_strerror(gaierr));
1.141     stevesk  2844:                        return -1;
1.25      markus   2845:                }
1.35      markus   2846:                for (ai = aitop; ai; ai = ai->ai_next) {
                   2847:                        if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   2848:                                continue;
1.189     markus   2849:                        sock = socket(ai->ai_family, ai->ai_socktype,
                   2850:                            ai->ai_protocol);
1.35      markus   2851:                        if (sock < 0) {
                   2852:                                error("socket: %.100s", strerror(errno));
1.203     markus   2853:                                freeaddrinfo(aitop);
1.141     stevesk  2854:                                return -1;
1.35      markus   2855:                        }
1.226     djm      2856:                        channel_set_reuseaddr(sock);
1.35      markus   2857:                        if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1.194     markus   2858:                                debug2("bind port %d: %.100s", port, strerror(errno));
1.35      markus   2859:                                close(sock);
1.183     itojun   2860:
                   2861:                                if (ai->ai_next)
                   2862:                                        continue;
                   2863:
1.35      markus   2864:                                for (n = 0; n < num_socks; n++) {
                   2865:                                        close(socks[n]);
                   2866:                                }
                   2867:                                num_socks = 0;
                   2868:                                break;
                   2869:                        }
                   2870:                        socks[num_socks++] = sock;
                   2871:                        if (num_socks == NUM_SOCKS)
                   2872:                                break;
1.25      markus   2873:                }
1.83      stevesk  2874:                freeaddrinfo(aitop);
1.35      markus   2875:                if (num_socks > 0)
                   2876:                        break;
1.25      markus   2877:        }
                   2878:        if (display_number >= MAX_DISPLAYS) {
                   2879:                error("Failed to allocate internet-domain X11 display socket.");
1.141     stevesk  2880:                return -1;
1.25      markus   2881:        }
                   2882:        /* Start listening for connections on the socket. */
1.35      markus   2883:        for (n = 0; n < num_socks; n++) {
                   2884:                sock = socks[n];
1.199     markus   2885:                if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1.35      markus   2886:                        error("listen: %.100s", strerror(errno));
                   2887:                        close(sock);
1.141     stevesk  2888:                        return -1;
1.35      markus   2889:                }
1.25      markus   2890:        }
1.35      markus   2891:
                   2892:        /* Allocate a channel for each socket. */
1.242     djm      2893:        *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
1.35      markus   2894:        for (n = 0; n < num_socks; n++) {
                   2895:                sock = socks[n];
1.149     markus   2896:                nc = channel_new("x11 listener",
1.51      markus   2897:                    SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
                   2898:                    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
1.190     markus   2899:                    0, "X11 inet listener", 1);
1.167     markus   2900:                nc->single_connection = single_connection;
1.224     markus   2901:                (*chanids)[n] = nc->self;
1.35      markus   2902:        }
1.224     markus   2903:        (*chanids)[n] = -1;
1.1       deraadt  2904:
1.141     stevesk  2905:        /* Return the display number for the DISPLAY environment variable. */
1.176     deraadt  2906:        *display_numberp = display_number;
                   2907:        return (0);
1.1       deraadt  2908: }
                   2909:
1.127     itojun   2910: static int
1.77      markus   2911: connect_local_xsocket(u_int dnr)
1.1       deraadt  2912: {
1.25      markus   2913:        int sock;
                   2914:        struct sockaddr_un addr;
                   2915:
1.147     stevesk  2916:        sock = socket(AF_UNIX, SOCK_STREAM, 0);
                   2917:        if (sock < 0)
                   2918:                error("socket: %.100s", strerror(errno));
                   2919:        memset(&addr, 0, sizeof(addr));
                   2920:        addr.sun_family = AF_UNIX;
                   2921:        snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
1.239     deraadt  2922:        if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
1.147     stevesk  2923:                return sock;
                   2924:        close(sock);
1.25      markus   2925:        error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
                   2926:        return -1;
1.1       deraadt  2927: }
                   2928:
1.51      markus   2929: int
                   2930: x11_connect_display(void)
1.1       deraadt  2931: {
1.248     deraadt  2932:        u_int display_number;
1.25      markus   2933:        const char *display;
1.51      markus   2934:        char buf[1024], *cp;
1.35      markus   2935:        struct addrinfo hints, *ai, *aitop;
                   2936:        char strport[NI_MAXSERV];
1.248     deraadt  2937:        int gaierr, sock = 0;
1.25      markus   2938:
                   2939:        /* Try to open a socket for the local X server. */
                   2940:        display = getenv("DISPLAY");
                   2941:        if (!display) {
                   2942:                error("DISPLAY not set.");
1.51      markus   2943:                return -1;
1.25      markus   2944:        }
1.27      markus   2945:        /*
                   2946:         * Now we decode the value of the DISPLAY variable and make a
                   2947:         * connection to the real X server.
                   2948:         */
                   2949:
                   2950:        /*
                   2951:         * Check if it is a unix domain socket.  Unix domain displays are in
                   2952:         * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
                   2953:         */
1.25      markus   2954:        if (strncmp(display, "unix:", 5) == 0 ||
                   2955:            display[0] == ':') {
                   2956:                /* Connect to the unix domain socket. */
1.248     deraadt  2957:                if (sscanf(strrchr(display, ':') + 1, "%u", &display_number) != 1) {
1.25      markus   2958:                        error("Could not parse display number from DISPLAY: %.100s",
1.148     deraadt  2959:                            display);
1.51      markus   2960:                        return -1;
1.25      markus   2961:                }
                   2962:                /* Create a socket. */
                   2963:                sock = connect_local_xsocket(display_number);
                   2964:                if (sock < 0)
1.51      markus   2965:                        return -1;
1.25      markus   2966:
                   2967:                /* OK, we now have a connection to the display. */
1.51      markus   2968:                return sock;
1.25      markus   2969:        }
1.27      markus   2970:        /*
                   2971:         * Connect to an inet socket.  The DISPLAY value is supposedly
                   2972:         * hostname:d[.s], where hostname may also be numeric IP address.
                   2973:         */
1.145     stevesk  2974:        strlcpy(buf, display, sizeof(buf));
1.25      markus   2975:        cp = strchr(buf, ':');
                   2976:        if (!cp) {
                   2977:                error("Could not find ':' in DISPLAY: %.100s", display);
1.51      markus   2978:                return -1;
1.25      markus   2979:        }
                   2980:        *cp = 0;
1.27      markus   2981:        /* buf now contains the host name.  But first we parse the display number. */
1.248     deraadt  2982:        if (sscanf(cp + 1, "%u", &display_number) != 1) {
1.25      markus   2983:                error("Could not parse display number from DISPLAY: %.100s",
1.148     deraadt  2984:                    display);
1.51      markus   2985:                return -1;
1.25      markus   2986:        }
1.35      markus   2987:
                   2988:        /* Look up the host address */
                   2989:        memset(&hints, 0, sizeof(hints));
                   2990:        hints.ai_family = IPv4or6;
                   2991:        hints.ai_socktype = SOCK_STREAM;
1.248     deraadt  2992:        snprintf(strport, sizeof strport, "%u", 6000 + display_number);
1.35      markus   2993:        if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
                   2994:                error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
1.51      markus   2995:                return -1;
1.25      markus   2996:        }
1.35      markus   2997:        for (ai = aitop; ai; ai = ai->ai_next) {
                   2998:                /* Create a socket. */
1.189     markus   2999:                sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1.35      markus   3000:                if (sock < 0) {
1.194     markus   3001:                        debug2("socket: %.100s", strerror(errno));
1.41      markus   3002:                        continue;
                   3003:                }
                   3004:                /* Connect it to the display. */
                   3005:                if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1.248     deraadt  3006:                        debug2("connect %.100s port %u: %.100s", buf,
1.41      markus   3007:                            6000 + display_number, strerror(errno));
                   3008:                        close(sock);
                   3009:                        continue;
                   3010:                }
                   3011:                /* Success */
                   3012:                break;
1.35      markus   3013:        }
                   3014:        freeaddrinfo(aitop);
                   3015:        if (!ai) {
1.248     deraadt  3016:                error("connect %.100s port %u: %.100s", buf, 6000 + display_number,
1.35      markus   3017:                    strerror(errno));
1.51      markus   3018:                return -1;
1.25      markus   3019:        }
1.162     stevesk  3020:        set_nodelay(sock);
1.51      markus   3021:        return sock;
                   3022: }
                   3023:
                   3024: /*
                   3025:  * This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
                   3026:  * the remote channel number.  We should do whatever we want, and respond
                   3027:  * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
                   3028:  */
                   3029:
1.259     stevesk  3030: /* ARGSUSED */
1.51      markus   3031: void
1.154     markus   3032: x11_input_open(int type, u_int32_t seq, void *ctxt)
1.51      markus   3033: {
1.113     markus   3034:        Channel *c = NULL;
                   3035:        int remote_id, sock = 0;
1.51      markus   3036:        char *remote_host;
1.25      markus   3037:
1.113     markus   3038:        debug("Received X11 open request.");
1.51      markus   3039:
1.113     markus   3040:        remote_id = packet_get_int();
1.121     markus   3041:
                   3042:        if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
1.113     markus   3043:                remote_host = packet_get_string(NULL);
1.51      markus   3044:        } else {
                   3045:                remote_host = xstrdup("unknown (remote did not supply name)");
                   3046:        }
1.152     markus   3047:        packet_check_eom();
1.25      markus   3048:
1.51      markus   3049:        /* Obtain a connection to the real X display. */
                   3050:        sock = x11_connect_display();
1.113     markus   3051:        if (sock != -1) {
                   3052:                /* Allocate a channel for this connection. */
                   3053:                c = channel_new("connected x11 socket",
                   3054:                    SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
                   3055:                    remote_host, 1);
1.167     markus   3056:                c->remote_id = remote_id;
                   3057:                c->force_drain = 1;
1.113     markus   3058:        }
1.190     markus   3059:        xfree(remote_host);
1.113     markus   3060:        if (c == NULL) {
1.51      markus   3061:                /* Send refusal to the remote host. */
                   3062:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1.113     markus   3063:                packet_put_int(remote_id);
1.51      markus   3064:        } else {
                   3065:                /* Send a confirmation to the remote host. */
                   3066:                packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1.113     markus   3067:                packet_put_int(remote_id);
                   3068:                packet_put_int(c->self);
1.51      markus   3069:        }
1.113     markus   3070:        packet_send();
1.72      markus   3071: }
                   3072:
                   3073: /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
1.259     stevesk  3074: /* ARGSUSED */
1.72      markus   3075: void
1.154     markus   3076: deny_input_open(int type, u_int32_t seq, void *ctxt)
1.72      markus   3077: {
                   3078:        int rchan = packet_get_int();
1.180     deraadt  3079:
1.143     deraadt  3080:        switch (type) {
1.72      markus   3081:        case SSH_SMSG_AGENT_OPEN:
                   3082:                error("Warning: ssh server tried agent forwarding.");
                   3083:                break;
                   3084:        case SSH_SMSG_X11_OPEN:
                   3085:                error("Warning: ssh server tried X11 forwarding.");
                   3086:                break;
                   3087:        default:
1.154     markus   3088:                error("deny_input_open: type %d", type);
1.72      markus   3089:                break;
                   3090:        }
1.230     stevesk  3091:        error("Warning: this is probably a break-in attempt by a malicious server.");
1.72      markus   3092:        packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   3093:        packet_put_int(rchan);
                   3094:        packet_send();
1.1       deraadt  3095: }
                   3096:
1.27      markus   3097: /*
                   3098:  * Requests forwarding of X11 connections, generates fake authentication
                   3099:  * data, and enables authentication spoofing.
1.121     markus   3100:  * This should be called in the client only.
1.27      markus   3101:  */
1.49      markus   3102: void
1.215     djm      3103: x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
1.51      markus   3104:     const char *proto, const char *data)
1.1       deraadt  3105: {
1.77      markus   3106:        u_int data_len = (u_int) strlen(data) / 2;
1.219     djm      3107:        u_int i, value;
1.25      markus   3108:        char *new_data;
                   3109:        int screen_number;
                   3110:        const char *cp;
1.207     avsm     3111:        u_int32_t rnd = 0;
1.25      markus   3112:
1.220     markus   3113:        if (x11_saved_display == NULL)
                   3114:                x11_saved_display = xstrdup(disp);
                   3115:        else if (strcmp(disp, x11_saved_display) != 0) {
1.219     djm      3116:                error("x11_request_forwarding_with_spoofing: different "
                   3117:                    "$DISPLAY already forwarded");
                   3118:                return;
                   3119:        }
                   3120:
1.215     djm      3121:        cp = disp;
                   3122:        if (disp)
                   3123:                cp = strchr(disp, ':');
1.25      markus   3124:        if (cp)
                   3125:                cp = strchr(cp, '.');
                   3126:        if (cp)
1.245     deraadt  3127:                screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
1.25      markus   3128:        else
                   3129:                screen_number = 0;
                   3130:
1.219     djm      3131:        if (x11_saved_proto == NULL) {
                   3132:                /* Save protocol name. */
                   3133:                x11_saved_proto = xstrdup(proto);
                   3134:                /*
1.221     djm      3135:                 * Extract real authentication data and generate fake data
1.219     djm      3136:                 * of the same length.
                   3137:                 */
                   3138:                x11_saved_data = xmalloc(data_len);
                   3139:                x11_fake_data = xmalloc(data_len);
                   3140:                for (i = 0; i < data_len; i++) {
                   3141:                        if (sscanf(data + 2 * i, "%2x", &value) != 1)
                   3142:                                fatal("x11_request_forwarding: bad "
                   3143:                                    "authentication data: %.100s", data);
                   3144:                        if (i % 4 == 0)
                   3145:                                rnd = arc4random();
                   3146:                        x11_saved_data[i] = value;
                   3147:                        x11_fake_data[i] = rnd & 0xff;
                   3148:                        rnd >>= 8;
                   3149:                }
                   3150:                x11_saved_data_len = data_len;
                   3151:                x11_fake_data_len = data_len;
1.25      markus   3152:        }
                   3153:
                   3154:        /* Convert the fake data into hex. */
1.219     djm      3155:        new_data = tohex(x11_fake_data, data_len);
1.25      markus   3156:
                   3157:        /* Send the request packet. */
1.51      markus   3158:        if (compat20) {
                   3159:                channel_request_start(client_session_id, "x11-req", 0);
                   3160:                packet_put_char(0);     /* XXX bool single connection */
                   3161:        } else {
                   3162:                packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
                   3163:        }
                   3164:        packet_put_cstring(proto);
                   3165:        packet_put_cstring(new_data);
1.25      markus   3166:        packet_put_int(screen_number);
                   3167:        packet_send();
                   3168:        packet_write_wait();
                   3169:        xfree(new_data);
1.1       deraadt  3170: }
                   3171:
1.121     markus   3172:
                   3173: /* -- agent forwarding */
                   3174:
1.1       deraadt  3175: /* Sends a message to the server to request authentication fd forwarding. */
                   3176:
1.49      markus   3177: void
1.142     itojun   3178: auth_request_forwarding(void)
1.1       deraadt  3179: {
1.25      markus   3180:        packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
                   3181:        packet_send();
                   3182:        packet_write_wait();
1.1       deraadt  3183: }