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

1.1       deraadt     1: /*
                      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: */
                     17:
                     18: #include "includes.h"
1.2     ! provos     19: RCSID("$Id: channels.c,v 1.1 1999/09/26 20:53:34 deraadt Exp $");
1.1       deraadt    20:
                     21: #ifndef HAVE_GETHOSTNAME
                     22: #include <sys/utsname.h>
                     23: #endif
                     24: #include "ssh.h"
                     25: #include "packet.h"
                     26: #include "xmalloc.h"
                     27: #include "buffer.h"
                     28: #include "authfd.h"
                     29: #include "uidswap.h"
                     30:
                     31: /* Maximum number of fake X11 displays to try. */
                     32: #define MAX_DISPLAYS  1000
                     33:
                     34: /* Definitions for channel types. */
                     35: #define SSH_CHANNEL_FREE               0 /* This channel is free (unused). */
                     36: #define SSH_CHANNEL_X11_LISTENER       1 /* Listening for inet X11 conn. */
                     37: #define SSH_CHANNEL_PORT_LISTENER      2 /* Listening on a port. */
                     38: #define SSH_CHANNEL_OPENING            3 /* waiting for confirmation */
                     39: #define SSH_CHANNEL_OPEN               4 /* normal open two-way channel */
                     40: #define SSH_CHANNEL_CLOSED             5 /* waiting for close confirmation */
                     41: #define SSH_CHANNEL_AUTH_FD            6 /* authentication fd */
                     42: #define SSH_CHANNEL_AUTH_SOCKET                7 /* authentication socket */
                     43: #define SSH_CHANNEL_AUTH_SOCKET_FD     8 /* connection to auth socket */
                     44: #define SSH_CHANNEL_X11_OPEN           9 /* reading first X11 packet */
                     45: #define SSH_CHANNEL_INPUT_DRAINING     10 /* sending remaining data to conn */
                     46: #define SSH_CHANNEL_OUTPUT_DRAINING    11 /* sending remaining data to app */
                     47:
                     48: /* Data structure for channel data.  This is iniailized in channel_allocate
                     49:    and cleared in channel_free. */
                     50:
                     51: typedef struct
                     52: {
                     53:   int type;
                     54:   int sock;
                     55:   int remote_id;
                     56:   Buffer input;
                     57:   Buffer output;
                     58:   char path[200]; /* path for unix domain sockets, or host name for forwards */
                     59:   int host_port;  /* port to connect for forwards */
                     60:   int listening_port; /* port being listened for forwards */
                     61:   char *remote_name;
                     62: } Channel;
                     63:
                     64: /* Pointer to an array containing all allocated channels.  The array is
                     65:    dynamically extended as needed. */
                     66: static Channel *channels = NULL;
                     67:
                     68: /* Size of the channel array.  All slots of the array must always be
                     69:    initialized (at least the type field); unused slots are marked with
                     70:    type SSH_CHANNEL_FREE. */
                     71: static int channels_alloc = 0;
                     72:
                     73: /* Maximum file descriptor value used in any of the channels.  This is updated
                     74:    in channel_allocate. */
                     75: static int channel_max_fd_value = 0;
                     76:
                     77: /* These two variables are for authentication agent forwarding. */
                     78: static int channel_forwarded_auth_fd = -1;
                     79: static char *channel_forwarded_auth_socket_name = NULL;
                     80:
                     81: /* Saved X11 authentication protocol name. */
                     82: char *x11_saved_proto = NULL;
                     83:
                     84: /* Saved X11 authentication data.  This is the real data. */
                     85: char *x11_saved_data = NULL;
                     86: unsigned int x11_saved_data_len = 0;
                     87:
                     88: /* Fake X11 authentication data.  This is what the server will be sending
                     89:    us; we should replace any occurrences of this by the real data. */
                     90: char *x11_fake_data = NULL;
                     91: unsigned int x11_fake_data_len;
                     92:
                     93: /* Data structure for storing which hosts are permitted for forward requests.
                     94:    The local sides of any remote forwards are stored in this array to prevent
                     95:    a corrupt remote server from accessing arbitrary TCP/IP ports on our
                     96:    local network (which might be behind a firewall). */
                     97: typedef struct
                     98: {
                     99:   char *host;          /* Host name. */
                    100:   int port;            /* Port number. */
                    101: } ForwardPermission;
                    102:
                    103: /* List of all permitted host/port pairs to connect. */
                    104: static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
                    105: /* Number of permitted host/port pairs in the array. */
                    106: static int num_permitted_opens = 0;
                    107: /* If this is true, all opens are permitted.  This is the case on the
                    108:    server on which we have to trust the client anyway, and the user could
                    109:    do anything after logging in anyway. */
                    110: static int all_opens_permitted = 0;
                    111:
                    112: /* This is set to true if both sides support SSH_PROTOFLAG_HOST_IN_FWD_OPEN. */
                    113: static int have_hostname_in_open = 0;
                    114:
                    115: /* Sets specific protocol options. */
                    116:
                    117: void channel_set_options(int hostname_in_open)
                    118: {
                    119:   have_hostname_in_open = hostname_in_open;
                    120: }
                    121:
                    122: /* Permits opening to any host/port in SSH_MSG_PORT_OPEN.  This is usually
                    123:    called by the server, because the user could connect to any port anyway,
                    124:    and the server has no way to know but to trust the client anyway. */
                    125:
                    126: void channel_permit_all_opens()
                    127: {
                    128:   all_opens_permitted = 1;
                    129: }
                    130:
                    131: /* Allocate a new channel object and set its type and socket.
                    132:    This will cause remote_name to be freed. */
                    133:
                    134: int channel_allocate(int type, int sock, char *remote_name)
                    135: {
                    136:   int i, old_channels;
                    137:
                    138:   /* Update the maximum file descriptor value. */
                    139:   if (sock > channel_max_fd_value)
                    140:     channel_max_fd_value = sock;
                    141:
                    142:   /* Do initial allocation if this is the first call. */
                    143:   if (channels_alloc == 0)
                    144:     {
                    145:       channels_alloc = 10;
                    146:       channels = xmalloc(channels_alloc * sizeof(Channel));
                    147:       for (i = 0; i < channels_alloc; i++)
                    148:        channels[i].type = SSH_CHANNEL_FREE;
                    149:
                    150:       /* Kludge: arrange a call to channel_stop_listening if we terminate
                    151:         with fatal(). */
                    152:       fatal_add_cleanup((void (*)(void *))channel_stop_listening, NULL);
                    153:     }
                    154:
                    155:   /* Try to find a free slot where to put the new channel. */
                    156:   for (i = 0; i < channels_alloc; i++)
                    157:     if (channels[i].type == SSH_CHANNEL_FREE)
                    158:       {
                    159:        /* Found a free slot.  Initialize the fields and return its number. */
                    160:        buffer_init(&channels[i].input);
                    161:        buffer_init(&channels[i].output);
                    162:        channels[i].type = type;
                    163:        channels[i].sock = sock;
                    164:        channels[i].remote_id = -1;
                    165:        channels[i].remote_name = remote_name;
                    166:        return i;
                    167:       }
                    168:
                    169:   /* There are no free slots.  Must expand the array. */
                    170:   old_channels = channels_alloc;
                    171:   channels_alloc += 10;
                    172:   channels = xrealloc(channels, channels_alloc * sizeof(Channel));
                    173:   for (i = old_channels; i < channels_alloc; i++)
                    174:     channels[i].type = SSH_CHANNEL_FREE;
                    175:
                    176:   /* We know that the next one after the old maximum channel number is now
                    177:      available.  Initialize and return its number. */
                    178:   buffer_init(&channels[old_channels].input);
                    179:   buffer_init(&channels[old_channels].output);
                    180:   channels[old_channels].type = type;
                    181:   channels[old_channels].sock = sock;
                    182:   channels[old_channels].remote_id = -1;
                    183:   channels[old_channels].remote_name = remote_name;
                    184:   return old_channels;
                    185: }
                    186:
                    187: /* Free the channel and close its socket. */
                    188:
                    189: void channel_free(int channel)
                    190: {
                    191:   assert(channel >= 0 && channel < channels_alloc &&
                    192:         channels[channel].type != SSH_CHANNEL_FREE);
                    193:   shutdown(channels[channel].sock, 2);
                    194:   close(channels[channel].sock);
                    195:   buffer_free(&channels[channel].input);
                    196:   buffer_free(&channels[channel].output);
                    197:   channels[channel].type = SSH_CHANNEL_FREE;
                    198:   if (channels[channel].remote_name)
                    199:     {
                    200:       xfree(channels[channel].remote_name);
                    201:       channels[channel].remote_name = NULL;
                    202:     }
                    203: }
                    204:
                    205: /* This is called just before select() to add any bits relevant to
                    206:    channels in the select bitmasks. */
                    207:
                    208: void channel_prepare_select(fd_set *readset, fd_set *writeset)
                    209: {
                    210:   int i;
                    211:   Channel *ch;
                    212:   unsigned char *ucp;
                    213:   unsigned int proto_len, data_len;
                    214:
                    215:   for (i = 0; i < channels_alloc; i++)
                    216:     {
                    217:       ch = &channels[i];
                    218:     redo:
                    219:       switch (ch->type)
                    220:        {
                    221:        case SSH_CHANNEL_X11_LISTENER:
                    222:        case SSH_CHANNEL_PORT_LISTENER:
                    223:        case SSH_CHANNEL_AUTH_SOCKET:
                    224:        case SSH_CHANNEL_AUTH_SOCKET_FD:
                    225:        case SSH_CHANNEL_AUTH_FD:
                    226:          FD_SET(ch->sock, readset);
                    227:          break;
                    228:
                    229:        case SSH_CHANNEL_OPEN:
                    230:          if (buffer_len(&ch->input) < 32768)
                    231:            FD_SET(ch->sock, readset);
                    232:          if (buffer_len(&ch->output) > 0)
                    233:            FD_SET(ch->sock, writeset);
                    234:          break;
                    235:
                    236:        case SSH_CHANNEL_INPUT_DRAINING:
                    237:          if (buffer_len(&ch->input) == 0)
                    238:            {
                    239:              packet_start(SSH_MSG_CHANNEL_CLOSE);
                    240:              packet_put_int(ch->remote_id);
                    241:              packet_send();
                    242:              ch->type = SSH_CHANNEL_CLOSED;
                    243:              debug("Closing channel %d after input drain.", i);
                    244:              break;
                    245:            }
                    246:          break;
                    247:
                    248:        case SSH_CHANNEL_OUTPUT_DRAINING:
                    249:          if (buffer_len(&ch->output) == 0)
                    250:            {
                    251:              /* debug("Freeing channel %d after output drain.", i); */
                    252:              channel_free(i);
                    253:              break;
                    254:            }
                    255:          FD_SET(ch->sock, writeset);
                    256:          break;
                    257:
                    258:        case SSH_CHANNEL_X11_OPEN:
                    259:          /* This is a special state for X11 authentication spoofing.  An
                    260:             opened X11 connection (when authentication spoofing is being
                    261:             done) remains in this state until the first packet has been
                    262:             completely read.  The authentication data in that packet is
                    263:             then substituted by the real data if it matches the fake data,
                    264:             and the channel is put into normal mode. */
                    265:
                    266:          /* Check if the fixed size part of the packet is in buffer. */
                    267:          if (buffer_len(&ch->output) < 12)
                    268:            break;
                    269:
                    270:          /* Parse the lengths of variable-length fields. */
                    271:          ucp = (unsigned char *)buffer_ptr(&ch->output);
                    272:          if (ucp[0] == 0x42)
                    273:            { /* Byte order MSB first. */
                    274:              proto_len = 256 * ucp[6] + ucp[7];
                    275:              data_len = 256 * ucp[8] + ucp[9];
                    276:            }
                    277:          else
                    278:            if (ucp[0] == 0x6c)
                    279:              { /* Byte order LSB first. */
                    280:                proto_len = ucp[6] + 256 * ucp[7];
                    281:                data_len = ucp[8] + 256 * ucp[9];
                    282:              }
                    283:            else
                    284:              {
                    285:                debug("Initial X11 packet contains bad byte order byte: 0x%x",
                    286:                      ucp[0]);
                    287:                ch->type = SSH_CHANNEL_OPEN;
                    288:                goto reject;
                    289:              }
                    290:
                    291:          /* Check if the whole packet is in buffer. */
                    292:          if (buffer_len(&ch->output) <
                    293:              12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
                    294:            break;
                    295:
                    296:          /* Check if authentication protocol matches. */
                    297:          if (proto_len != strlen(x11_saved_proto) ||
                    298:              memcmp(ucp + 12, x11_saved_proto, proto_len) != 0)
                    299:            {
                    300:              debug("X11 connection uses different authentication protocol.");
                    301:              ch->type = SSH_CHANNEL_OPEN;
                    302:              goto reject;
                    303:            }
                    304:
                    305:          /* Check if authentication data matches our fake data. */
                    306:          if (data_len != x11_fake_data_len ||
                    307:              memcmp(ucp + 12 + ((proto_len + 3) & ~3),
                    308:                     x11_fake_data, x11_fake_data_len) != 0)
                    309:            {
                    310:              debug("X11 auth data does not match fake data.");
                    311:              ch->type = SSH_CHANNEL_OPEN;
                    312:              goto reject;
                    313:            }
                    314:
                    315:          /* Received authentication protocol and data match our fake data.
                    316:             Substitute the fake data with real data. */
                    317:          assert(x11_fake_data_len == x11_saved_data_len);
                    318:          memcpy(ucp + 12 + ((proto_len + 3) & ~3),
                    319:                 x11_saved_data, x11_saved_data_len);
                    320:
                    321:          /* Start normal processing for the channel. */
                    322:          ch->type = SSH_CHANNEL_OPEN;
                    323:          goto redo;
                    324:
                    325:        reject:
                    326:          /* We have received an X11 connection that has bad authentication
                    327:             information. */
                    328:          log("X11 connection rejected because of wrong authentication.\r\n");
                    329:          buffer_clear(&ch->input);
                    330:          buffer_clear(&ch->output);
                    331:          close(ch->sock);
                    332:          ch->sock = -1;
                    333:          ch->type = SSH_CHANNEL_CLOSED;
                    334:          packet_start(SSH_MSG_CHANNEL_CLOSE);
                    335:          packet_put_int(ch->remote_id);
                    336:          packet_send();
                    337:          break;
                    338:
                    339:        case SSH_CHANNEL_FREE:
                    340:        default:
                    341:          continue;
                    342:        }
                    343:     }
                    344: }
                    345:
                    346: /* After select, perform any appropriate operations for channels which
                    347:    have events pending. */
                    348:
                    349: void channel_after_select(fd_set *readset, fd_set *writeset)
                    350: {
                    351:   struct sockaddr addr;
                    352:   int addrlen, newsock, i, newch, len, port;
                    353:   Channel *ch;
                    354:   char buf[16384], *remote_hostname;
                    355:
                    356:   /* Loop over all channels... */
                    357:   for (i = 0; i < channels_alloc; i++)
                    358:     {
                    359:       ch = &channels[i];
                    360:       switch (ch->type)
                    361:        {
                    362:        case SSH_CHANNEL_X11_LISTENER:
                    363:          /* This is our fake X11 server socket. */
                    364:          if (FD_ISSET(ch->sock, readset))
                    365:            {
                    366:              debug("X11 connection requested.");
                    367:              addrlen = sizeof(addr);
                    368:              newsock = accept(ch->sock, &addr, &addrlen);
                    369:              if (newsock < 0)
                    370:                {
                    371:                  error("accept: %.100s", strerror(errno));
                    372:                  break;
                    373:                }
                    374:              remote_hostname = get_remote_hostname(newsock);
                    375:              sprintf(buf, "X11 connection from %.200s port %d",
                    376:                      remote_hostname, get_peer_port(newsock));
                    377:              xfree(remote_hostname);
                    378:              newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
                    379:                                       xstrdup(buf));
                    380:              packet_start(SSH_SMSG_X11_OPEN);
                    381:              packet_put_int(newch);
                    382:              if (have_hostname_in_open)
                    383:                packet_put_string(buf, strlen(buf));
                    384:              packet_send();
                    385:            }
                    386:          break;
                    387:
                    388:        case SSH_CHANNEL_PORT_LISTENER:
                    389:          /* This socket is listening for connections to a forwarded TCP/IP
                    390:             port. */
                    391:          if (FD_ISSET(ch->sock, readset))
                    392:            {
                    393:              debug("Connection to port %d forwarding to %.100s:%d requested.",
                    394:                    ch->listening_port, ch->path, ch->host_port);
                    395:              addrlen = sizeof(addr);
                    396:              newsock = accept(ch->sock, &addr, &addrlen);
                    397:              if (newsock < 0)
                    398:                {
                    399:                  error("accept: %.100s", strerror(errno));
                    400:                  break;
                    401:                }
                    402:              remote_hostname = get_remote_hostname(newsock);
                    403:              sprintf(buf, "port %d, connection from %.200s port %d",
                    404:                      ch->listening_port, remote_hostname,
                    405:                      get_peer_port(newsock));
                    406:              xfree(remote_hostname);
                    407:              newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
                    408:                                       xstrdup(buf));
                    409:              packet_start(SSH_MSG_PORT_OPEN);
                    410:              packet_put_int(newch);
                    411:              packet_put_string(ch->path, strlen(ch->path));
                    412:              packet_put_int(ch->host_port);
                    413:              if (have_hostname_in_open)
                    414:                packet_put_string(buf, strlen(buf));
                    415:              packet_send();
                    416:            }
                    417:          break;
                    418:
                    419:        case SSH_CHANNEL_AUTH_FD:
                    420:          /* This is the authentication agent file descriptor.  It is used to
                    421:             obtain the real connection to the agent. */
                    422:        case SSH_CHANNEL_AUTH_SOCKET_FD:
                    423:          /* This is the temporary connection obtained by connecting the
                    424:             authentication agent socket. */
                    425:          if (FD_ISSET(ch->sock, readset))
                    426:            {
                    427:              len = recv(ch->sock, buf, sizeof(buf), 0);
                    428:              if (len <= 0)
                    429:                {
                    430:                  channel_free(i);
                    431:                  break;
                    432:                }
                    433:              if (len != 3 || (unsigned char)buf[0] != SSH_AUTHFD_CONNECT)
                    434:                break; /* Ignore any messages of wrong length or type. */
                    435:              port = 256 * (unsigned char)buf[1] + (unsigned char)buf[2];
                    436:              packet_start(SSH_SMSG_AGENT_OPEN);
                    437:              packet_put_int(port);
                    438:              packet_send();
                    439:            }
                    440:          break;
                    441:
                    442:        case SSH_CHANNEL_AUTH_SOCKET:
                    443:          /* This is the authentication agent socket listening for connections
                    444:             from clients. */
                    445:          if (FD_ISSET(ch->sock, readset))
                    446:            {
                    447:              len = sizeof(addr);
                    448:              newsock = accept(ch->sock, &addr, &len);
                    449:              if (newsock < 0)
                    450:                error("Accept from authentication socket failed");
                    451:              (void)channel_allocate(SSH_CHANNEL_AUTH_SOCKET_FD, newsock,
                    452:                                     xstrdup("accepted auth socket"));
                    453:            }
                    454:          break;
                    455:
                    456:        case SSH_CHANNEL_OPEN:
                    457:          /* This is an open two-way communication channel.  It is not of
                    458:             interest to us at this point what kind of data is being
                    459:             transmitted. */
                    460:          /* Read available incoming data and append it to buffer. */
                    461:          if (FD_ISSET(ch->sock, readset))
                    462:            {
                    463:              len = read(ch->sock, buf, sizeof(buf));
                    464:              if (len <= 0)
                    465:                {
                    466:                  buffer_consume(&ch->output, buffer_len(&ch->output));
                    467:                  ch->type = SSH_CHANNEL_INPUT_DRAINING;
                    468:                  debug("Channel %d status set to input draining.", i);
                    469:                  break;
                    470:                }
                    471:              buffer_append(&ch->input, buf, len);
                    472:            }
                    473:          /* Send buffered output data to the socket. */
                    474:          if (FD_ISSET(ch->sock, writeset) && buffer_len(&ch->output) > 0)
                    475:            {
                    476:              len = write(ch->sock, buffer_ptr(&ch->output),
                    477:                          buffer_len(&ch->output));
                    478:              if (len <= 0)
                    479:                {
                    480:                  buffer_consume(&ch->output, buffer_len(&ch->output));
                    481:                  debug("Channel %d status set to input draining.", i);
                    482:                  ch->type = SSH_CHANNEL_INPUT_DRAINING;
                    483:                  break;
                    484:                }
                    485:              buffer_consume(&ch->output, len);
                    486:            }
                    487:          break;
                    488:
                    489:        case SSH_CHANNEL_OUTPUT_DRAINING:
                    490:          /* Send buffered output data to the socket. */
                    491:          if (FD_ISSET(ch->sock, writeset) && buffer_len(&ch->output) > 0)
                    492:            {
                    493:              len = write(ch->sock, buffer_ptr(&ch->output),
                    494:                          buffer_len(&ch->output));
                    495:              if (len <= 0)
                    496:                buffer_consume(&ch->output, buffer_len(&ch->output));
                    497:              else
                    498:                buffer_consume(&ch->output, len);
                    499:            }
                    500:          break;
                    501:
                    502:        case SSH_CHANNEL_X11_OPEN:
                    503:        case SSH_CHANNEL_FREE:
                    504:        default:
                    505:          continue;
                    506:        }
                    507:     }
                    508: }
                    509:
                    510: /* If there is data to send to the connection, send some of it now. */
                    511:
                    512: void channel_output_poll()
                    513: {
                    514:   int len, i;
                    515:   Channel *ch;
                    516:
                    517:   for (i = 0; i < channels_alloc; i++)
                    518:     {
                    519:       ch = &channels[i];
                    520:       /* We are only interested in channels that can have buffered incoming
                    521:         data. */
                    522:       if (ch->type != SSH_CHANNEL_OPEN &&
                    523:          ch->type != SSH_CHANNEL_INPUT_DRAINING)
                    524:        continue;
                    525:
                    526:       /* Get the amount of buffered data for this channel. */
                    527:       len = buffer_len(&ch->input);
                    528:       if (len > 0)
                    529:        {
                    530:          /* Send some data for the other side over the secure connection. */
                    531:          if (packet_is_interactive())
                    532:            {
                    533:              if (len > 1024)
                    534:                len = 512;
                    535:            }
                    536:          else
                    537:            {
                    538:              if (len > 16384)
                    539:                len = 16384;  /* Keep the packets at reasonable size. */
                    540:            }
                    541:          packet_start(SSH_MSG_CHANNEL_DATA);
                    542:          packet_put_int(ch->remote_id);
                    543:          packet_put_string(buffer_ptr(&ch->input), len);
                    544:          packet_send();
                    545:          buffer_consume(&ch->input, len);
                    546:        }
                    547:     }
                    548: }
                    549:
                    550: /* This is called when a packet of type CHANNEL_DATA has just been received.
                    551:    The message type has already been consumed, but channel number and data
                    552:    is still there. */
                    553:
                    554: void channel_input_data(int payload_len)
                    555: {
                    556:   int channel;
                    557:   char *data;
                    558:   unsigned int data_len;
                    559:
                    560:   /* Get the channel number and verify it. */
                    561:   channel = packet_get_int();
                    562:   if (channel < 0 || channel >= channels_alloc ||
                    563:       channels[channel].type == SSH_CHANNEL_FREE)
                    564:     packet_disconnect("Received data for nonexistent channel %d.", channel);
                    565:
                    566:   /* Ignore any data for non-open channels (might happen on close) */
                    567:   if (channels[channel].type != SSH_CHANNEL_OPEN &&
                    568:       channels[channel].type != SSH_CHANNEL_X11_OPEN)
                    569:     return;
                    570:
                    571:   /* Get the data. */
                    572:   data = packet_get_string(&data_len);
                    573:   packet_integrity_check(payload_len, 4 + 4+data_len, SSH_MSG_CHANNEL_DATA);
                    574:   buffer_append(&channels[channel].output, data, data_len);
                    575:   xfree(data);
                    576: }
                    577:
                    578: /* Returns true if no channel has too much buffered data, and false if
                    579:    one or more channel is overfull. */
                    580:
                    581: int channel_not_very_much_buffered_data()
                    582: {
                    583:   unsigned int i;
                    584:   Channel *ch;
                    585:
                    586:   for (i = 0; i < channels_alloc; i++)
                    587:     {
                    588:       ch = &channels[i];
                    589:       switch (channels[i].type)
                    590:        {
                    591:        case SSH_CHANNEL_X11_LISTENER:
                    592:        case SSH_CHANNEL_PORT_LISTENER:
                    593:        case SSH_CHANNEL_AUTH_SOCKET:
                    594:        case SSH_CHANNEL_AUTH_SOCKET_FD:
                    595:        case SSH_CHANNEL_AUTH_FD:
                    596:          continue;
                    597:        case SSH_CHANNEL_OPEN:
                    598:          if (buffer_len(&ch->input) > 32768)
                    599:            return 0;
                    600:          if (buffer_len(&ch->output) > 32768)
                    601:            return 0;
                    602:          continue;
                    603:        case SSH_CHANNEL_INPUT_DRAINING:
                    604:        case SSH_CHANNEL_OUTPUT_DRAINING:
                    605:        case SSH_CHANNEL_X11_OPEN:
                    606:        case SSH_CHANNEL_FREE:
                    607:        default:
                    608:          continue;
                    609:        }
                    610:     }
                    611:   return 1;
                    612: }
                    613:
                    614: /* This is called after receiving CHANNEL_CLOSE. */
                    615:
                    616: void channel_input_close()
                    617: {
                    618:   int channel;
                    619:
                    620:   /* Get the channel number and verify it. */
                    621:   channel = packet_get_int();
                    622:   if (channel < 0 || channel >= channels_alloc ||
                    623:       channels[channel].type == SSH_CHANNEL_FREE)
                    624:     packet_disconnect("Received data for nonexistent channel %d.", channel);
                    625:
                    626:   /* Send a confirmation that we have closed the channel and no more data is
                    627:      coming for it. */
                    628:   packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
                    629:   packet_put_int(channels[channel].remote_id);
                    630:   packet_send();
                    631:
                    632:   /* If the channel is in closed state, we have sent a close request, and
                    633:      the other side will eventually respond with a confirmation.  Thus,
                    634:      we cannot free the channel here, because then there would be no-one to
                    635:      receive the confirmation.  The channel gets freed when the confirmation
                    636:      arrives. */
                    637:   if (channels[channel].type != SSH_CHANNEL_CLOSED)
                    638:     {
                    639:       /* Not a closed channel - mark it as draining, which will cause it to
                    640:         be freed later. */
                    641:       buffer_consume(&channels[channel].input,
                    642:                     buffer_len(&channels[channel].input));
                    643:       channels[channel].type = SSH_CHANNEL_OUTPUT_DRAINING;
                    644:       /* debug("Setting status to output draining; output len = %d",
                    645:         buffer_len(&channels[channel].output)); */
                    646:     }
                    647: }
                    648:
                    649: /* This is called after receiving CHANNEL_CLOSE_CONFIRMATION. */
                    650:
                    651: void channel_input_close_confirmation()
                    652: {
                    653:   int channel;
                    654:
                    655:   /* Get the channel number and verify it. */
                    656:   channel = packet_get_int();
                    657:   if (channel < 0 || channel >= channels_alloc)
                    658:     packet_disconnect("Received close confirmation for out-of-range channel %d.",
                    659:                      channel);
                    660:   if (channels[channel].type != SSH_CHANNEL_CLOSED)
                    661:     packet_disconnect("Received close confirmation for non-closed channel %d (type %d).",
                    662:                      channel, channels[channel].type);
                    663:
                    664:   /* Free the channel. */
                    665:   channel_free(channel);
                    666: }
                    667:
                    668: /* This is called after receiving CHANNEL_OPEN_CONFIRMATION. */
                    669:
                    670: void channel_input_open_confirmation()
                    671: {
                    672:   int channel, remote_channel;
                    673:
                    674:   /* Get the channel number and verify it. */
                    675:   channel = packet_get_int();
                    676:   if (channel < 0 || channel >= channels_alloc ||
                    677:       channels[channel].type != SSH_CHANNEL_OPENING)
                    678:     packet_disconnect("Received open confirmation for non-opening channel %d.",
                    679:                      channel);
                    680:
                    681:   /* Get remote side's id for this channel. */
                    682:   remote_channel = packet_get_int();
                    683:
                    684:   /* Record the remote channel number and mark that the channel is now open. */
                    685:   channels[channel].remote_id = remote_channel;
                    686:   channels[channel].type = SSH_CHANNEL_OPEN;
                    687: }
                    688:
                    689: /* This is called after receiving CHANNEL_OPEN_FAILURE from the other side. */
                    690:
                    691: void channel_input_open_failure()
                    692: {
                    693:   int channel;
                    694:
                    695:   /* Get the channel number and verify it. */
                    696:   channel = packet_get_int();
                    697:   if (channel < 0 || channel >= channels_alloc ||
                    698:       channels[channel].type != SSH_CHANNEL_OPENING)
                    699:     packet_disconnect("Received open failure for non-opening channel %d.",
                    700:                      channel);
                    701:
                    702:   /* Free the channel.  This will also close the socket. */
                    703:   channel_free(channel);
                    704: }
                    705:
                    706: /* Stops listening for channels, and removes any unix domain sockets that
                    707:    we might have. */
                    708:
                    709: void channel_stop_listening()
                    710: {
                    711:   int i;
                    712:   for (i = 0; i < channels_alloc; i++)
                    713:     {
                    714:       switch (channels[i].type)
                    715:        {
                    716:        case SSH_CHANNEL_AUTH_SOCKET:
                    717:          close(channels[i].sock);
                    718:          remove(channels[i].path);
                    719:          channel_free(i);
                    720:          break;
                    721:        case SSH_CHANNEL_PORT_LISTENER:
                    722:        case SSH_CHANNEL_X11_LISTENER:
                    723:          close(channels[i].sock);
                    724:          channel_free(i);
                    725:          break;
                    726:        default:
                    727:          break;
                    728:        }
                    729:     }
                    730: }
                    731:
                    732: /* Closes the sockets of all channels.  This is used to close extra file
                    733:    descriptors after a fork. */
                    734:
                    735: void channel_close_all()
                    736: {
                    737:   int i;
                    738:   for (i = 0; i < channels_alloc; i++)
                    739:     {
                    740:       if (channels[i].type != SSH_CHANNEL_FREE)
                    741:        close(channels[i].sock);
                    742:     }
                    743: }
                    744:
                    745: /* Returns the maximum file descriptor number used by the channels. */
                    746:
                    747: int channel_max_fd()
                    748: {
                    749:   return channel_max_fd_value;
                    750: }
                    751:
                    752: /* Returns true if any channel is still open. */
                    753:
                    754: int channel_still_open()
                    755: {
                    756:   unsigned int i;
                    757:   for (i = 0; i < channels_alloc; i++)
                    758:     switch (channels[i].type)
                    759:       {
                    760:       case SSH_CHANNEL_FREE:
                    761:       case SSH_CHANNEL_X11_LISTENER:
                    762:       case SSH_CHANNEL_PORT_LISTENER:
                    763:       case SSH_CHANNEL_CLOSED:
                    764:       case SSH_CHANNEL_AUTH_FD:
                    765:       case SSH_CHANNEL_AUTH_SOCKET:
                    766:       case SSH_CHANNEL_AUTH_SOCKET_FD:
                    767:        continue;
                    768:       case SSH_CHANNEL_OPENING:
                    769:       case SSH_CHANNEL_OPEN:
                    770:       case SSH_CHANNEL_X11_OPEN:
                    771:       case SSH_CHANNEL_INPUT_DRAINING:
                    772:       case SSH_CHANNEL_OUTPUT_DRAINING:
                    773:        return 1;
                    774:       default:
                    775:        fatal("channel_still_open: bad channel type %d", channels[i].type);
                    776:        /*NOTREACHED*/
                    777:       }
                    778:   return 0;
                    779: }
                    780:
                    781: /* Returns a message describing the currently open forwarded
                    782:    connections, suitable for sending to the client.  The message
                    783:    contains crlf pairs for newlines. */
                    784:
                    785: char *channel_open_message()
                    786: {
                    787:   Buffer buffer;
                    788:   int i;
                    789:   char buf[512], *cp;
                    790:
                    791:   buffer_init(&buffer);
                    792:   sprintf(buf, "The following connections are open:\r\n");
                    793:   buffer_append(&buffer, buf, strlen(buf));
                    794:   for (i = 0; i < channels_alloc; i++)
                    795:     switch (channels[i].type)
                    796:       {
                    797:       case SSH_CHANNEL_FREE:
                    798:       case SSH_CHANNEL_X11_LISTENER:
                    799:       case SSH_CHANNEL_PORT_LISTENER:
                    800:       case SSH_CHANNEL_CLOSED:
                    801:       case SSH_CHANNEL_AUTH_FD:
                    802:       case SSH_CHANNEL_AUTH_SOCKET:
                    803:       case SSH_CHANNEL_AUTH_SOCKET_FD:
                    804:        continue;
                    805:       case SSH_CHANNEL_OPENING:
                    806:       case SSH_CHANNEL_OPEN:
                    807:       case SSH_CHANNEL_X11_OPEN:
                    808:       case SSH_CHANNEL_INPUT_DRAINING:
                    809:       case SSH_CHANNEL_OUTPUT_DRAINING:
                    810:        sprintf(buf, "  %.300s\r\n", channels[i].remote_name);
                    811:        buffer_append(&buffer, buf, strlen(buf));
                    812:        continue;
                    813:       default:
                    814:        fatal("channel_still_open: bad channel type %d", channels[i].type);
                    815:        /*NOTREACHED*/
                    816:       }
                    817:   buffer_append(&buffer, "\0", 1);
                    818:   cp = xstrdup(buffer_ptr(&buffer));
                    819:   buffer_free(&buffer);
                    820:   return cp;
                    821: }
                    822:
                    823: /* Initiate forwarding of connections to local port "port" through the secure
                    824:    channel to host:port from remote side. */
                    825:
                    826: void channel_request_local_forwarding(int port, const char *host,
                    827:                                      int host_port)
                    828: {
                    829:   int ch, sock;
                    830:   struct sockaddr_in sin;
                    831:
                    832:   if (strlen(host) > sizeof(channels[0].path) - 1)
                    833:     packet_disconnect("Forward host name too long.");
                    834:
                    835:   /* Create a port to listen for the host. */
                    836:   sock = socket(AF_INET, SOCK_STREAM, 0);
                    837:   if (sock < 0)
                    838:     packet_disconnect("socket: %.100s", strerror(errno));
                    839:
                    840:   /* Initialize socket address. */
                    841:   memset(&sin, 0, sizeof(sin));
                    842:   sin.sin_family = AF_INET;
                    843:   sin.sin_addr.s_addr = INADDR_ANY;
                    844:   sin.sin_port = htons(port);
                    845:
                    846:   /* Bind the socket to the address. */
                    847:   if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
                    848:     packet_disconnect("bind: %.100s", strerror(errno));
                    849:
                    850:   /* Start listening for connections on the socket. */
                    851:   if (listen(sock, 5) < 0)
                    852:     packet_disconnect("listen: %.100s", strerror(errno));
                    853:
                    854:   /* Allocate a channel number for the socket. */
                    855:   ch = channel_allocate(SSH_CHANNEL_PORT_LISTENER, sock,
                    856:                        xstrdup("port listener"));
                    857:   strcpy(channels[ch].path, host); /* note: host name stored here */
                    858:   channels[ch].host_port = host_port; /* port on host to connect to */
                    859:   channels[ch].listening_port = port; /* port being listened */
                    860: }
                    861:
                    862: /* Initiate forwarding of connections to port "port" on remote host through
                    863:    the secure channel to host:port from local side. */
                    864:
                    865: void channel_request_remote_forwarding(int port, const char *host,
                    866:                                       int remote_port)
                    867: {
                    868:   int payload_len;
                    869:   /* Record locally that connection to this host/port is permitted. */
                    870:   if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
                    871:     fatal("channel_request_remote_forwarding: too many forwards");
                    872:   permitted_opens[num_permitted_opens].host = xstrdup(host);
                    873:   permitted_opens[num_permitted_opens].port = remote_port;
                    874:   num_permitted_opens++;
                    875:
                    876:   /* Send the forward request to the remote side. */
                    877:   packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
                    878:   packet_put_int(port);
                    879:   packet_put_string(host, strlen(host));
                    880:   packet_put_int(remote_port);
                    881:   packet_send();
                    882:   packet_write_wait();
                    883:
                    884:   /* Wait for response from the remote side.  It will send a disconnect
                    885:      message on failure, and we will never see it here. */
                    886:   packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
                    887: }
                    888:
                    889: /* This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
                    890:    listening for the port, and sends back a success reply (or disconnect
                    891:    message if there was an error).  This never returns if there was an
                    892:    error. */
                    893:
                    894: void channel_input_port_forward_request(int is_root)
                    895: {
                    896:   int port, host_port;
                    897:   char *hostname;
                    898:
                    899:   /* Get arguments from the packet. */
                    900:   port = packet_get_int();
                    901:   hostname = packet_get_string(NULL);
                    902:   host_port = packet_get_int();
                    903:
                    904:   /* Port numbers are 16 bit quantities. */
                    905:   if ((port & 0xffff) != port)
                    906:     packet_disconnect("Requested forwarding of nonexistent port %d.", port);
                    907:
                    908:
                    909:   /* Check that an unprivileged user is not trying to forward a privileged
                    910:      port. */
                    911:   if (port < 1024 && !is_root)
                    912:     packet_disconnect("Requested forwarding of port %d but user is not root.",
                    913:                      port);
                    914:
                    915:   /* Initiate forwarding. */
                    916:   channel_request_local_forwarding(port, hostname, host_port);
                    917:
                    918:   /* Free the argument string. */
                    919:   xfree(hostname);
                    920: }
                    921:
                    922: /* This is called after receiving PORT_OPEN message.  This attempts to connect
                    923:    to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION or
                    924:    CHANNEL_OPEN_FAILURE. */
                    925:
                    926: void channel_input_port_open(int payload_len)
                    927: {
                    928:   int remote_channel, sock, newch, host_port, i;
                    929:   struct sockaddr_in sin;
                    930:   char *host, *originator_string;
                    931:   struct hostent *hp;
                    932:   int host_len, originator_len;
                    933:
                    934:   /* Get remote channel number. */
                    935:   remote_channel = packet_get_int();
                    936:
                    937:   /* Get host name to connect to. */
                    938:   host = packet_get_string(&host_len);
                    939:
                    940:   /* Get port to connect to. */
                    941:   host_port = packet_get_int();
                    942:
                    943:   /* Get remote originator name. */
                    944:   if (have_hostname_in_open)
                    945:     originator_string = packet_get_string(&originator_len);
                    946:   else
                    947:     originator_string = xstrdup("unknown (remote did not supply name)");
                    948:
                    949:   packet_integrity_check(payload_len,
                    950:                         4 + 4 + host_len + 4 + 4 + originator_len,
                    951:                         SSH_MSG_PORT_OPEN);
                    952:
                    953:   /* Check if opening that port is permitted. */
                    954:   if (!all_opens_permitted)
                    955:     {
                    956:       /* Go trough all permitted ports. */
                    957:       for (i = 0; i < num_permitted_opens; i++)
                    958:        if (permitted_opens[i].port == host_port &&
                    959:            strcmp(permitted_opens[i].host, host) == 0)
                    960:          break;
                    961:
                    962:       /* Check if we found the requested port among those permitted. */
                    963:       if (i >= num_permitted_opens)
                    964:        {
                    965:          /* The port is not permitted. */
                    966:          log("Received request to connect to %.100s:%d, but the request was denied.",
                    967:              host, host_port);
                    968:          packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                    969:          packet_put_int(remote_channel);
                    970:          packet_send();
                    971:        }
                    972:     }
                    973:
                    974:   memset(&sin, 0, sizeof(sin));
                    975: #ifdef BROKEN_INET_ADDR
                    976:   sin.sin_addr.s_addr = inet_network(host);
                    977: #else /* BROKEN_INET_ADDR */
                    978:   sin.sin_addr.s_addr = inet_addr(host);
                    979: #endif /* BROKEN_INET_ADDR */
                    980:   if ((sin.sin_addr.s_addr & 0xffffffff) != 0xffffffff)
                    981:     {
                    982:       /* It was a valid numeric host address. */
                    983:       sin.sin_family = AF_INET;
                    984:     }
                    985:   else
                    986:     {
                    987:       /* Look up the host address from the name servers. */
                    988:       hp = gethostbyname(host);
                    989:       if (!hp)
                    990:        {
                    991:          error("%.100s: unknown host.", host);
                    992:          goto fail;
                    993:        }
                    994:       if (!hp->h_addr_list[0])
                    995:        {
                    996:          error("%.100s: host has no IP address.", host);
                    997:          goto fail;
                    998:        }
                    999:       sin.sin_family = hp->h_addrtype;
                   1000:       memcpy(&sin.sin_addr, hp->h_addr_list[0],
                   1001:             sizeof(sin.sin_addr));
                   1002:     }
                   1003:   sin.sin_port = htons(host_port);
                   1004:
                   1005:   /* Create the socket. */
                   1006:   sock = socket(sin.sin_family, SOCK_STREAM, 0);
                   1007:   if (sock < 0)
                   1008:     {
                   1009:       error("socket: %.100s", strerror(errno));
                   1010:       goto fail;
                   1011:     }
                   1012:
                   1013:   /* Connect to the host/port. */
                   1014:   if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
                   1015:     {
                   1016:       error("connect %.100s:%d: %.100s", host, host_port,
                   1017:            strerror(errno));
                   1018:       close(sock);
                   1019:       goto fail;
                   1020:     }
                   1021:
                   1022:   /* Successful connection. */
                   1023:
                   1024:   /* Allocate a channel for this connection. */
                   1025:   newch = channel_allocate(SSH_CHANNEL_OPEN, sock, originator_string);
                   1026:   channels[newch].remote_id = remote_channel;
                   1027:
                   1028:   /* Send a confirmation to the remote host. */
                   1029:   packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1030:   packet_put_int(remote_channel);
                   1031:   packet_put_int(newch);
                   1032:   packet_send();
                   1033:
                   1034:   /* Free the argument string. */
                   1035:   xfree(host);
                   1036:
                   1037:   return;
                   1038:
                   1039:  fail:
                   1040:   /* Free the argument string. */
                   1041:   xfree(host);
                   1042:
                   1043:   /* Send refusal to the remote host. */
                   1044:   packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   1045:   packet_put_int(remote_channel);
                   1046:   packet_send();
                   1047: }
                   1048:
                   1049: /* Creates an internet domain socket for listening for X11 connections.
                   1050:    Returns a suitable value for the DISPLAY variable, or NULL if an error
                   1051:    occurs. */
                   1052:
                   1053: char *x11_create_display_inet(int screen_number)
                   1054: {
                   1055:   int display_number, port, sock;
                   1056:   struct sockaddr_in sin;
                   1057:   char buf[512];
                   1058: #ifdef HAVE_GETHOSTNAME
                   1059:   char hostname[257];
                   1060: #else
                   1061:   struct utsname uts;
                   1062: #endif
                   1063:
                   1064:   for (display_number = 1; display_number < MAX_DISPLAYS; display_number++)
                   1065:     {
                   1066:       port = 6000 + display_number;
                   1067:       memset(&sin, 0, sizeof(sin));
                   1068:       sin.sin_family = AF_INET;
                   1069:       sin.sin_addr.s_addr = INADDR_ANY;
                   1070:       sin.sin_port = htons(port);
                   1071:
                   1072:       sock = socket(AF_INET, SOCK_STREAM, 0);
                   1073:       if (sock < 0)
                   1074:        {
                   1075:          error("socket: %.100s", strerror(errno));
                   1076:          return NULL;
                   1077:        }
                   1078:
                   1079:       if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
                   1080:        {
                   1081:          debug("bind port %d: %.100s", port, strerror(errno));
                   1082:          shutdown(sock, 2);
                   1083:          close(sock);
                   1084:          continue;
                   1085:        }
                   1086:       break;
                   1087:     }
                   1088:   if (display_number >= MAX_DISPLAYS)
                   1089:     {
                   1090:       error("Failed to allocate internet-domain X11 display socket.");
                   1091:       return NULL;
                   1092:     }
                   1093:
                   1094:   /* Start listening for connections on the socket. */
                   1095:   if (listen(sock, 5) < 0)
                   1096:     {
                   1097:       error("listen: %.100s", strerror(errno));
                   1098:       shutdown(sock, 2);
                   1099:       close(sock);
                   1100:       return NULL;
                   1101:     }
                   1102:
                   1103:   /* Set up a suitable value for the DISPLAY variable. */
                   1104: #ifdef HPSUX_NONSTANDARD_X11_KLUDGE
                   1105:   /* HPSUX has some special shared memory stuff in their X server, which
                   1106:      appears to be enable if the host name matches that of the local machine.
                   1107:      However, it can be circumvented by using the IP address of the local
                   1108:      machine instead.  */
                   1109:   if (gethostname(hostname, sizeof(hostname)) < 0)
                   1110:     fatal("gethostname: %.100s", strerror(errno));
                   1111:   {
                   1112:     struct hostent *hp;
                   1113:     struct in_addr addr;
                   1114:     hp = gethostbyname(hostname);
                   1115:     if (!hp->h_addr_list[0])
                   1116:       {
                   1117:        error("Could not server IP address for %.200d.", hostname);
                   1118:        packet_send_debug("Could not get server IP address for %.200d.",
                   1119:                          hostname);
                   1120:        shutdown(sock, 2);
                   1121:        close(sock);
                   1122:        return NULL;
                   1123:       }
                   1124:     memcpy(&addr, hp->h_addr_list[0], sizeof(addr));
                   1125:     sprintf(buf, "%.100s:%d.%d", inet_ntoa(addr), display_number,
                   1126:            screen_number);
                   1127:   }
                   1128: #else /* HPSUX_NONSTANDARD_X11_KLUDGE */
                   1129: #ifdef HAVE_GETHOSTNAME
                   1130:   if (gethostname(hostname, sizeof(hostname)) < 0)
                   1131:     fatal("gethostname: %.100s", strerror(errno));
                   1132:   sprintf(buf, "%.400s:%d.%d", hostname, display_number, screen_number);
                   1133: #else /* HAVE_GETHOSTNAME */
                   1134:   if (uname(&uts) < 0)
                   1135:     fatal("uname: %s", strerror(errno));
                   1136:   sprintf(buf, "%.400s:%d.%d", uts.nodename, display_number, screen_number);
                   1137: #endif /* HAVE_GETHOSTNAME */
                   1138: #endif /* HPSUX_NONSTANDARD_X11_KLUDGE */
                   1139:
                   1140:   /* Allocate a channel for the socket. */
                   1141:   (void)channel_allocate(SSH_CHANNEL_X11_LISTENER, sock,
                   1142:                         xstrdup("X11 inet listener"));
                   1143:
                   1144:   /* Return a suitable value for the DISPLAY environment variable. */
                   1145:   return xstrdup(buf);
                   1146: }
                   1147:
                   1148: #ifndef X_UNIX_PATH
                   1149: #define X_UNIX_PATH "/tmp/.X11-unix/X"
                   1150: #endif
                   1151:
                   1152: static
                   1153: int
                   1154: connect_local_xsocket(unsigned dnr)
                   1155: {
                   1156:   static const char *const x_sockets[] = {
                   1157:     X_UNIX_PATH "%u",
                   1158:     "/var/X/.X11-unix/X" "%u",
                   1159:     "/usr/spool/sockets/X11/" "%u",
                   1160:     NULL
                   1161:   };
                   1162:   int sock;
                   1163:   struct sockaddr_un addr;
                   1164:   const char *const *path;
                   1165:
                   1166:   for (path = x_sockets; *path; ++path)
                   1167:     {
                   1168:       sock = socket(AF_UNIX, SOCK_STREAM, 0);
                   1169:       if (sock < 0)
                   1170:        error("socket: %.100s", strerror(errno));
                   1171:       memset(&addr, 0, sizeof(addr));
                   1172:       addr.sun_family = AF_UNIX;
                   1173:       sprintf(addr.sun_path, *path, dnr);
                   1174:       if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
                   1175:        return sock;
                   1176:       close(sock);
                   1177:     }
                   1178:   error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
                   1179:   return -1;
                   1180: }
                   1181:
                   1182:
                   1183: /* This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
                   1184:    the remote channel number.  We should do whatever we want, and respond
                   1185:    with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE. */
                   1186:
                   1187: void x11_input_open(int payload_len)
                   1188: {
                   1189:   int remote_channel, display_number, sock, newch;
                   1190:   const char *display;
                   1191:   struct sockaddr_in sin;
                   1192:   char buf[1024], *cp, *remote_host;
                   1193:   struct hostent *hp;
                   1194:   int remote_len;
                   1195:
                   1196:   /* Get remote channel number. */
                   1197:   remote_channel = packet_get_int();
                   1198:
                   1199:   /* Get remote originator name. */
                   1200:   if (have_hostname_in_open)
                   1201:     remote_host = packet_get_string(&remote_len);
                   1202:   else
                   1203:     remote_host = xstrdup("unknown (remote did not supply name)");
                   1204:
                   1205:   debug("Received X11 open request.");
                   1206:   packet_integrity_check(payload_len, 4 + 4+remote_len, SSH_SMSG_X11_OPEN);
                   1207:
                   1208:   /* Try to open a socket for the local X server. */
                   1209:   display = getenv("DISPLAY");
                   1210:   if (!display)
                   1211:     {
                   1212:       error("DISPLAY not set.");
                   1213:       goto fail;
                   1214:     }
                   1215:
                   1216:   /* Now we decode the value of the DISPLAY variable and make a connection
                   1217:      to the real X server. */
                   1218:
                   1219:   /* Check if it is a unix domain socket.  Unix domain displays are in one
                   1220:      of the following formats: unix:d[.s], :d[.s], ::d[.s] */
                   1221:   if (strncmp(display, "unix:", 5) == 0 ||
                   1222:       display[0] == ':')
                   1223:     {
                   1224:       /* Connect to the unix domain socket. */
                   1225:       if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1)
                   1226:        {
                   1227:          error("Could not parse display number from DISPLAY: %.100s",
                   1228:                display);
                   1229:          goto fail;
                   1230:        }
                   1231:       /* Create a socket. */
                   1232:       sock = connect_local_xsocket(display_number);
                   1233:       if (sock < 0)
                   1234:        goto fail;
                   1235:
                   1236:       /* OK, we now have a connection to the display. */
                   1237:       goto success;
                   1238:     }
                   1239:
                   1240:   /* Connect to an inet socket.  The DISPLAY value is supposedly
                   1241:       hostname:d[.s], where hostname may also be numeric IP address. */
                   1242:   strncpy(buf, display, sizeof(buf));
                   1243:   buf[sizeof(buf) - 1] = 0;
                   1244:   cp = strchr(buf, ':');
                   1245:   if (!cp)
                   1246:     {
                   1247:       error("Could not find ':' in DISPLAY: %.100s", display);
                   1248:       goto fail;
                   1249:     }
                   1250:   *cp = 0;
                   1251:   /* buf now contains the host name.  But first we parse the display number. */
                   1252:   if (sscanf(cp + 1, "%d", &display_number) != 1)
                   1253:     {
                   1254:        error("Could not parse display number from DISPLAY: %.100s",
                   1255:             display);
                   1256:       goto fail;
                   1257:     }
                   1258:
                   1259:   /* Try to parse the host name as a numeric IP address. */
                   1260:   memset(&sin, 0, sizeof(sin));
                   1261: #ifdef BROKEN_INET_ADDR
                   1262:   sin.sin_addr.s_addr = inet_network(buf);
                   1263: #else /* BROKEN_INET_ADDR */
                   1264:   sin.sin_addr.s_addr = inet_addr(buf);
                   1265: #endif /* BROKEN_INET_ADDR */
                   1266:   if ((sin.sin_addr.s_addr & 0xffffffff) != 0xffffffff)
                   1267:     {
                   1268:       /* It was a valid numeric host address. */
                   1269:       sin.sin_family = AF_INET;
                   1270:     }
                   1271:   else
                   1272:     {
                   1273:       /* Not a numeric IP address. */
                   1274:       /* Look up the host address from the name servers. */
                   1275:       hp = gethostbyname(buf);
                   1276:       if (!hp)
                   1277:        {
                   1278:          error("%.100s: unknown host.", buf);
                   1279:          goto fail;
                   1280:        }
                   1281:       if (!hp->h_addr_list[0])
                   1282:        {
                   1283:          error("%.100s: host has no IP address.", buf);
                   1284:          goto fail;
                   1285:        }
                   1286:       sin.sin_family = hp->h_addrtype;
                   1287:       memcpy(&sin.sin_addr, hp->h_addr_list[0],
                   1288:             sizeof(sin.sin_addr));
                   1289:     }
                   1290:   /* Set port number. */
                   1291:   sin.sin_port = htons(6000 + display_number);
                   1292:
                   1293:   /* Create a socket. */
                   1294:   sock = socket(sin.sin_family, SOCK_STREAM, 0);
                   1295:   if (sock < 0)
                   1296:     {
                   1297:       error("socket: %.100s", strerror(errno));
                   1298:       goto fail;
                   1299:     }
                   1300:   /* Connect it to the display. */
                   1301:   if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
                   1302:     {
                   1303:       error("connect %.100s:%d: %.100s", buf, 6000 + display_number,
                   1304:            strerror(errno));
                   1305:       close(sock);
                   1306:       goto fail;
                   1307:     }
                   1308:
                   1309:  success:
                   1310:   /* We have successfully obtained a connection to the real X display. */
                   1311:
                   1312:   /* Allocate a channel for this connection. */
                   1313:   if (x11_saved_proto == NULL)
                   1314:     newch = channel_allocate(SSH_CHANNEL_OPEN, sock, remote_host);
                   1315:   else
                   1316:     newch = channel_allocate(SSH_CHANNEL_X11_OPEN, sock, remote_host);
                   1317:   channels[newch].remote_id = remote_channel;
                   1318:
                   1319:   /* Send a confirmation to the remote host. */
                   1320:   packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1321:   packet_put_int(remote_channel);
                   1322:   packet_put_int(newch);
                   1323:   packet_send();
                   1324:
                   1325:   return;
                   1326:
                   1327:  fail:
                   1328:   /* Send refusal to the remote host. */
                   1329:   packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   1330:   packet_put_int(remote_channel);
                   1331:   packet_send();
                   1332: }
                   1333:
                   1334: /* Requests forwarding of X11 connections, generates fake authentication
                   1335:    data, and enables authentication spoofing. */
                   1336:
1.2     ! provos   1337: void x11_request_forwarding_with_spoofing(const char *proto, const char *data)
1.1       deraadt  1338: {
                   1339:   unsigned int data_len = (unsigned int)strlen(data) / 2;
                   1340:   unsigned int i, value;
                   1341:   char *new_data;
                   1342:   int screen_number;
                   1343:   const char *cp;
1.2     ! provos   1344:   u_int32_t rand;
1.1       deraadt  1345:
                   1346:   cp = getenv("DISPLAY");
                   1347:   if (cp)
                   1348:     cp = strchr(cp, ':');
                   1349:   if (cp)
                   1350:     cp = strchr(cp, '.');
                   1351:   if (cp)
                   1352:     screen_number = atoi(cp + 1);
                   1353:   else
                   1354:     screen_number = 0;
                   1355:
                   1356:   /* Save protocol name. */
                   1357:   x11_saved_proto = xstrdup(proto);
                   1358:
                   1359:   /* Extract real authentication data and generate fake data of the same
                   1360:      length. */
                   1361:   x11_saved_data = xmalloc(data_len);
                   1362:   x11_fake_data = xmalloc(data_len);
                   1363:   for (i = 0; i < data_len; i++)
                   1364:     {
                   1365:       if (sscanf(data + 2 * i, "%2x", &value) != 1)
                   1366:        fatal("x11_request_forwarding: bad authentication data: %.100s", data);
1.2     ! provos   1367:       if (i % 4 == 0)
        !          1368:        rand = arc4random();
1.1       deraadt  1369:       x11_saved_data[i] = value;
1.2     ! provos   1370:       x11_fake_data[i] = rand & 0xff;
        !          1371:       rand >>= 8;
1.1       deraadt  1372:     }
                   1373:   x11_saved_data_len = data_len;
                   1374:   x11_fake_data_len = data_len;
                   1375:
                   1376:   /* Convert the fake data into hex. */
                   1377:   new_data = xmalloc(2 * data_len + 1);
                   1378:   for (i = 0; i < data_len; i++)
                   1379:     sprintf(new_data + 2 * i, "%02x", (unsigned char)x11_fake_data[i]);
                   1380:
                   1381:   /* Send the request packet. */
                   1382:   packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
                   1383:   packet_put_string(proto, strlen(proto));
                   1384:   packet_put_string(new_data, strlen(new_data));
                   1385:   packet_put_int(screen_number);
                   1386:   packet_send();
                   1387:   packet_write_wait();
                   1388:   xfree(new_data);
                   1389: }
                   1390:
                   1391: /* Sends a message to the server to request authentication fd forwarding. */
                   1392:
                   1393: void auth_request_forwarding()
                   1394: {
                   1395:   packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
                   1396:   packet_send();
                   1397:   packet_write_wait();
                   1398: }
                   1399:
                   1400: /* Returns the number of the file descriptor to pass to child programs as
                   1401:    the authentication fd.  Returns -1 if there is no forwarded authentication
                   1402:    fd. */
                   1403:
                   1404: int auth_get_fd()
                   1405: {
                   1406:   return channel_forwarded_auth_fd;
                   1407: }
                   1408:
                   1409: /* Returns the name of the forwarded authentication socket.  Returns NULL
                   1410:    if there is no forwarded authentication socket.  The returned value
                   1411:    points to a static buffer. */
                   1412:
                   1413: char *auth_get_socket_name()
                   1414: {
                   1415:   return channel_forwarded_auth_socket_name;
                   1416: }
                   1417:
                   1418: /* This if called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
                   1419:    This starts forwarding authentication requests. */
                   1420:
                   1421: void auth_input_request_forwarding(struct passwd *pw)
                   1422: {
                   1423:   int pfd = get_permanent_fd(pw->pw_shell);
                   1424: #ifdef HAVE_UMASK
                   1425:   mode_t savedumask;
                   1426: #endif /* HAVE_UMASK */
                   1427:
                   1428:   if (pfd < 0)
                   1429:     {
                   1430:       int sock, newch;
                   1431:       struct sockaddr_un sunaddr;
                   1432:
                   1433:       if (auth_get_socket_name() != NULL)
                   1434:        fatal("Protocol error: authentication forwarding requested twice.");
                   1435:
                   1436:       /* Allocate a buffer for the socket name, and format the name. */
                   1437:       channel_forwarded_auth_socket_name = xmalloc(100);
                   1438:       sprintf(channel_forwarded_auth_socket_name, SSH_AGENT_SOCKET,
                   1439:              (int)getpid());
                   1440:
                   1441:       /* Create the socket. */
                   1442:       sock = socket(AF_UNIX, SOCK_STREAM, 0);
                   1443:       if (sock < 0)
                   1444:        packet_disconnect("socket: %.100s", strerror(errno));
                   1445:
                   1446:       /* Bind it to the name. */
                   1447:       memset(&sunaddr, 0, sizeof(sunaddr));
                   1448:       sunaddr.sun_family = AF_UNIX;
                   1449:       strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
                   1450:              sizeof(sunaddr.sun_path));
                   1451:
                   1452: #ifdef HAVE_UMASK
                   1453:       savedumask = umask(0077);
                   1454: #endif /* HAVE_UMASK */
                   1455:
                   1456:       /* Temporarily use a privileged uid. */
                   1457:       temporarily_use_uid(pw->pw_uid);
                   1458:
                   1459:       if (bind(sock, (struct sockaddr *)&sunaddr, AF_UNIX_SIZE(sunaddr)) < 0)
                   1460:        packet_disconnect("bind: %.100s", strerror(errno));
                   1461:
                   1462:       /* Restore the privileged uid. */
                   1463:       restore_uid();
                   1464:
                   1465: #ifdef HAVE_UMASK
                   1466:       umask(savedumask);
                   1467: #endif /* HAVE_UMASK */
                   1468:
                   1469:       /* Start listening on the socket. */
                   1470:       if (listen(sock, 5) < 0)
                   1471:        packet_disconnect("listen: %.100s", strerror(errno));
                   1472:
                   1473:       /* Allocate a channel for the authentication agent socket. */
                   1474:       newch = channel_allocate(SSH_CHANNEL_AUTH_SOCKET, sock,
                   1475:                               xstrdup("auth socket"));
                   1476:       strcpy(channels[newch].path, channel_forwarded_auth_socket_name);
                   1477:     }
                   1478:   else
                   1479:     {
                   1480:       int sockets[2], i, cnt, newfd;
                   1481:       int *dups = xmalloc(sizeof (int) * (pfd + 1));
                   1482:
                   1483:       if (auth_get_fd() != -1)
                   1484:        fatal("Protocol error: authentication forwarding requested twice.");
                   1485:
                   1486:       /* Create a socket pair. */
                   1487:       if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) < 0)
                   1488:        packet_disconnect("socketpair: %.100s", strerror(errno));
                   1489:
                   1490:       /* Dup some descriptors to get the authentication fd to pfd,
                   1491:         because some shells arbitrarily close descriptors below that.
                   1492:         Don't use dup2 because maybe some systems don't have it?? */
                   1493:       for (cnt = 0;; cnt++)
                   1494:        {
                   1495:          if ((dups[cnt] = dup(packet_get_connection_in())) < 0)
                   1496:            fatal("auth_input_request_forwarding: dup failed");
                   1497:          if (dups[cnt] == pfd)
                   1498:            break;
                   1499:        }
                   1500:       close(dups[cnt]);
                   1501:
                   1502:       /* Move the file descriptor we pass to children up high where
                   1503:         the shell won't close it. */
                   1504:       newfd = dup(sockets[1]);
                   1505:       if (newfd != pfd)
                   1506:        fatal ("auth_input_request_forwarding: dup didn't return %d.", pfd);
                   1507:       close(sockets[1]);
                   1508:       sockets[1] = newfd;
                   1509:       /* Close duped descriptors. */
                   1510:       for (i = 0; i < cnt; i++)
                   1511:        close(dups[i]);
                   1512:       free(dups);
                   1513:
                   1514:       /* Record the file descriptor to be passed to children. */
                   1515:       channel_forwarded_auth_fd = sockets[1];
                   1516:
                   1517:       /* Allcate a channel for the authentication fd. */
                   1518:       (void)channel_allocate(SSH_CHANNEL_AUTH_FD, sockets[0],
                   1519:                             xstrdup("auth fd"));
                   1520:     }
                   1521: }
                   1522:
                   1523: /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
                   1524:
                   1525: void auth_input_open_request()
                   1526: {
                   1527:   int port, sock, newch;
                   1528:   char *dummyname;
                   1529:
                   1530:   /* Read the port number from the message. */
                   1531:   port = packet_get_int();
                   1532:
                   1533:   /* Get a connection to the local authentication agent (this may again get
                   1534:      forwarded). */
                   1535:   sock = ssh_get_authentication_connection_fd();
                   1536:
                   1537:   /* If we could not connect the agent, just return.  This will cause the
                   1538:      client to timeout and fail.  This should never happen unless the agent
                   1539:      dies, because authentication forwarding is only enabled if we have an
                   1540:      agent. */
                   1541:   if (sock < 0)
                   1542:     return;
                   1543:
                   1544:   debug("Forwarding authentication connection.");
                   1545:
                   1546:   /* Dummy host name.  This will be freed when the channel is freed; it will
                   1547:      still be valid in the packet_put_string below since the channel cannot
                   1548:      yet be freed at that point. */
                   1549:   dummyname = xstrdup("authentication agent connection");
                   1550:
                   1551:   /* Allocate a channel for the new connection. */
                   1552:   newch = channel_allocate(SSH_CHANNEL_OPENING, sock, dummyname);
                   1553:
                   1554:   /* Fake a forwarding request. */
                   1555:   packet_start(SSH_MSG_PORT_OPEN);
                   1556:   packet_put_int(newch);
                   1557:   packet_put_string("localhost", strlen("localhost"));
                   1558:   packet_put_int(port);
                   1559:   if (have_hostname_in_open)
                   1560:     packet_put_string(dummyname, strlen(dummyname));
                   1561:   packet_send();
                   1562: }