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

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