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

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