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

1.1       deraadt     1: /*
1.26      deraadt     2:  *
                      3:  * channels.c
                      4:  *
                      5:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      6:  *
                      7:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      8:  *                    All rights reserved
                      9:  *
                     10:  * Created: Fri Mar 24 16:35:24 1995 ylo
                     11:  *
                     12:  * This file contains functions for generic socket connection forwarding.
                     13:  * There is also code for initiating connection forwarding for X11 connections,
                     14:  * arbitrary tcp/ip connections, and the authentication agent connection.
                     15:  *
                     16:  */
1.1       deraadt    17:
                     18: #include "includes.h"
1.41    ! markus     19: RCSID("$Id: channels.c,v 1.40 2000/03/27 17:41:50 markus Exp $");
1.1       deraadt    20:
                     21: #include "ssh.h"
                     22: #include "packet.h"
                     23: #include "xmalloc.h"
                     24: #include "buffer.h"
                     25: #include "authfd.h"
                     26: #include "uidswap.h"
1.20      markus     27: #include "readconf.h"
1.3       deraadt    28: #include "servconf.h"
1.1       deraadt    29:
1.14      markus     30: #include "channels.h"
                     31: #include "nchan.h"
                     32: #include "compat.h"
                     33:
1.1       deraadt    34: /* Maximum number of fake X11 displays to try. */
                     35: #define MAX_DISPLAYS  1000
                     36:
1.12      markus     37: /* Max len of agent socket */
                     38: #define MAX_SOCKET_NAME 100
                     39:
1.41    ! markus     40: /* default buffer for tcp-fwd-channel */
        !            41: #define CHAN_WINDOW_DEFAULT      (8*1024)
        !            42: #define CHAN_PACKET_DEFAULT     (CHAN_WINDOW_DEFAULT/2)
        !            43:
1.27      markus     44: /*
                     45:  * Pointer to an array containing all allocated channels.  The array is
                     46:  * dynamically extended as needed.
                     47:  */
1.1       deraadt    48: static Channel *channels = NULL;
                     49:
1.27      markus     50: /*
                     51:  * Size of the channel array.  All slots of the array must always be
                     52:  * initialized (at least the type field); unused slots are marked with type
                     53:  * SSH_CHANNEL_FREE.
                     54:  */
1.1       deraadt    55: static int channels_alloc = 0;
                     56:
1.27      markus     57: /*
                     58:  * Maximum file descriptor value used in any of the channels.  This is
                     59:  * updated in channel_allocate.
                     60:  */
1.1       deraadt    61: static int channel_max_fd_value = 0;
                     62:
1.12      markus     63: /* Name and directory of socket for authentication agent forwarding. */
1.1       deraadt    64: static char *channel_forwarded_auth_socket_name = NULL;
1.25      markus     65: static char *channel_forwarded_auth_socket_dir = NULL;
1.1       deraadt    66:
                     67: /* Saved X11 authentication protocol name. */
                     68: char *x11_saved_proto = NULL;
                     69:
                     70: /* Saved X11 authentication data.  This is the real data. */
                     71: char *x11_saved_data = NULL;
                     72: unsigned int x11_saved_data_len = 0;
                     73:
1.27      markus     74: /*
                     75:  * Fake X11 authentication data.  This is what the server will be sending us;
                     76:  * we should replace any occurrences of this by the real data.
                     77:  */
1.1       deraadt    78: char *x11_fake_data = NULL;
                     79: unsigned int x11_fake_data_len;
                     80:
1.27      markus     81: /*
                     82:  * Data structure for storing which hosts are permitted for forward requests.
                     83:  * The local sides of any remote forwards are stored in this array to prevent
                     84:  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
                     85:  * network (which might be behind a firewall).
                     86:  */
1.25      markus     87: typedef struct {
1.41    ! markus     88:        char *host_to_connect;          /* Connect to 'host'. */
        !            89:        u_short port_to_connect;        /* Connect to 'port'. */
        !            90:        u_short listen_port;            /* Remote side should listen port number. */
1.1       deraadt    91: } ForwardPermission;
                     92:
                     93: /* List of all permitted host/port pairs to connect. */
                     94: static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
                     95: /* Number of permitted host/port pairs in the array. */
                     96: static int num_permitted_opens = 0;
1.27      markus     97: /*
                     98:  * If this is true, all opens are permitted.  This is the case on the server
                     99:  * on which we have to trust the client anyway, and the user could do
                    100:  * anything after logging in anyway.
                    101:  */
1.1       deraadt   102: static int all_opens_permitted = 0;
                    103:
                    104: /* This is set to true if both sides support SSH_PROTOFLAG_HOST_IN_FWD_OPEN. */
                    105: static int have_hostname_in_open = 0;
                    106:
                    107: /* Sets specific protocol options. */
                    108:
1.25      markus    109: void
                    110: channel_set_options(int hostname_in_open)
1.1       deraadt   111: {
1.25      markus    112:        have_hostname_in_open = hostname_in_open;
1.1       deraadt   113: }
                    114:
1.27      markus    115: /*
                    116:  * Permits opening to any host/port in SSH_MSG_PORT_OPEN.  This is usually
                    117:  * called by the server, because the user could connect to any port anyway,
                    118:  * and the server has no way to know but to trust the client anyway.
                    119:  */
1.1       deraadt   120:
1.25      markus    121: void
                    122: channel_permit_all_opens()
1.1       deraadt   123: {
1.25      markus    124:        all_opens_permitted = 1;
1.1       deraadt   125: }
                    126:
1.41    ! markus    127: /* lookup channel by id */
        !           128:
        !           129: Channel *
        !           130: channel_lookup(int id)
        !           131: {
        !           132:        Channel *c;
        !           133:        if (id < 0 && id > channels_alloc) {
        !           134:                log("channel_lookup: %d: bad id", id);
        !           135:                return NULL;
        !           136:        }
        !           137:        c = &channels[id];
        !           138:        if (c->type == SSH_CHANNEL_FREE) {
        !           139:                log("channel_lookup: %d: bad id: channel free", id);
        !           140:                return NULL;
        !           141:        }
        !           142:        return c;
        !           143: }
        !           144:
1.27      markus    145: /*
                    146:  * Allocate a new channel object and set its type and socket. This will cause
                    147:  * remote_name to be freed.
                    148:  */
1.1       deraadt   149:
1.25      markus    150: int
1.41    ! markus    151: channel_new(char *ctype, int type, int rfd, int wfd, int efd,
        !           152:     int window, int maxpack, int extended_usage, char *remote_name)
1.1       deraadt   153: {
1.25      markus    154:        int i, found;
                    155:        Channel *c;
1.1       deraadt   156:
1.25      markus    157:        /* Update the maximum file descriptor value. */
1.41    ! markus    158:        if (rfd > channel_max_fd_value)
        !           159:                channel_max_fd_value = rfd;
        !           160:        if (wfd > channel_max_fd_value)
        !           161:                channel_max_fd_value = wfd;
        !           162:        if (efd > channel_max_fd_value)
        !           163:                channel_max_fd_value = efd;
1.27      markus    164:        /* XXX set close-on-exec -markus */
1.25      markus    165:
                    166:        /* Do initial allocation if this is the first call. */
                    167:        if (channels_alloc == 0) {
                    168:                channels_alloc = 10;
                    169:                channels = xmalloc(channels_alloc * sizeof(Channel));
                    170:                for (i = 0; i < channels_alloc; i++)
                    171:                        channels[i].type = SSH_CHANNEL_FREE;
1.27      markus    172:                /*
                    173:                 * Kludge: arrange a call to channel_stop_listening if we
                    174:                 * terminate with fatal().
                    175:                 */
1.25      markus    176:                fatal_add_cleanup((void (*) (void *)) channel_stop_listening, NULL);
                    177:        }
                    178:        /* Try to find a free slot where to put the new channel. */
                    179:        for (found = -1, i = 0; i < channels_alloc; i++)
                    180:                if (channels[i].type == SSH_CHANNEL_FREE) {
                    181:                        /* Found a free slot. */
                    182:                        found = i;
                    183:                        break;
                    184:                }
                    185:        if (found == -1) {
1.27      markus    186:                /* There are no free slots.  Take last+1 slot and expand the array.  */
1.25      markus    187:                found = channels_alloc;
                    188:                channels_alloc += 10;
                    189:                debug("channel: expanding %d", channels_alloc);
                    190:                channels = xrealloc(channels, channels_alloc * sizeof(Channel));
                    191:                for (i = found; i < channels_alloc; i++)
                    192:                        channels[i].type = SSH_CHANNEL_FREE;
                    193:        }
                    194:        /* Initialize and return new channel number. */
                    195:        c = &channels[found];
                    196:        buffer_init(&c->input);
                    197:        buffer_init(&c->output);
1.41    ! markus    198:        buffer_init(&c->extended);
1.25      markus    199:        chan_init_iostates(c);
                    200:        c->self = found;
                    201:        c->type = type;
1.41    ! markus    202:        c->ctype = ctype;
        !           203:        c->local_window = window;
        !           204:        c->local_window_max = window;
        !           205:        c->local_consumed = 0;
        !           206:        c->local_maxpacket = maxpack;
        !           207:        c->remote_window = 0;
        !           208:        c->remote_maxpacket = 0;
        !           209:        c->rfd = rfd;
        !           210:        c->wfd = wfd;
        !           211:        c->sock = (rfd == wfd) ? rfd : -1;
        !           212:        c->efd = efd;
        !           213:        c->extended_usage = extended_usage;
1.25      markus    214:        c->remote_id = -1;
                    215:        c->remote_name = remote_name;
1.41    ! markus    216:        c->remote_window = 0;
        !           217:        c->remote_maxpacket = 0;
        !           218:        c->cb_fn = NULL;
        !           219:        c->cb_arg = NULL;
        !           220:        c->cb_event = 0;
        !           221:        c->dettach_user = NULL;
1.25      markus    222:        debug("channel %d: new [%s]", found, remote_name);
                    223:        return found;
1.1       deraadt   224: }
1.41    ! markus    225: int
        !           226: channel_allocate(int type, int sock, char *remote_name)
        !           227: {
        !           228:        return channel_new("", type, sock, sock, -1, 0, 0, 0, remote_name);
        !           229: }
1.1       deraadt   230:
                    231: /* Free the channel and close its socket. */
                    232:
1.25      markus    233: void
1.41    ! markus    234: channel_free(int id)
1.1       deraadt   235: {
1.41    ! markus    236:        Channel *c = channel_lookup(id);
        !           237:        if (c == NULL)
        !           238:                packet_disconnect("channel free: bad local channel %d", id);
        !           239:        debug("channel_free: channel %d: status: %s", id, channel_open_message());
1.25      markus    240:        if (compat13)
1.41    ! markus    241:                shutdown(c->sock, SHUT_RDWR);
        !           242:        buffer_free(&c->input);
        !           243:        buffer_free(&c->output);
        !           244:        buffer_free(&c->extended);
        !           245:        c->type = SSH_CHANNEL_FREE;
        !           246:        if (c->remote_name) {
        !           247:                xfree(c->remote_name);
        !           248:                c->remote_name = NULL;
1.25      markus    249:        }
1.1       deraadt   250: }
                    251:
1.27      markus    252: /*
1.41    ! markus    253:  * 'channel_pre*' are called just before select() to add any bits relevant to
        !           254:  * channels in the select bitmasks.
        !           255:  */
        !           256: /*
        !           257:  * 'channel_post*': perform any appropriate operations for channels which
        !           258:  * have events pending.
1.27      markus    259:  */
1.41    ! markus    260: typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
        !           261: chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
        !           262: chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
        !           263:
        !           264: void
        !           265: channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
        !           266: {
        !           267:        FD_SET(c->sock, readset);
        !           268: }
        !           269:
        !           270: void
        !           271: channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
        !           272: {
        !           273:        if (buffer_len(&c->input) < packet_get_maxsize())
        !           274:                FD_SET(c->sock, readset);
        !           275:        if (buffer_len(&c->output) > 0)
        !           276:                FD_SET(c->sock, writeset);
        !           277: }
1.1       deraadt   278:
1.41    ! markus    279: void
        !           280: channel_pre_open_15(Channel *c, fd_set * readset, fd_set * writeset)
        !           281: {
        !           282:        /* test whether sockets are 'alive' for read/write */
        !           283:        if (c->istate == CHAN_INPUT_OPEN)
        !           284:                if (buffer_len(&c->input) < packet_get_maxsize())
        !           285:                        FD_SET(c->sock, readset);
        !           286:        if (c->ostate == CHAN_OUTPUT_OPEN ||
        !           287:            c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
        !           288:                if (buffer_len(&c->output) > 0) {
        !           289:                        FD_SET(c->sock, writeset);
        !           290:                } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
        !           291:                        chan_obuf_empty(c);
        !           292:                }
        !           293:        }
        !           294: }
        !           295:
        !           296: void
        !           297: channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
        !           298: {
        !           299:        if (buffer_len(&c->input) == 0) {
        !           300:                packet_start(SSH_MSG_CHANNEL_CLOSE);
        !           301:                packet_put_int(c->remote_id);
        !           302:                packet_send();
        !           303:                c->type = SSH_CHANNEL_CLOSED;
        !           304:                debug("Closing channel %d after input drain.", c->self);
        !           305:        }
        !           306: }
        !           307:
        !           308: void
        !           309: channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
        !           310: {
        !           311:        if (buffer_len(&c->output) == 0)
        !           312:                channel_free(c->self);
        !           313:        else
        !           314:                FD_SET(c->sock, writeset);
        !           315: }
        !           316:
        !           317: /*
        !           318:  * This is a special state for X11 authentication spoofing.  An opened X11
        !           319:  * connection (when authentication spoofing is being done) remains in this
        !           320:  * state until the first packet has been completely read.  The authentication
        !           321:  * data in that packet is then substituted by the real data if it matches the
        !           322:  * fake data, and the channel is put into normal mode.
        !           323:  */
        !           324: int
        !           325: x11_open_helper(Channel *c)
1.1       deraadt   326: {
1.25      markus    327:        unsigned char *ucp;
                    328:        unsigned int proto_len, data_len;
                    329:
1.41    ! markus    330:        /* Check if the fixed size part of the packet is in buffer. */
        !           331:        if (buffer_len(&c->output) < 12)
        !           332:                return 0;
        !           333:
        !           334:        /* Parse the lengths of variable-length fields. */
        !           335:        ucp = (unsigned char *) buffer_ptr(&c->output);
        !           336:        if (ucp[0] == 0x42) {   /* Byte order MSB first. */
        !           337:                proto_len = 256 * ucp[6] + ucp[7];
        !           338:                data_len = 256 * ucp[8] + ucp[9];
        !           339:        } else if (ucp[0] == 0x6c) {    /* Byte order LSB first. */
        !           340:                proto_len = ucp[6] + 256 * ucp[7];
        !           341:                data_len = ucp[8] + 256 * ucp[9];
        !           342:        } else {
        !           343:                debug("Initial X11 packet contains bad byte order byte: 0x%x",
        !           344:                      ucp[0]);
        !           345:                return -1;
        !           346:        }
        !           347:
        !           348:        /* Check if the whole packet is in buffer. */
        !           349:        if (buffer_len(&c->output) <
        !           350:            12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
        !           351:                return 0;
        !           352:
        !           353:        /* Check if authentication protocol matches. */
        !           354:        if (proto_len != strlen(x11_saved_proto) ||
        !           355:            memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
        !           356:                debug("X11 connection uses different authentication protocol.");
        !           357:                return -1;
        !           358:        }
        !           359:        /* Check if authentication data matches our fake data. */
        !           360:        if (data_len != x11_fake_data_len ||
        !           361:            memcmp(ucp + 12 + ((proto_len + 3) & ~3),
        !           362:                x11_fake_data, x11_fake_data_len) != 0) {
        !           363:                debug("X11 auth data does not match fake data.");
        !           364:                return -1;
        !           365:        }
        !           366:        /* Check fake data length */
        !           367:        if (x11_fake_data_len != x11_saved_data_len) {
        !           368:                error("X11 fake_data_len %d != saved_data_len %d",
        !           369:                    x11_fake_data_len, x11_saved_data_len);
        !           370:                return -1;
        !           371:        }
        !           372:        /*
        !           373:         * Received authentication protocol and data match
        !           374:         * our fake data. Substitute the fake data with real
        !           375:         * data.
        !           376:         */
        !           377:        memcpy(ucp + 12 + ((proto_len + 3) & ~3),
        !           378:            x11_saved_data, x11_saved_data_len);
        !           379:        return 1;
        !           380: }
        !           381:
        !           382: void
        !           383: channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
        !           384: {
        !           385:        int ret = x11_open_helper(c);
        !           386:        if (ret == 1) {
        !           387:                /* Start normal processing for the channel. */
        !           388:                c->type = SSH_CHANNEL_OPEN;
        !           389:        } else if (ret == -1) {
        !           390:                /*
        !           391:                 * We have received an X11 connection that has bad
        !           392:                 * authentication information.
        !           393:                 */
        !           394:                log("X11 connection rejected because of wrong authentication.\r\n");
        !           395:                buffer_clear(&c->input);
        !           396:                buffer_clear(&c->output);
        !           397:                close(c->sock);
        !           398:                c->sock = -1;
        !           399:                c->type = SSH_CHANNEL_CLOSED;
        !           400:                packet_start(SSH_MSG_CHANNEL_CLOSE);
        !           401:                packet_put_int(c->remote_id);
        !           402:                packet_send();
        !           403:        }
        !           404: }
1.25      markus    405:
1.41    ! markus    406: void
        !           407: channel_pre_x11_open_15(Channel *c, fd_set * readset, fd_set * writeset)
        !           408: {
        !           409:        int ret = x11_open_helper(c);
        !           410:        if (ret == 1) {
        !           411:                c->type = SSH_CHANNEL_OPEN;
        !           412:        } else if (ret == -1) {
        !           413:                debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
        !           414:                chan_read_failed(c);
        !           415:                chan_write_failed(c);
        !           416:                debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
        !           417:        }
        !           418: }
1.25      markus    419:
1.41    ! markus    420: /* This is our fake X11 server socket. */
        !           421: void
        !           422: channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
        !           423: {
        !           424:        struct sockaddr addr;
        !           425:        int newsock, newch;
        !           426:        socklen_t addrlen;
        !           427:        char buf[16384], *remote_hostname;
1.25      markus    428:
1.41    ! markus    429:        if (FD_ISSET(c->sock, readset)) {
        !           430:                debug("X11 connection requested.");
        !           431:                addrlen = sizeof(addr);
        !           432:                newsock = accept(c->sock, &addr, &addrlen);
        !           433:                if (newsock < 0) {
        !           434:                        error("accept: %.100s", strerror(errno));
        !           435:                        return;
        !           436:                }
        !           437:                remote_hostname = get_remote_hostname(newsock);
        !           438:                snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
        !           439:                remote_hostname, get_peer_port(newsock));
        !           440:                xfree(remote_hostname);
        !           441:                newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
        !           442:                                         xstrdup(buf));
        !           443:                packet_start(SSH_SMSG_X11_OPEN);
        !           444:                packet_put_int(newch);
        !           445:                if (have_hostname_in_open)
        !           446:                        packet_put_string(buf, strlen(buf));
        !           447:                packet_send();
        !           448:        }
        !           449: }
1.25      markus    450:
1.41    ! markus    451: /*
        !           452:  * This socket is listening for connections to a forwarded TCP/IP port.
        !           453:  */
        !           454: void
        !           455: channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
        !           456: {
        !           457:        struct sockaddr addr;
        !           458:        int newsock, newch;
        !           459:        socklen_t addrlen;
        !           460:        char buf[1024], *remote_hostname;
        !           461:        int remote_port;
1.25      markus    462:
1.41    ! markus    463:        if (FD_ISSET(c->sock, readset)) {
        !           464:                debug("Connection to port %d forwarding "
        !           465:                    "to %.100s port %d requested.",
        !           466:                    c->listening_port, c->path, c->host_port);
        !           467:                addrlen = sizeof(addr);
        !           468:                newsock = accept(c->sock, &addr, &addrlen);
        !           469:                if (newsock < 0) {
        !           470:                        error("accept: %.100s", strerror(errno));
        !           471:                        return;
        !           472:                }
        !           473:                remote_hostname = get_remote_hostname(newsock);
        !           474:                remote_port = get_peer_port(newsock);
        !           475:                snprintf(buf, sizeof buf,
        !           476:                    "listen port %d for %.100s port %d, "
        !           477:                    "connect from %.200s port %d",
        !           478:                    c->listening_port, c->path, c->host_port,
        !           479:                    remote_hostname, remote_port);
        !           480:                newch = channel_new("direct-tcpip",
        !           481:                    SSH_CHANNEL_OPENING, newsock, newsock, -1,
        !           482:                    c->local_window_max, c->local_maxpacket,
        !           483:                    0, xstrdup(buf));
        !           484:
        !           485:                packet_start(SSH_MSG_PORT_OPEN);
        !           486:                packet_put_int(newch);
        !           487:                packet_put_string(c->path, strlen(c->path));
        !           488:                packet_put_int(c->host_port);
        !           489:                if (have_hostname_in_open) {
        !           490:                        packet_put_string(buf, strlen(buf));
        !           491:                }
        !           492:                packet_send();
        !           493:                xfree(remote_hostname);
        !           494:        }
        !           495: }
1.25      markus    496:
1.41    ! markus    497: /*
        !           498:  * This is the authentication agent socket listening for connections from
        !           499:  * clients.
        !           500:  */
        !           501: void
        !           502: channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
        !           503: {
        !           504:        struct sockaddr addr;
        !           505:        int newsock, newch;
        !           506:        socklen_t addrlen;
1.25      markus    507:
1.41    ! markus    508:        if (FD_ISSET(c->sock, readset)) {
        !           509:                addrlen = sizeof(addr);
        !           510:                newsock = accept(c->sock, &addr, &addrlen);
        !           511:                if (newsock < 0) {
        !           512:                        error("accept from auth socket: %.100s", strerror(errno));
        !           513:                        return;
        !           514:                }
        !           515:                newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
        !           516:                    xstrdup("accepted auth socket"));
        !           517:                packet_start(SSH_SMSG_AGENT_OPEN);
        !           518:                packet_put_int(newch);
        !           519:                packet_send();
        !           520:        }
        !           521: }
1.25      markus    522:
1.41    ! markus    523: int
        !           524: channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
        !           525: {
        !           526:        char buf[16*1024];
        !           527:        int len;
1.25      markus    528:
1.41    ! markus    529:        if (c->rfd != -1 &&
        !           530:            FD_ISSET(c->rfd, readset)) {
        !           531:                len = read(c->rfd, buf, sizeof(buf));
        !           532:                if (len <= 0) {
        !           533:                        debug("channel %d: read<0 rfd %d len %d",
        !           534:                            c->self, c->rfd, len);
1.25      markus    535:                        if (compat13) {
1.41    ! markus    536:                                buffer_consume(&c->output, buffer_len(&c->output));
        !           537:                                c->type = SSH_CHANNEL_INPUT_DRAINING;
        !           538:                                debug("Channel %d status set to input draining.", c->self);
1.25      markus    539:                        } else {
1.41    ! markus    540:                                chan_read_failed(c);
1.25      markus    541:                        }
1.41    ! markus    542:                        return -1;
        !           543:                }
        !           544:                buffer_append(&c->input, buf, len);
        !           545:        }
        !           546:        return 1;
        !           547: }
        !           548: int
        !           549: channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
        !           550: {
        !           551:        int len;
1.25      markus    552:
1.41    ! markus    553:        /* Send buffered output data to the socket. */
        !           554:        if (c->wfd != -1 &&
        !           555:            FD_ISSET(c->wfd, writeset) &&
        !           556:            buffer_len(&c->output) > 0) {
        !           557:                len = write(c->wfd, buffer_ptr(&c->output),
        !           558:                            buffer_len(&c->output));
        !           559:                if (len <= 0) {
        !           560:                        if (compat13) {
        !           561:                                buffer_consume(&c->output, buffer_len(&c->output));
        !           562:                                debug("Channel %d status set to input draining.", c->self);
        !           563:                                c->type = SSH_CHANNEL_INPUT_DRAINING;
        !           564:                        } else {
        !           565:                                chan_write_failed(c);
        !           566:                        }
        !           567:                        return -1;
1.25      markus    568:                }
1.41    ! markus    569:                buffer_consume(&c->output, len);
1.1       deraadt   570:        }
1.41    ! markus    571:        return 1;
1.1       deraadt   572: }
                    573:
1.41    ! markus    574: void
        !           575: channel_post_open_1(Channel *c, fd_set * readset, fd_set * writeset)
        !           576: {
        !           577:        channel_handle_rfd(c, readset, writeset);
        !           578:        channel_handle_wfd(c, readset, writeset);
        !           579: }
1.1       deraadt   580:
1.41    ! markus    581: void
        !           582: channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
1.1       deraadt   583: {
1.41    ! markus    584:        int len;
        !           585:        /* Send buffered output data to the socket. */
        !           586:        if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
        !           587:                len = write(c->sock, buffer_ptr(&c->output),
        !           588:                            buffer_len(&c->output));
        !           589:                if (len <= 0)
        !           590:                        buffer_consume(&c->output, buffer_len(&c->output));
        !           591:                else
        !           592:                        buffer_consume(&c->output, len);
        !           593:        }
        !           594: }
1.25      markus    595:
1.41    ! markus    596: void
        !           597: channel_handler_init_13(void)
        !           598: {
        !           599:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_13;
        !           600:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open_13;
        !           601:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
        !           602:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
        !           603:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
        !           604:        channel_pre[SSH_CHANNEL_INPUT_DRAINING] =       &channel_pre_input_draining;
        !           605:        channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] =      &channel_pre_output_draining;
1.25      markus    606:
1.41    ! markus    607:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_1;
        !           608:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
        !           609:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
        !           610:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
        !           611:        channel_post[SSH_CHANNEL_OUTPUT_DRAINING] =     &channel_post_output_drain_13;
        !           612: }
1.25      markus    613:
1.41    ! markus    614: void
        !           615: channel_handler_init_15(void)
        !           616: {
        !           617:        channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_15;
        !           618:        channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open_15;
        !           619:        channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
        !           620:        channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
        !           621:        channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1.25      markus    622:
1.41    ! markus    623:        channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
        !           624:        channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
        !           625:        channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
        !           626:        channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_1;
        !           627: }
1.27      markus    628:
1.41    ! markus    629: void
        !           630: channel_handler_init(void)
        !           631: {
        !           632:        int i;
        !           633:        for(i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
        !           634:                channel_pre[i] = NULL;
        !           635:                channel_post[i] = NULL;
        !           636:        }
        !           637:        if (compat13)
        !           638:                channel_handler_init_13();
        !           639:        else
        !           640:                channel_handler_init_15();
        !           641: }
1.25      markus    642:
1.41    ! markus    643: void
        !           644: channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
        !           645: {
        !           646:        static int did_init = 0;
        !           647:        int i;
        !           648:        Channel *c;
1.25      markus    649:
1.41    ! markus    650:        if (!did_init) {
        !           651:                channel_handler_init();
        !           652:                did_init = 1;
        !           653:        }
        !           654:        for (i = 0; i < channels_alloc; i++) {
        !           655:                c = &channels[i];
        !           656:                if (c->type == SSH_CHANNEL_FREE)
        !           657:                        continue;
        !           658:                if (ftab[c->type] == NULL)
1.25      markus    659:                        continue;
1.41    ! markus    660:                (*ftab[c->type])(c, readset, writeset);
        !           661:                chan_delete_if_full_closed(c);
1.1       deraadt   662:        }
                    663: }
                    664:
1.41    ! markus    665: void
        !           666: channel_prepare_select(fd_set * readset, fd_set * writeset)
        !           667: {
        !           668:        channel_handler(channel_pre, readset, writeset);
        !           669: }
        !           670:
        !           671: void
        !           672: channel_after_select(fd_set * readset, fd_set * writeset)
        !           673: {
        !           674:        channel_handler(channel_post, readset, writeset);
        !           675: }
        !           676:
1.1       deraadt   677: /* If there is data to send to the connection, send some of it now. */
                    678:
1.25      markus    679: void
                    680: channel_output_poll()
1.1       deraadt   681: {
1.25      markus    682:        int len, i;
1.41    ! markus    683:        Channel *c;
1.1       deraadt   684:
1.25      markus    685:        for (i = 0; i < channels_alloc; i++) {
1.41    ! markus    686:                c = &channels[i];
1.37      markus    687:
1.27      markus    688:                /* We are only interested in channels that can have buffered incoming data. */
1.37      markus    689:                if (compat13) {
1.41    ! markus    690:                        if (c->type != SSH_CHANNEL_OPEN &&
        !           691:                            c->type != SSH_CHANNEL_INPUT_DRAINING)
1.37      markus    692:                                continue;
                    693:                } else {
1.41    ! markus    694:                        if (c->type != SSH_CHANNEL_OPEN)
1.37      markus    695:                                continue;
1.41    ! markus    696:                        if (c->istate != CHAN_INPUT_OPEN &&
        !           697:                            c->istate != CHAN_INPUT_WAIT_DRAIN)
1.37      markus    698:                                continue;
                    699:                }
1.25      markus    700:
                    701:                /* Get the amount of buffered data for this channel. */
1.41    ! markus    702:                len = buffer_len(&c->input);
1.25      markus    703:                if (len > 0) {
1.27      markus    704:                        /* Send some data for the other side over the secure connection. */
1.25      markus    705:                        if (packet_is_interactive()) {
                    706:                                if (len > 1024)
                    707:                                        len = 512;
                    708:                        } else {
                    709:                                /* Keep the packets at reasonable size. */
1.40      markus    710:                                if (len > packet_get_maxsize())
1.34      markus    711:                                        len = packet_get_maxsize()/2;
1.25      markus    712:                        }
1.41    ! markus    713:                        if (len > 0) {
        !           714:                                packet_start(SSH_MSG_CHANNEL_DATA);
        !           715:                                packet_put_int(c->remote_id);
        !           716:                                packet_put_string(buffer_ptr(&c->input), len);
        !           717:                                packet_send();
        !           718:                                buffer_consume(&c->input, len);
        !           719:                                c->remote_window -= len;
        !           720: debug("channel %d: send data len %d", c->self, len);
        !           721:                        }
        !           722:                } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1.25      markus    723:                        if (compat13)
                    724:                                fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1.27      markus    725:                        /*
                    726:                         * input-buffer is empty and read-socket shutdown:
                    727:                         * tell peer, that we will not send more data: send IEOF
                    728:                         */
1.41    ! markus    729:                        chan_ibuf_empty(c);
1.25      markus    730:                }
                    731:        }
1.1       deraadt   732: }
                    733:
1.27      markus    734: /*
                    735:  * This is called when a packet of type CHANNEL_DATA has just been received.
                    736:  * The message type has already been consumed, but channel number and data is
                    737:  * still there.
                    738:  */
1.1       deraadt   739:
1.25      markus    740: void
1.41    ! markus    741: channel_input_data(int type, int plen)
1.1       deraadt   742: {
1.37      markus    743:        int id;
1.25      markus    744:        char *data;
                    745:        unsigned int data_len;
1.41    ! markus    746:        Channel *c;
1.25      markus    747:
                    748:        /* Get the channel number and verify it. */
1.37      markus    749:        id = packet_get_int();
1.41    ! markus    750:        c = channel_lookup(id);
        !           751:        if (c == NULL)
1.37      markus    752:                packet_disconnect("Received data for nonexistent channel %d.", id);
1.25      markus    753:
                    754:        /* Ignore any data for non-open channels (might happen on close) */
1.41    ! markus    755:        if (c->type != SSH_CHANNEL_OPEN &&
        !           756:            c->type != SSH_CHANNEL_X11_OPEN)
1.37      markus    757:                return;
                    758:
                    759:        /* same for protocol 1.5 if output end is no longer open */
1.41    ! markus    760:        if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
1.25      markus    761:                return;
                    762:
                    763:        /* Get the data. */
                    764:        data = packet_get_string(&data_len);
1.41    ! markus    765:
        !           766:        packet_integrity_check(plen, 4 + 4 + data_len, SSH_MSG_CHANNEL_DATA);
        !           767:        buffer_append(&c->output, data, data_len);
1.25      markus    768:        xfree(data);
1.1       deraadt   769: }
                    770:
1.27      markus    771: /*
                    772:  * Returns true if no channel has too much buffered data, and false if one or
                    773:  * more channel is overfull.
                    774:  */
1.1       deraadt   775:
1.25      markus    776: int
                    777: channel_not_very_much_buffered_data()
1.1       deraadt   778: {
1.25      markus    779:        unsigned int i;
1.41    ! markus    780:        Channel *c;
1.25      markus    781:
                    782:        for (i = 0; i < channels_alloc; i++) {
1.41    ! markus    783:                c = &channels[i];
        !           784:                if (c->type == SSH_CHANNEL_OPEN) {
        !           785:                        if (buffer_len(&c->input) > packet_get_maxsize()) {
        !           786:                                debug("channel %d: big input buffer %d",
        !           787:                                    c->self, buffer_len(&c->input));
1.25      markus    788:                                return 0;
1.41    ! markus    789:                        }
        !           790:                        if (buffer_len(&c->output) > packet_get_maxsize()) {
        !           791:                                debug("channel %d: big output buffer %d",
        !           792:                                    c->self, buffer_len(&c->output));
1.25      markus    793:                                return 0;
1.41    ! markus    794:                        }
1.25      markus    795:                }
1.1       deraadt   796:        }
1.25      markus    797:        return 1;
1.1       deraadt   798: }
                    799:
1.41    ! markus    800: void
        !           801: channel_input_ieof(int type, int plen)
        !           802: {
        !           803:        int id;
        !           804:        Channel *c;
        !           805:
        !           806:        packet_integrity_check(plen, 4, type);
        !           807:
        !           808:        id = packet_get_int();
        !           809:        c = channel_lookup(id);
        !           810:        if (c == NULL)
        !           811:                packet_disconnect("Received ieof for nonexistent channel %d.", id);
        !           812:        chan_rcvd_ieof(c);
        !           813: }
1.1       deraadt   814:
1.25      markus    815: void
1.41    ! markus    816: channel_input_close(int type, int plen)
1.1       deraadt   817: {
1.41    ! markus    818:        int id;
        !           819:        Channel *c;
1.1       deraadt   820:
1.41    ! markus    821:        packet_integrity_check(plen, 4, type);
        !           822:
        !           823:        id = packet_get_int();
        !           824:        c = channel_lookup(id);
        !           825:        if (c == NULL)
        !           826:                packet_disconnect("Received close for nonexistent channel %d.", id);
1.27      markus    827:
                    828:        /*
                    829:         * Send a confirmation that we have closed the channel and no more
                    830:         * data is coming for it.
                    831:         */
1.25      markus    832:        packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1.41    ! markus    833:        packet_put_int(c->remote_id);
1.25      markus    834:        packet_send();
                    835:
1.27      markus    836:        /*
                    837:         * If the channel is in closed state, we have sent a close request,
                    838:         * and the other side will eventually respond with a confirmation.
                    839:         * Thus, we cannot free the channel here, because then there would be
                    840:         * no-one to receive the confirmation.  The channel gets freed when
                    841:         * the confirmation arrives.
                    842:         */
1.41    ! markus    843:        if (c->type != SSH_CHANNEL_CLOSED) {
1.27      markus    844:                /*
                    845:                 * Not a closed channel - mark it as draining, which will
                    846:                 * cause it to be freed later.
                    847:                 */
1.41    ! markus    848:                buffer_consume(&c->input, buffer_len(&c->input));
        !           849:                c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1.25      markus    850:        }
1.1       deraadt   851: }
                    852:
1.41    ! markus    853: /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
        !           854: void
        !           855: channel_input_oclose(int type, int plen)
        !           856: {
        !           857:        int id = packet_get_int();
        !           858:        Channel *c = channel_lookup(id);
        !           859:        packet_integrity_check(plen, 4, type);
        !           860:        if (c == NULL)
        !           861:                packet_disconnect("Received oclose for nonexistent channel %d.", id);
        !           862:        chan_rcvd_oclose(c);
        !           863: }
1.1       deraadt   864:
1.25      markus    865: void
1.41    ! markus    866: channel_input_close_confirmation(int type, int plen)
1.1       deraadt   867: {
1.41    ! markus    868:        int id = packet_get_int();
        !           869:        Channel *c = channel_lookup(id);
1.1       deraadt   870:
1.41    ! markus    871:        if (c == NULL)
        !           872:                packet_disconnect("Received close confirmation for "
        !           873:                    "out-of-range channel %d.", id);
        !           874:        if (c->type != SSH_CHANNEL_CLOSED)
        !           875:                packet_disconnect("Received close confirmation for "
        !           876:                    "non-closed channel %d (type %d).", id, c->type);
        !           877:        channel_free(c->self);
1.1       deraadt   878: }
                    879:
1.25      markus    880: void
1.41    ! markus    881: channel_input_open_confirmation(int type, int plen)
1.1       deraadt   882: {
1.41    ! markus    883:        int id, remote_id;
        !           884:        Channel *c;
1.1       deraadt   885:
1.41    ! markus    886:        packet_integrity_check(plen, 4 + 4, type);
1.25      markus    887:
1.41    ! markus    888:        id = packet_get_int();
        !           889:        c = channel_lookup(id);
1.25      markus    890:
1.41    ! markus    891:        if (c==NULL || c->type != SSH_CHANNEL_OPENING)
        !           892:                packet_disconnect("Received open confirmation for "
        !           893:                    "non-opening channel %d.", id);
        !           894:        remote_id = packet_get_int();
1.27      markus    895:        /* Record the remote channel number and mark that the channel is now open. */
1.41    ! markus    896:        c->remote_id = remote_id;
        !           897:        c->type = SSH_CHANNEL_OPEN;
1.1       deraadt   898: }
                    899:
1.25      markus    900: void
1.41    ! markus    901: channel_input_open_failure(int type, int plen)
1.1       deraadt   902: {
1.41    ! markus    903:        int id;
        !           904:        Channel *c;
        !           905:
        !           906:        packet_integrity_check(plen, 4, type);
        !           907:
        !           908:        id = packet_get_int();
        !           909:        c = channel_lookup(id);
1.25      markus    910:
1.41    ! markus    911:        if (c==NULL || c->type != SSH_CHANNEL_OPENING)
        !           912:                packet_disconnect("Received open failure for "
        !           913:                    "non-opening channel %d.", id);
1.1       deraadt   914:
1.25      markus    915:        /* Free the channel.  This will also close the socket. */
1.41    ! markus    916:        channel_free(id);
1.1       deraadt   917: }
                    918:
1.27      markus    919: /*
                    920:  * Stops listening for channels, and removes any unix domain sockets that we
                    921:  * might have.
                    922:  */
1.1       deraadt   923:
1.25      markus    924: void
                    925: channel_stop_listening()
1.1       deraadt   926: {
1.25      markus    927:        int i;
                    928:        for (i = 0; i < channels_alloc; i++) {
                    929:                switch (channels[i].type) {
                    930:                case SSH_CHANNEL_AUTH_SOCKET:
                    931:                        close(channels[i].sock);
                    932:                        remove(channels[i].path);
                    933:                        channel_free(i);
                    934:                        break;
                    935:                case SSH_CHANNEL_PORT_LISTENER:
                    936:                case SSH_CHANNEL_X11_LISTENER:
                    937:                        close(channels[i].sock);
                    938:                        channel_free(i);
                    939:                        break;
                    940:                default:
                    941:                        break;
                    942:                }
1.1       deraadt   943:        }
                    944: }
                    945:
1.27      markus    946: /*
                    947:  * Closes the sockets of all channels.  This is used to close extra file
                    948:  * descriptors after a fork.
                    949:  */
1.1       deraadt   950:
1.25      markus    951: void
                    952: channel_close_all()
1.1       deraadt   953: {
1.25      markus    954:        int i;
                    955:        for (i = 0; i < channels_alloc; i++) {
                    956:                if (channels[i].type != SSH_CHANNEL_FREE)
                    957:                        close(channels[i].sock);
                    958:        }
1.1       deraadt   959: }
                    960:
                    961: /* Returns the maximum file descriptor number used by the channels. */
                    962:
1.25      markus    963: int
                    964: channel_max_fd()
1.1       deraadt   965: {
1.25      markus    966:        return channel_max_fd_value;
1.1       deraadt   967: }
                    968:
                    969: /* Returns true if any channel is still open. */
                    970:
1.25      markus    971: int
                    972: channel_still_open()
1.1       deraadt   973: {
1.25      markus    974:        unsigned int i;
                    975:        for (i = 0; i < channels_alloc; i++)
                    976:                switch (channels[i].type) {
                    977:                case SSH_CHANNEL_FREE:
                    978:                case SSH_CHANNEL_X11_LISTENER:
                    979:                case SSH_CHANNEL_PORT_LISTENER:
                    980:                case SSH_CHANNEL_CLOSED:
                    981:                case SSH_CHANNEL_AUTH_SOCKET:
                    982:                        continue;
                    983:                case SSH_CHANNEL_OPENING:
                    984:                case SSH_CHANNEL_OPEN:
                    985:                case SSH_CHANNEL_X11_OPEN:
                    986:                        return 1;
                    987:                case SSH_CHANNEL_INPUT_DRAINING:
                    988:                case SSH_CHANNEL_OUTPUT_DRAINING:
                    989:                        if (!compat13)
                    990:                                fatal("cannot happen: OUT_DRAIN");
                    991:                        return 1;
                    992:                default:
                    993:                        fatal("channel_still_open: bad channel type %d", channels[i].type);
                    994:                        /* NOTREACHED */
                    995:                }
                    996:        return 0;
1.1       deraadt   997: }
                    998:
1.27      markus    999: /*
                   1000:  * Returns a message describing the currently open forwarded connections,
                   1001:  * suitable for sending to the client.  The message contains crlf pairs for
                   1002:  * newlines.
                   1003:  */
1.1       deraadt  1004:
1.25      markus   1005: char *
                   1006: channel_open_message()
1.1       deraadt  1007: {
1.25      markus   1008:        Buffer buffer;
                   1009:        int i;
                   1010:        char buf[512], *cp;
                   1011:
                   1012:        buffer_init(&buffer);
                   1013:        snprintf(buf, sizeof buf, "The following connections are open:\r\n");
1.1       deraadt  1014:        buffer_append(&buffer, buf, strlen(buf));
1.25      markus   1015:        for (i = 0; i < channels_alloc; i++) {
                   1016:                Channel *c = &channels[i];
                   1017:                switch (c->type) {
                   1018:                case SSH_CHANNEL_FREE:
                   1019:                case SSH_CHANNEL_X11_LISTENER:
                   1020:                case SSH_CHANNEL_PORT_LISTENER:
                   1021:                case SSH_CHANNEL_CLOSED:
                   1022:                case SSH_CHANNEL_AUTH_SOCKET:
                   1023:                        continue;
                   1024:                case SSH_CHANNEL_OPENING:
                   1025:                case SSH_CHANNEL_OPEN:
                   1026:                case SSH_CHANNEL_X11_OPEN:
                   1027:                case SSH_CHANNEL_INPUT_DRAINING:
                   1028:                case SSH_CHANNEL_OUTPUT_DRAINING:
1.41    ! markus   1029:                        snprintf(buf, sizeof buf, "  #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
1.37      markus   1030:                            c->self, c->remote_name,
                   1031:                            c->type, c->remote_id,
                   1032:                            c->istate, buffer_len(&c->input),
1.41    ! markus   1033:                            c->ostate, buffer_len(&c->output),
        !          1034:                            c->rfd, c->wfd);
1.25      markus   1035:                        buffer_append(&buffer, buf, strlen(buf));
                   1036:                        continue;
                   1037:                default:
1.41    ! markus   1038:                        fatal("channel_open_message: bad channel type %d", c->type);
1.25      markus   1039:                        /* NOTREACHED */
                   1040:                }
                   1041:        }
                   1042:        buffer_append(&buffer, "\0", 1);
                   1043:        cp = xstrdup(buffer_ptr(&buffer));
                   1044:        buffer_free(&buffer);
                   1045:        return cp;
1.1       deraadt  1046: }
                   1047:
1.27      markus   1048: /*
                   1049:  * Initiate forwarding of connections to local port "port" through the secure
                   1050:  * channel to host:port from remote side.
                   1051:  */
1.1       deraadt  1052:
1.25      markus   1053: void
1.31      markus   1054: channel_request_local_forwarding(u_short port, const char *host,
1.33      markus   1055:                                 u_short host_port, int gateway_ports)
1.25      markus   1056: {
1.35      markus   1057:        int success, ch, sock, on = 1;
                   1058:        struct addrinfo hints, *ai, *aitop;
                   1059:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1.28      markus   1060:        struct linger linger;
1.25      markus   1061:
                   1062:        if (strlen(host) > sizeof(channels[0].path) - 1)
                   1063:                packet_disconnect("Forward host name too long.");
                   1064:
1.28      markus   1065:        /*
1.35      markus   1066:         * getaddrinfo returns a loopback address if the hostname is
                   1067:         * set to NULL and hints.ai_flags is not AI_PASSIVE
1.28      markus   1068:         */
1.35      markus   1069:        memset(&hints, 0, sizeof(hints));
                   1070:        hints.ai_family = IPv4or6;
                   1071:        hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
                   1072:        hints.ai_socktype = SOCK_STREAM;
                   1073:        snprintf(strport, sizeof strport, "%d", port);
                   1074:        if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
                   1075:                packet_disconnect("getaddrinfo: fatal error");
                   1076:
                   1077:        success = 0;
                   1078:        for (ai = aitop; ai; ai = ai->ai_next) {
                   1079:                if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   1080:                        continue;
                   1081:                if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
                   1082:                    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
                   1083:                        error("channel_request_local_forwarding: getnameinfo failed");
                   1084:                        continue;
                   1085:                }
                   1086:                /* Create a port to listen for the host. */
                   1087:                sock = socket(ai->ai_family, SOCK_STREAM, 0);
                   1088:                if (sock < 0) {
                   1089:                        /* this is no error since kernel may not support ipv6 */
                   1090:                        verbose("socket: %.100s", strerror(errno));
                   1091:                        continue;
                   1092:                }
                   1093:                /*
                   1094:                 * Set socket options.  We would like the socket to disappear
                   1095:                 * as soon as it has been closed for whatever reason.
                   1096:                 */
                   1097:                setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
                   1098:                linger.l_onoff = 1;
                   1099:                linger.l_linger = 5;
                   1100:                setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
                   1101:                debug("Local forwarding listening on %s port %s.", ntop, strport);
                   1102:
                   1103:                /* Bind the socket to the address. */
                   1104:                if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   1105:                        /* address can be in use ipv6 address is already bound */
                   1106:                        verbose("bind: %.100s", strerror(errno));
                   1107:                        close(sock);
                   1108:                        continue;
                   1109:                }
                   1110:                /* Start listening for connections on the socket. */
                   1111:                if (listen(sock, 5) < 0) {
                   1112:                        error("listen: %.100s", strerror(errno));
                   1113:                        close(sock);
                   1114:                        continue;
                   1115:                }
                   1116:                /* Allocate a channel number for the socket. */
1.41    ! markus   1117:                ch = channel_new(
        !          1118:                    "port listener", SSH_CHANNEL_PORT_LISTENER,
        !          1119:                    sock, sock, -1,
        !          1120:                    CHAN_WINDOW_DEFAULT, CHAN_PACKET_DEFAULT,
        !          1121:                    0, xstrdup("port listener"));
1.35      markus   1122:                strlcpy(channels[ch].path, host, sizeof(channels[ch].path));
                   1123:                channels[ch].host_port = host_port;
                   1124:                channels[ch].listening_port = port;
                   1125:                success = 1;
                   1126:        }
                   1127:        if (success == 0)
                   1128:                packet_disconnect("cannot listen port: %d", port);
                   1129:        freeaddrinfo(aitop);
1.25      markus   1130: }
1.1       deraadt  1131:
1.27      markus   1132: /*
                   1133:  * Initiate forwarding of connections to port "port" on remote host through
                   1134:  * the secure channel to host:port from local side.
                   1135:  */
1.1       deraadt  1136:
1.25      markus   1137: void
1.41    ! markus   1138: channel_request_remote_forwarding(u_short listen_port, const char *host_to_connect,
        !          1139:                                  u_short port_to_connect)
1.25      markus   1140: {
                   1141:        int payload_len;
                   1142:        /* Record locally that connection to this host/port is permitted. */
                   1143:        if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
                   1144:                fatal("channel_request_remote_forwarding: too many forwards");
                   1145:
1.41    ! markus   1146:        permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
        !          1147:        permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
        !          1148:        permitted_opens[num_permitted_opens].listen_port = listen_port;
1.25      markus   1149:        num_permitted_opens++;
                   1150:
                   1151:        /* Send the forward request to the remote side. */
                   1152:        packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1.41    ! markus   1153:        packet_put_int(port_to_connect);
        !          1154:        packet_put_string(host_to_connect, strlen(host_to_connect));
        !          1155:        packet_put_int(listen_port);
1.25      markus   1156:        packet_send();
                   1157:        packet_write_wait();
1.27      markus   1158:        /*
                   1159:         * Wait for response from the remote side.  It will send a disconnect
                   1160:         * message on failure, and we will never see it here.
                   1161:         */
1.25      markus   1162:        packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1.1       deraadt  1163: }
                   1164:
1.27      markus   1165: /*
                   1166:  * This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
                   1167:  * listening for the port, and sends back a success reply (or disconnect
                   1168:  * message if there was an error).  This never returns if there was an error.
                   1169:  */
1.1       deraadt  1170:
1.25      markus   1171: void
                   1172: channel_input_port_forward_request(int is_root)
1.1       deraadt  1173: {
1.31      markus   1174:        u_short port, host_port;
1.25      markus   1175:        char *hostname;
1.1       deraadt  1176:
1.25      markus   1177:        /* Get arguments from the packet. */
                   1178:        port = packet_get_int();
                   1179:        hostname = packet_get_string(NULL);
                   1180:        host_port = packet_get_int();
                   1181:
1.27      markus   1182:        /*
                   1183:         * Check that an unprivileged user is not trying to forward a
                   1184:         * privileged port.
                   1185:         */
1.25      markus   1186:        if (port < IPPORT_RESERVED && !is_root)
                   1187:                packet_disconnect("Requested forwarding of port %d but user is not root.",
                   1188:                                  port);
1.33      markus   1189:        /*
                   1190:         * Initiate forwarding,
                   1191:         * bind port to localhost only (gateway ports == 0).
                   1192:         */
                   1193:        channel_request_local_forwarding(port, hostname, host_port, 0);
1.25      markus   1194:
                   1195:        /* Free the argument string. */
                   1196:        xfree(hostname);
1.1       deraadt  1197: }
                   1198:
1.41    ! markus   1199: /* XXX move to aux.c */
        !          1200: int
        !          1201: channel_connect_to(const char *host, u_short host_port)
        !          1202: {
        !          1203:        struct addrinfo hints, *ai, *aitop;
        !          1204:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
        !          1205:        int gaierr;
        !          1206:        int sock = -1;
        !          1207:
        !          1208:        memset(&hints, 0, sizeof(hints));
        !          1209:        hints.ai_family = IPv4or6;
        !          1210:        hints.ai_socktype = SOCK_STREAM;
        !          1211:        snprintf(strport, sizeof strport, "%d", host_port);
        !          1212:        if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
        !          1213:                error("%.100s: unknown host (%s)", host, gai_strerror(gaierr));
        !          1214:                return -1;
        !          1215:        }
        !          1216:        for (ai = aitop; ai; ai = ai->ai_next) {
        !          1217:                if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
        !          1218:                        continue;
        !          1219:                if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
        !          1220:                    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
        !          1221:                        error("channel_connect_to: getnameinfo failed");
        !          1222:                        continue;
        !          1223:                }
        !          1224:                /* Create the socket. */
        !          1225:                sock = socket(ai->ai_family, SOCK_STREAM, 0);
        !          1226:                if (sock < 0) {
        !          1227:                        error("socket: %.100s", strerror(errno));
        !          1228:                        continue;
        !          1229:                }
        !          1230:                /* Connect to the host/port. */
        !          1231:                if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
        !          1232:                        error("connect %.100s port %s: %.100s", ntop, strport,
        !          1233:                            strerror(errno));
        !          1234:                        close(sock);
        !          1235:                        continue;       /* fail -- try next */
        !          1236:                }
        !          1237:                break; /* success */
        !          1238:
        !          1239:        }
        !          1240:        freeaddrinfo(aitop);
        !          1241:        if (!ai) {
        !          1242:                error("connect %.100s port %d: failed.", host, host_port);
        !          1243:                return -1;
        !          1244:        }
        !          1245:        /* success */
        !          1246:        return sock;
        !          1247: }
1.27      markus   1248: /*
                   1249:  * This is called after receiving PORT_OPEN message.  This attempts to
                   1250:  * connect to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION
                   1251:  * or CHANNEL_OPEN_FAILURE.
                   1252:  */
1.1       deraadt  1253:
1.25      markus   1254: void
1.41    ! markus   1255: channel_input_port_open(int type, int plen)
1.1       deraadt  1256: {
1.31      markus   1257:        u_short host_port;
1.25      markus   1258:        char *host, *originator_string;
1.41    ! markus   1259:        int remote_channel, sock = -1, newch, i, denied;
1.39      markus   1260:        unsigned int host_len, originator_len;
1.25      markus   1261:
                   1262:        /* Get remote channel number. */
                   1263:        remote_channel = packet_get_int();
                   1264:
                   1265:        /* Get host name to connect to. */
                   1266:        host = packet_get_string(&host_len);
                   1267:
                   1268:        /* Get port to connect to. */
                   1269:        host_port = packet_get_int();
                   1270:
                   1271:        /* Get remote originator name. */
1.29      markus   1272:        if (have_hostname_in_open) {
1.25      markus   1273:                originator_string = packet_get_string(&originator_len);
1.29      markus   1274:                originator_len += 4;    /* size of packet_int */
                   1275:        } else {
1.25      markus   1276:                originator_string = xstrdup("unknown (remote did not supply name)");
1.29      markus   1277:                originator_len = 0;     /* no originator supplied */
                   1278:        }
1.25      markus   1279:
1.41    ! markus   1280:        packet_integrity_check(plen,
        !          1281:            4 + 4 + host_len + 4 + originator_len, SSH_MSG_PORT_OPEN);
1.25      markus   1282:
                   1283:        /* Check if opening that port is permitted. */
1.41    ! markus   1284:        denied = 0;
1.25      markus   1285:        if (!all_opens_permitted) {
                   1286:                /* Go trough all permitted ports. */
                   1287:                for (i = 0; i < num_permitted_opens; i++)
1.41    ! markus   1288:                        if (permitted_opens[i].port_to_connect == host_port &&
        !          1289:                            strcmp(permitted_opens[i].host_to_connect, host) == 0)
1.25      markus   1290:                                break;
                   1291:
                   1292:                /* Check if we found the requested port among those permitted. */
                   1293:                if (i >= num_permitted_opens) {
                   1294:                        /* The port is not permitted. */
                   1295:                        log("Received request to connect to %.100s:%d, but the request was denied.",
                   1296:                            host, host_port);
1.41    ! markus   1297:                        denied = 1;
1.25      markus   1298:                }
                   1299:        }
1.41    ! markus   1300:        sock = denied ? -1 : channel_connect_to(host, host_port);
        !          1301:        if (sock > 0) {
        !          1302:                /* Allocate a channel for this connection. */
        !          1303:                newch = channel_allocate(SSH_CHANNEL_OPEN, sock, originator_string);
        !          1304:                channels[newch].remote_id = remote_channel;
        !          1305:
        !          1306:                packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
        !          1307:                packet_put_int(remote_channel);
        !          1308:                packet_put_int(newch);
        !          1309:                packet_send();
        !          1310:        } else {
        !          1311:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
        !          1312:                packet_put_int(remote_channel);
        !          1313:                packet_send();
1.25      markus   1314:        }
                   1315:        xfree(host);
1.1       deraadt  1316: }
                   1317:
1.27      markus   1318: /*
                   1319:  * Creates an internet domain socket for listening for X11 connections.
                   1320:  * Returns a suitable value for the DISPLAY variable, or NULL if an error
                   1321:  * occurs.
                   1322:  */
1.1       deraadt  1323:
1.35      markus   1324: #define        NUM_SOCKS       10
                   1325:
1.25      markus   1326: char *
1.33      markus   1327: x11_create_display_inet(int screen_number, int x11_display_offset)
1.1       deraadt  1328: {
1.31      markus   1329:        int display_number, sock;
                   1330:        u_short port;
1.35      markus   1331:        struct addrinfo hints, *ai, *aitop;
                   1332:        char strport[NI_MAXSERV];
                   1333:        int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
                   1334:        char display[512];
1.25      markus   1335:        char hostname[MAXHOSTNAMELEN];
                   1336:
1.33      markus   1337:        for (display_number = x11_display_offset;
1.25      markus   1338:             display_number < MAX_DISPLAYS;
                   1339:             display_number++) {
                   1340:                port = 6000 + display_number;
1.35      markus   1341:                memset(&hints, 0, sizeof(hints));
                   1342:                hints.ai_family = IPv4or6;
1.36      markus   1343:                hints.ai_flags = AI_PASSIVE;            /* XXX loopback only ? */
1.35      markus   1344:                hints.ai_socktype = SOCK_STREAM;
                   1345:                snprintf(strport, sizeof strport, "%d", port);
                   1346:                if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
                   1347:                        error("getaddrinfo: %.100s", gai_strerror(gaierr));
1.25      markus   1348:                        return NULL;
                   1349:                }
1.35      markus   1350:                for (ai = aitop; ai; ai = ai->ai_next) {
                   1351:                        if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   1352:                                continue;
                   1353:                        sock = socket(ai->ai_family, SOCK_STREAM, 0);
                   1354:                        if (sock < 0) {
                   1355:                                error("socket: %.100s", strerror(errno));
                   1356:                                return NULL;
                   1357:                        }
                   1358:                        if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   1359:                                debug("bind port %d: %.100s", port, strerror(errno));
                   1360:                                shutdown(sock, SHUT_RDWR);
                   1361:                                close(sock);
                   1362:                                for (n = 0; n < num_socks; n++) {
                   1363:                                        shutdown(socks[n], SHUT_RDWR);
                   1364:                                        close(socks[n]);
                   1365:                                }
                   1366:                                num_socks = 0;
                   1367:                                break;
                   1368:                        }
                   1369:                        socks[num_socks++] = sock;
                   1370:                        if (num_socks == NUM_SOCKS)
                   1371:                                break;
1.25      markus   1372:                }
1.35      markus   1373:                if (num_socks > 0)
                   1374:                        break;
1.25      markus   1375:        }
                   1376:        if (display_number >= MAX_DISPLAYS) {
                   1377:                error("Failed to allocate internet-domain X11 display socket.");
                   1378:                return NULL;
                   1379:        }
                   1380:        /* Start listening for connections on the socket. */
1.35      markus   1381:        for (n = 0; n < num_socks; n++) {
                   1382:                sock = socks[n];
                   1383:                if (listen(sock, 5) < 0) {
                   1384:                        error("listen: %.100s", strerror(errno));
                   1385:                        shutdown(sock, SHUT_RDWR);
                   1386:                        close(sock);
                   1387:                        return NULL;
                   1388:                }
1.25      markus   1389:        }
1.35      markus   1390:
1.25      markus   1391:        /* Set up a suitable value for the DISPLAY variable. */
                   1392:        if (gethostname(hostname, sizeof(hostname)) < 0)
                   1393:                fatal("gethostname: %.100s", strerror(errno));
1.35      markus   1394:        snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
1.25      markus   1395:                 display_number, screen_number);
                   1396:
1.35      markus   1397:        /* Allocate a channel for each socket. */
                   1398:        for (n = 0; n < num_socks; n++) {
                   1399:                sock = socks[n];
                   1400:                (void) channel_allocate(SSH_CHANNEL_X11_LISTENER, sock,
                   1401:                                        xstrdup("X11 inet listener"));
                   1402:        }
1.1       deraadt  1403:
1.25      markus   1404:        /* Return a suitable value for the DISPLAY environment variable. */
1.35      markus   1405:        return xstrdup(display);
1.1       deraadt  1406: }
                   1407:
                   1408: #ifndef X_UNIX_PATH
                   1409: #define X_UNIX_PATH "/tmp/.X11-unix/X"
                   1410: #endif
                   1411:
                   1412: static
                   1413: int
1.30      deraadt  1414: connect_local_xsocket(unsigned int dnr)
1.1       deraadt  1415: {
1.25      markus   1416:        static const char *const x_sockets[] = {
                   1417:                X_UNIX_PATH "%u",
                   1418:                "/var/X/.X11-unix/X" "%u",
                   1419:                "/usr/spool/sockets/X11/" "%u",
                   1420:                NULL
                   1421:        };
                   1422:        int sock;
                   1423:        struct sockaddr_un addr;
                   1424:        const char *const * path;
                   1425:
                   1426:        for (path = x_sockets; *path; ++path) {
                   1427:                sock = socket(AF_UNIX, SOCK_STREAM, 0);
                   1428:                if (sock < 0)
                   1429:                        error("socket: %.100s", strerror(errno));
                   1430:                memset(&addr, 0, sizeof(addr));
                   1431:                addr.sun_family = AF_UNIX;
                   1432:                snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
                   1433:                if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
                   1434:                        return sock;
                   1435:                close(sock);
                   1436:        }
                   1437:        error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
                   1438:        return -1;
1.1       deraadt  1439: }
                   1440:
                   1441:
1.27      markus   1442: /*
                   1443:  * This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
                   1444:  * the remote channel number.  We should do whatever we want, and respond
                   1445:  * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
                   1446:  */
1.1       deraadt  1447:
1.25      markus   1448: void
1.41    ! markus   1449: x11_input_open(int type, int plen)
1.1       deraadt  1450: {
1.35      markus   1451:        int remote_channel, display_number, sock = 0, newch;
1.25      markus   1452:        const char *display;
                   1453:        char buf[1024], *cp, *remote_host;
1.39      markus   1454:        unsigned int remote_len;
1.35      markus   1455:        struct addrinfo hints, *ai, *aitop;
                   1456:        char strport[NI_MAXSERV];
                   1457:        int gaierr;
1.25      markus   1458:
                   1459:        /* Get remote channel number. */
                   1460:        remote_channel = packet_get_int();
                   1461:
                   1462:        /* Get remote originator name. */
1.29      markus   1463:        if (have_hostname_in_open) {
1.25      markus   1464:                remote_host = packet_get_string(&remote_len);
1.29      markus   1465:                remote_len += 4;
                   1466:        } else {
1.25      markus   1467:                remote_host = xstrdup("unknown (remote did not supply name)");
1.29      markus   1468:                remote_len = 0;
                   1469:        }
1.25      markus   1470:
                   1471:        debug("Received X11 open request.");
1.41    ! markus   1472:        packet_integrity_check(plen, 4 + remote_len, SSH_SMSG_X11_OPEN);
1.25      markus   1473:
                   1474:        /* Try to open a socket for the local X server. */
                   1475:        display = getenv("DISPLAY");
                   1476:        if (!display) {
                   1477:                error("DISPLAY not set.");
                   1478:                goto fail;
                   1479:        }
1.27      markus   1480:        /*
                   1481:         * Now we decode the value of the DISPLAY variable and make a
                   1482:         * connection to the real X server.
                   1483:         */
                   1484:
                   1485:        /*
                   1486:         * Check if it is a unix domain socket.  Unix domain displays are in
                   1487:         * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
                   1488:         */
1.25      markus   1489:        if (strncmp(display, "unix:", 5) == 0 ||
                   1490:            display[0] == ':') {
                   1491:                /* Connect to the unix domain socket. */
                   1492:                if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
                   1493:                        error("Could not parse display number from DISPLAY: %.100s",
                   1494:                              display);
                   1495:                        goto fail;
                   1496:                }
                   1497:                /* Create a socket. */
                   1498:                sock = connect_local_xsocket(display_number);
                   1499:                if (sock < 0)
                   1500:                        goto fail;
                   1501:
                   1502:                /* OK, we now have a connection to the display. */
                   1503:                goto success;
                   1504:        }
1.27      markus   1505:        /*
                   1506:         * Connect to an inet socket.  The DISPLAY value is supposedly
                   1507:         * hostname:d[.s], where hostname may also be numeric IP address.
                   1508:         */
1.25      markus   1509:        strncpy(buf, display, sizeof(buf));
                   1510:        buf[sizeof(buf) - 1] = 0;
                   1511:        cp = strchr(buf, ':');
                   1512:        if (!cp) {
                   1513:                error("Could not find ':' in DISPLAY: %.100s", display);
                   1514:                goto fail;
                   1515:        }
                   1516:        *cp = 0;
1.27      markus   1517:        /* buf now contains the host name.  But first we parse the display number. */
1.25      markus   1518:        if (sscanf(cp + 1, "%d", &display_number) != 1) {
                   1519:                error("Could not parse display number from DISPLAY: %.100s",
                   1520:                      display);
                   1521:                goto fail;
                   1522:        }
1.35      markus   1523:
                   1524:        /* Look up the host address */
                   1525:        memset(&hints, 0, sizeof(hints));
                   1526:        hints.ai_family = IPv4or6;
                   1527:        hints.ai_socktype = SOCK_STREAM;
                   1528:        snprintf(strport, sizeof strport, "%d", 6000 + display_number);
                   1529:        if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
                   1530:                error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
1.25      markus   1531:                goto fail;
                   1532:        }
1.35      markus   1533:        for (ai = aitop; ai; ai = ai->ai_next) {
                   1534:                /* Create a socket. */
                   1535:                sock = socket(ai->ai_family, SOCK_STREAM, 0);
                   1536:                if (sock < 0) {
                   1537:                        debug("socket: %.100s", strerror(errno));
1.41    ! markus   1538:                        continue;
        !          1539:                }
        !          1540:                /* Connect it to the display. */
        !          1541:                if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
        !          1542:                        debug("connect %.100s port %d: %.100s", buf,
        !          1543:                            6000 + display_number, strerror(errno));
        !          1544:                        close(sock);
        !          1545:                        continue;
        !          1546:                }
        !          1547:                /* Success */
        !          1548:                break;
1.35      markus   1549:        }
                   1550:        freeaddrinfo(aitop);
                   1551:        if (!ai) {
                   1552:                error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
                   1553:                    strerror(errno));
1.25      markus   1554:                goto fail;
                   1555:        }
                   1556: success:
                   1557:        /* We have successfully obtained a connection to the real X display. */
                   1558:
                   1559:        /* Allocate a channel for this connection. */
                   1560:        if (x11_saved_proto == NULL)
                   1561:                newch = channel_allocate(SSH_CHANNEL_OPEN, sock, remote_host);
                   1562:        else
                   1563:                newch = channel_allocate(SSH_CHANNEL_X11_OPEN, sock, remote_host);
                   1564:        channels[newch].remote_id = remote_channel;
                   1565:
                   1566:        /* Send a confirmation to the remote host. */
                   1567:        packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1568:        packet_put_int(remote_channel);
                   1569:        packet_put_int(newch);
                   1570:        packet_send();
                   1571:
                   1572:        return;
                   1573:
                   1574: fail:
                   1575:        /* Send refusal to the remote host. */
                   1576:        packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   1577:        packet_put_int(remote_channel);
                   1578:        packet_send();
1.1       deraadt  1579: }
                   1580:
1.27      markus   1581: /*
                   1582:  * Requests forwarding of X11 connections, generates fake authentication
                   1583:  * data, and enables authentication spoofing.
                   1584:  */
1.1       deraadt  1585:
1.25      markus   1586: void
                   1587: x11_request_forwarding_with_spoofing(const char *proto, const char *data)
1.1       deraadt  1588: {
1.25      markus   1589:        unsigned int data_len = (unsigned int) strlen(data) / 2;
                   1590:        unsigned int i, value;
                   1591:        char *new_data;
                   1592:        int screen_number;
                   1593:        const char *cp;
                   1594:        u_int32_t rand = 0;
                   1595:
                   1596:        cp = getenv("DISPLAY");
                   1597:        if (cp)
                   1598:                cp = strchr(cp, ':');
                   1599:        if (cp)
                   1600:                cp = strchr(cp, '.');
                   1601:        if (cp)
                   1602:                screen_number = atoi(cp + 1);
                   1603:        else
                   1604:                screen_number = 0;
                   1605:
                   1606:        /* Save protocol name. */
                   1607:        x11_saved_proto = xstrdup(proto);
                   1608:
1.27      markus   1609:        /*
                   1610:         * Extract real authentication data and generate fake data of the
                   1611:         * same length.
                   1612:         */
1.25      markus   1613:        x11_saved_data = xmalloc(data_len);
                   1614:        x11_fake_data = xmalloc(data_len);
                   1615:        for (i = 0; i < data_len; i++) {
                   1616:                if (sscanf(data + 2 * i, "%2x", &value) != 1)
                   1617:                        fatal("x11_request_forwarding: bad authentication data: %.100s", data);
                   1618:                if (i % 4 == 0)
                   1619:                        rand = arc4random();
                   1620:                x11_saved_data[i] = value;
                   1621:                x11_fake_data[i] = rand & 0xff;
                   1622:                rand >>= 8;
                   1623:        }
                   1624:        x11_saved_data_len = data_len;
                   1625:        x11_fake_data_len = data_len;
                   1626:
                   1627:        /* Convert the fake data into hex. */
                   1628:        new_data = xmalloc(2 * data_len + 1);
                   1629:        for (i = 0; i < data_len; i++)
                   1630:                sprintf(new_data + 2 * i, "%02x", (unsigned char) x11_fake_data[i]);
                   1631:
                   1632:        /* Send the request packet. */
                   1633:        packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
                   1634:        packet_put_string(proto, strlen(proto));
                   1635:        packet_put_string(new_data, strlen(new_data));
                   1636:        packet_put_int(screen_number);
                   1637:        packet_send();
                   1638:        packet_write_wait();
                   1639:        xfree(new_data);
1.1       deraadt  1640: }
                   1641:
                   1642: /* Sends a message to the server to request authentication fd forwarding. */
                   1643:
1.25      markus   1644: void
                   1645: auth_request_forwarding()
1.1       deraadt  1646: {
1.25      markus   1647:        packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
                   1648:        packet_send();
                   1649:        packet_write_wait();
1.1       deraadt  1650: }
                   1651:
1.27      markus   1652: /*
                   1653:  * Returns the name of the forwarded authentication socket.  Returns NULL if
                   1654:  * there is no forwarded authentication socket.  The returned value points to
                   1655:  * a static buffer.
                   1656:  */
1.1       deraadt  1657:
1.25      markus   1658: char *
                   1659: auth_get_socket_name()
1.1       deraadt  1660: {
1.25      markus   1661:        return channel_forwarded_auth_socket_name;
1.1       deraadt  1662: }
                   1663:
1.12      markus   1664: /* removes the agent forwarding socket */
                   1665:
1.25      markus   1666: void
                   1667: cleanup_socket(void)
                   1668: {
                   1669:        remove(channel_forwarded_auth_socket_name);
                   1670:        rmdir(channel_forwarded_auth_socket_dir);
1.12      markus   1671: }
                   1672:
1.27      markus   1673: /*
                   1674:  * This if called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
                   1675:  * This starts forwarding authentication requests.
                   1676:  */
1.1       deraadt  1677:
1.25      markus   1678: void
                   1679: auth_input_request_forwarding(struct passwd * pw)
1.1       deraadt  1680: {
1.25      markus   1681:        int sock, newch;
                   1682:        struct sockaddr_un sunaddr;
                   1683:
                   1684:        if (auth_get_socket_name() != NULL)
                   1685:                fatal("Protocol error: authentication forwarding requested twice.");
                   1686:
                   1687:        /* Temporarily drop privileged uid for mkdir/bind. */
                   1688:        temporarily_use_uid(pw->pw_uid);
                   1689:
                   1690:        /* Allocate a buffer for the socket name, and format the name. */
                   1691:        channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
                   1692:        channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
                   1693:        strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
                   1694:
                   1695:        /* Create private directory for socket */
                   1696:        if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL)
                   1697:                packet_disconnect("mkdtemp: %.100s", strerror(errno));
                   1698:        snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME, "%s/agent.%d",
                   1699:                 channel_forwarded_auth_socket_dir, (int) getpid());
                   1700:
                   1701:        if (atexit(cleanup_socket) < 0) {
                   1702:                int saved = errno;
                   1703:                cleanup_socket();
                   1704:                packet_disconnect("socket: %.100s", strerror(saved));
                   1705:        }
                   1706:        /* Create the socket. */
                   1707:        sock = socket(AF_UNIX, SOCK_STREAM, 0);
                   1708:        if (sock < 0)
                   1709:                packet_disconnect("socket: %.100s", strerror(errno));
                   1710:
                   1711:        /* Bind it to the name. */
                   1712:        memset(&sunaddr, 0, sizeof(sunaddr));
                   1713:        sunaddr.sun_family = AF_UNIX;
                   1714:        strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
                   1715:                sizeof(sunaddr.sun_path));
                   1716:
                   1717:        if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
                   1718:                packet_disconnect("bind: %.100s", strerror(errno));
                   1719:
                   1720:        /* Restore the privileged uid. */
                   1721:        restore_uid();
                   1722:
                   1723:        /* Start listening on the socket. */
                   1724:        if (listen(sock, 5) < 0)
                   1725:                packet_disconnect("listen: %.100s", strerror(errno));
                   1726:
                   1727:        /* Allocate a channel for the authentication agent socket. */
                   1728:        newch = channel_allocate(SSH_CHANNEL_AUTH_SOCKET, sock,
                   1729:                                 xstrdup("auth socket"));
1.32      deraadt  1730:        strlcpy(channels[newch].path, channel_forwarded_auth_socket_name,
                   1731:            sizeof(channels[newch].path));
1.1       deraadt  1732: }
                   1733:
                   1734: /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
                   1735:
1.25      markus   1736: void
1.41    ! markus   1737: auth_input_open_request(int type, int plen)
1.1       deraadt  1738: {
1.25      markus   1739:        int remch, sock, newch;
                   1740:        char *dummyname;
1.41    ! markus   1741:
        !          1742:        packet_integrity_check(plen, 4, type);
1.25      markus   1743:
                   1744:        /* Read the remote channel number from the message. */
                   1745:        remch = packet_get_int();
                   1746:
1.27      markus   1747:        /*
                   1748:         * Get a connection to the local authentication agent (this may again
                   1749:         * get forwarded).
                   1750:         */
1.25      markus   1751:        sock = ssh_get_authentication_socket();
                   1752:
1.27      markus   1753:        /*
                   1754:         * If we could not connect the agent, send an error message back to
                   1755:         * the server. This should never happen unless the agent dies,
                   1756:         * because authentication forwarding is only enabled if we have an
                   1757:         * agent.
                   1758:         */
1.25      markus   1759:        if (sock < 0) {
                   1760:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   1761:                packet_put_int(remch);
                   1762:                packet_send();
                   1763:                return;
                   1764:        }
                   1765:        debug("Forwarding authentication connection.");
1.1       deraadt  1766:
1.27      markus   1767:        /*
                   1768:         * Dummy host name.  This will be freed when the channel is freed; it
                   1769:         * will still be valid in the packet_put_string below since the
                   1770:         * channel cannot yet be freed at that point.
                   1771:         */
1.25      markus   1772:        dummyname = xstrdup("authentication agent connection");
                   1773:
                   1774:        newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
                   1775:        channels[newch].remote_id = remch;
                   1776:
                   1777:        /* Send a confirmation to the remote host. */
                   1778:        packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1779:        packet_put_int(remch);
                   1780:        packet_put_int(newch);
                   1781:        packet_send();
1.1       deraadt  1782: }