[BACK]Return to ssh.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/ssh.c, Revision 1.22

1.1       deraadt     1: /*
                      2:
                      3: ssh.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: Sat Mar 18 16:36:11 1995 ylo
                     11:
                     12: Ssh client program.  This program can be used to log into a remote machine.
                     13: The software supports strong authentication, encryption, and forwarding
                     14: of X11, TCP/IP, and authentication connections.
                     15:
1.2       provos     16: Modified to work with SSL by Niels Provos <provos@citi.umich.edu> in Canada.
                     17:
1.1       deraadt    18: */
                     19:
                     20: #include "includes.h"
1.22    ! provos     21: RCSID("$Id: ssh.c,v 1.21 1999/09/30 20:39:08 deraadt Exp $");
1.1       deraadt    22:
                     23: #include "xmalloc.h"
                     24: #include "ssh.h"
                     25: #include "packet.h"
                     26: #include "buffer.h"
                     27: #include "authfd.h"
                     28: #include "readconf.h"
                     29: #include "uidswap.h"
                     30:
                     31: /* Flag indicating whether debug mode is on.  This can be set on the
                     32:    command line. */
                     33: int debug_flag = 0;
                     34:
                     35: /* Flag indicating whether quiet mode is on. */
                     36: int quiet_flag = 0;
                     37:
                     38: /* Flag indicating whether to allocate a pseudo tty.  This can be set on the
                     39:    command line, and is automatically set if no command is given on the command
                     40:    line. */
                     41: int tty_flag = 0;
                     42:
                     43: /* Flag indicating that nothing should be read from stdin.  This can be set
                     44:    on the command line. */
                     45: int stdin_null_flag = 0;
                     46:
                     47: /* Flag indicating that ssh should fork after authentication.  This is useful
                     48:    so that the pasphrase can be entered manually, and then ssh goes to the
                     49:    background. */
                     50: int fork_after_authentication_flag = 0;
                     51:
                     52: /* General data structure for command line options and options configurable
                     53:    in configuration files.  See readconf.h. */
                     54: Options options;
                     55:
                     56: /* Name of the host we are connecting to.  This is the name given on the
                     57:    command line, or the HostName specified for the user-supplied name
                     58:    in a configuration file. */
                     59: char *host;
                     60:
1.22    ! provos     61: /* socket address the host resolves to */
        !            62: struct sockaddr_in hostaddr;
        !            63:
1.1       deraadt    64: /* Flag to indicate that we have received a window change signal which has
                     65:    not yet been processed.  This will cause a message indicating the new
                     66:    window size to be sent to the server a little later.  This is volatile
                     67:    because this is updated in a signal handler. */
                     68: volatile int received_window_change_signal = 0;
                     69:
                     70: /* Value of argv[0] (set in the main program). */
                     71: char *av0;
                     72:
                     73: /* Flag indicating whether we have a valid host private key loaded. */
                     74: int host_private_key_loaded = 0;
                     75:
                     76: /* Host private key. */
1.2       provos     77: RSA *host_private_key = NULL;
1.1       deraadt    78:
1.10      dugsong    79: /* Original real UID. */
                     80: uid_t original_real_uid;
1.1       deraadt    81:
                     82: /* Prints a help message to the user.  This function never returns. */
                     83:
1.2       provos     84: void
                     85: usage()
1.1       deraadt    86: {
                     87:   fprintf(stderr, "Usage: %s [options] host [command]\n", av0);
                     88:   fprintf(stderr, "Options:\n");
                     89:   fprintf(stderr, "  -l user     Log in using this user name.\n");
                     90:   fprintf(stderr, "  -n          Redirect input from /dev/null.\n");
1.7       provos     91:   fprintf(stderr, "  -a          Disable authentication agent forwarding.\n");
1.9       dugsong    92: #ifdef AFS
                     93:   fprintf(stderr, "  -k          Disable Kerberos ticket and AFS token forwarding.\n");
                     94: #endif /* AFS */
1.1       deraadt    95:   fprintf(stderr, "  -x          Disable X11 connection forwarding.\n");
                     96:   fprintf(stderr, "  -i file     Identity for RSA authentication (default: ~/.ssh/identity).\n");
                     97:   fprintf(stderr, "  -t          Tty; allocate a tty even if command is given.\n");
                     98:   fprintf(stderr, "  -v          Verbose; display verbose debugging messages.\n");
1.8       provos     99:   fprintf(stderr, "  -V          Display version number only.\n");
1.1       deraadt   100:   fprintf(stderr, "  -q          Quiet; don't display any warning messages.\n");
                    101:   fprintf(stderr, "  -f          Fork into background after authentication.\n");
                    102:   fprintf(stderr, "  -e char     Set escape character; ``none'' = disable (default: ~).\n");
                    103:
1.19      provos    104:   fprintf(stderr, "  -c cipher   Select encryption algorithm: "
                    105:                  "``3des'', "
                    106:                  "``blowfish''\n");
1.1       deraadt   107:   fprintf(stderr, "  -p port     Connect to this port.  Server must be on the same port.\n");
                    108:   fprintf(stderr, "  -L listen-port:host:port   Forward local port to remote address\n");
                    109:   fprintf(stderr, "  -R listen-port:host:port   Forward remote port to local address\n");
                    110:   fprintf(stderr, "              These cause %s to listen for connections on a port, and\n", av0);
                    111:   fprintf(stderr, "              forward them to the other side by connecting to host:port.\n");
                    112:   fprintf(stderr, "  -C          Enable compression.\n");
1.21      deraadt   113:   fprintf(stderr, "  -g          Allow remote hosts to connect to forwarded ports.\n");
1.1       deraadt   114:   fprintf(stderr, "  -o 'option' Process the option as if it was read from a configuration file.\n");
                    115:   exit(1);
                    116: }
                    117:
                    118: /* Connects to the given host using rsh (or prints an error message and exits
                    119:    if rsh is not available).  This function never returns. */
                    120:
1.2       provos    121: void
                    122: rsh_connect(char *host, char *user, Buffer *command)
1.1       deraadt   123: {
                    124:   char *args[10];
                    125:   int i;
                    126:
                    127:   log("Using rsh.  WARNING: Connection will not be encrypted.");
                    128:   /* Build argument list for rsh. */
                    129:   i = 0;
1.13      deraadt   130:   args[i++] = _PATH_RSH;
1.1       deraadt   131:   args[i++] = host;    /* may have to come after user on some systems */
                    132:   if (user)
                    133:     {
                    134:       args[i++] = "-l";
                    135:       args[i++] = user;
                    136:     }
                    137:   if (buffer_len(command) > 0)
                    138:     {
                    139:       buffer_append(command, "\0", 1);
                    140:       args[i++] = buffer_ptr(command);
                    141:     }
                    142:   args[i++] = NULL;
                    143:   if (debug_flag)
                    144:     {
                    145:       for (i = 0; args[i]; i++)
                    146:        {
                    147:          if (i != 0)
                    148:            fprintf(stderr, " ");
                    149:          fprintf(stderr, "%s", args[i]);
                    150:        }
                    151:       fprintf(stderr, "\n");
                    152:     }
1.13      deraadt   153:   execv(_PATH_RSH, args);
                    154:   perror(_PATH_RSH);
1.1       deraadt   155:   exit(1);
                    156: }
                    157:
                    158: /* Main program for the ssh client. */
                    159:
1.11      deraadt   160: uid_t original_real_uid;
                    161:
1.2       provos    162: int
                    163: main(int ac, char **av)
1.1       deraadt   164: {
                    165:   int i, opt, optind, type, exit_status, ok, fwd_port, fwd_host_port, authfd;
                    166:   char *optarg, *cp, buf[256];
                    167:   Buffer command;
                    168:   struct winsize ws;
                    169:   struct stat st;
                    170:   struct passwd *pw, pwcopy;
                    171:   int interactive = 0, dummy;
                    172:   uid_t original_effective_uid;
                    173:   int plen;
                    174:
                    175:   /* Save the original real uid.  It will be needed later (uid-swapping may
                    176:      clobber the real uid).  */
                    177:   original_real_uid = getuid();
                    178:   original_effective_uid = geteuid();
                    179:
                    180:   /* If we are installed setuid root be careful to not drop core. */
                    181:   if (original_real_uid != original_effective_uid)
                    182:     {
                    183:       struct rlimit rlim;
                    184:       rlim.rlim_cur = rlim.rlim_max = 0;
                    185:       if (setrlimit(RLIMIT_CORE, &rlim) < 0)
                    186:        fatal("setrlimit failed: %.100s", strerror(errno));
                    187:     }
                    188:
                    189:   /* Use uid-swapping to give up root privileges for the duration of option
                    190:      processing.  We will re-instantiate the rights when we are ready to
                    191:      create the privileged port, and will permanently drop them when the
                    192:      port has been created (actually, when the connection has been made, as
                    193:      we may need to create the port several times). */
                    194:   temporarily_use_uid(original_real_uid);
                    195:
                    196:   /* Set our umask to something reasonable, as some files are created with
                    197:      the default umask.  This will make them world-readable but writable
                    198:      only by the owner, which is ok for all files for which we don't set
                    199:      the modes explicitly. */
                    200:   umask(022);
                    201:
                    202:   /* Save our own name. */
                    203:   av0 = av[0];
                    204:
                    205:   /* Initialize option structure to indicate that no values have been set. */
                    206:   initialize_options(&options);
                    207:
                    208:   /* Parse command-line arguments. */
                    209:   host = NULL;
                    210:
                    211:   /* If program name is not one of the standard names, use it as host name. */
                    212:   if (strchr(av0, '/'))
                    213:     cp = strrchr(av0, '/') + 1;
                    214:   else
                    215:     cp = av0;
                    216:   if (strcmp(cp, "rsh") != 0 && strcmp(cp, "ssh") != 0 &&
                    217:       strcmp(cp, "rlogin") != 0 && strcmp(cp, "slogin") != 0)
                    218:     host = cp;
                    219:
                    220:   for (optind = 1; optind < ac; optind++)
                    221:     {
                    222:       if (av[optind][0] != '-')
                    223:        {
                    224:          if (host)
                    225:            break;
1.3       deraadt   226:           if ((cp = strchr(av[optind], '@'))) {
                    227:             options.user = av[optind];
                    228:             *cp = '\0';
                    229:             host = ++cp;
                    230:           }
                    231:           else
                    232:            host = av[optind];
1.1       deraadt   233:          continue;
                    234:        }
                    235:       opt = av[optind][1];
                    236:       if (!opt)
                    237:        usage();
                    238:       if (strchr("eilcpLRo", opt)) /* options with arguments */
                    239:        {
                    240:          optarg = av[optind] + 2;
                    241:          if (strcmp(optarg, "") == 0)
                    242:            {
                    243:              if (optind >= ac - 1)
                    244:                usage();
                    245:              optarg = av[++optind];
                    246:            }
                    247:        }
                    248:       else
                    249:        {
                    250:          if (av[optind][2])
                    251:            usage();
                    252:          optarg = NULL;
                    253:        }
                    254:       switch (opt)
                    255:        {
                    256:        case 'n':
                    257:          stdin_null_flag = 1;
                    258:          break;
                    259:
                    260:        case 'f':
                    261:          fork_after_authentication_flag = 1;
                    262:          stdin_null_flag = 1;
                    263:          break;
                    264:
                    265:        case 'x':
                    266:          options.forward_x11 = 0;
                    267:          break;
                    268:
                    269:        case 'X':
                    270:          options.forward_x11 = 1;
1.4       deraadt   271:          break;
                    272:
                    273:        case 'g':
                    274:          options.gateway_ports = 1;
1.1       deraadt   275:          break;
                    276:
                    277:        case 'a':
                    278:          options.forward_agent = 0;
1.9       dugsong   279:          break;
                    280: #ifdef AFS
                    281:        case 'k':
1.1       deraadt   282:          options.kerberos_tgt_passing = 0;
                    283:          options.afs_token_passing = 0;
1.9       dugsong   284:          break;
1.1       deraadt   285: #endif
                    286:        case 'i':
                    287:          if (stat(optarg, &st) < 0)
                    288:            {
                    289:              fprintf(stderr, "Warning: Identity file %s does not exist.\n",
                    290:                      optarg);
                    291:              break;
                    292:            }
                    293:          if (options.num_identity_files >= SSH_MAX_IDENTITY_FILES)
                    294:            fatal("Too many identity files specified (max %d)",
                    295:                  SSH_MAX_IDENTITY_FILES);
                    296:          options.identity_files[options.num_identity_files++] =
                    297:            xstrdup(optarg);
                    298:          break;
                    299:
                    300:        case 't':
                    301:          tty_flag = 1;
                    302:          break;
                    303:
                    304:        case 'v':
1.6       deraadt   305:        case 'V':
1.1       deraadt   306:          debug_flag = 1;
                    307:          fprintf(stderr, "SSH Version %s, protocol version %d.%d.\n",
                    308:                  SSH_VERSION, PROTOCOL_MAJOR, PROTOCOL_MINOR);
                    309:          fprintf(stderr, "Compiled with SSL.\n");
1.6       deraadt   310:          if (opt == 'V')
                    311:            exit(0);
1.1       deraadt   312:          break;
                    313:
                    314:        case 'q':
                    315:          quiet_flag = 1;
                    316:          break;
                    317:
                    318:        case 'e':
                    319:          if (optarg[0] == '^' && optarg[2] == 0 &&
                    320:              (unsigned char)optarg[1] >= 64 && (unsigned char)optarg[1] < 128)
                    321:            options.escape_char = (unsigned char)optarg[1] & 31;
                    322:          else
                    323:            if (strlen(optarg) == 1)
                    324:              options.escape_char = (unsigned char)optarg[0];
                    325:            else
                    326:              if (strcmp(optarg, "none") == 0)
                    327:                options.escape_char = -2;
                    328:              else
                    329:                {
                    330:                  fprintf(stderr, "Bad escape character '%s'.\n", optarg);
                    331:                  exit(1);
                    332:                }
                    333:          break;
                    334:
                    335:        case 'c':
                    336:          options.cipher = cipher_number(optarg);
                    337:          if (options.cipher == -1)
                    338:            {
                    339:              fprintf(stderr, "Unknown cipher type '%s'\n", optarg);
                    340:              exit(1);
                    341:            }
                    342:          break;
                    343:
                    344:        case 'p':
                    345:          options.port = atoi(optarg);
                    346:          if (options.port < 1 || options.port > 65535)
                    347:            {
                    348:              fprintf(stderr, "Bad port %s.\n", optarg);
                    349:              exit(1);
                    350:            }
                    351:          break;
                    352:
                    353:        case 'l':
                    354:          options.user = optarg;
                    355:          break;
                    356:
                    357:        case 'R':
                    358:          if (sscanf(optarg, "%d:%255[^:]:%d", &fwd_port, buf,
                    359:                     &fwd_host_port) != 3)
                    360:            {
                    361:              fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
                    362:              usage();
                    363:              /*NOTREACHED*/
                    364:            }
                    365:          add_remote_forward(&options, fwd_port, buf, fwd_host_port);
                    366:          break;
                    367:
                    368:        case 'L':
                    369:          if (sscanf(optarg, "%d:%255[^:]:%d", &fwd_port, buf,
                    370:                     &fwd_host_port) != 3)
                    371:            {
                    372:              fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
                    373:              usage();
                    374:              /*NOTREACHED*/
                    375:            }
                    376:          add_local_forward(&options, fwd_port, buf, fwd_host_port);
                    377:          break;
                    378:
                    379:        case 'C':
                    380:          options.compression = 1;
                    381:          break;
                    382:
                    383:        case 'o':
                    384:          dummy = 1;
                    385:          process_config_line(&options, host ? host : "", optarg,
                    386:                              "command-line", 0, &dummy);
                    387:          break;
                    388:
                    389:        default:
                    390:          usage();
                    391:        }
                    392:     }
                    393:
                    394:  /* Check that we got a host name. */
                    395:   if (!host)
                    396:     usage();
1.5       deraadt   397:
                    398:   /* check if RSA support exists */
                    399:   if (rsa_alive() == 0) {
                    400:     extern char *__progname;
                    401:
                    402:     fprintf(stderr,
                    403:       "%s: no RSA support in libssl and libcrypto.  See ssl(8).\n",
                    404:       __progname);
                    405:     exit(1);
                    406:   }
1.1       deraadt   407:
                    408:   /* Initialize the command to execute on remote host. */
                    409:   buffer_init(&command);
                    410:
                    411:   /* Save the command to execute on the remote host in a buffer.  There is
                    412:      no limit on the length of the command, except by the maximum packet
                    413:      size.  Also sets the tty flag if there is no command. */
                    414:   if (optind == ac)
                    415:     {
                    416:       /* No command specified - execute shell on a tty. */
                    417:       tty_flag = 1;
                    418:     }
                    419:   else
                    420:     {
                    421:       /* A command has been specified.  Store it into the buffer. */
                    422:       for (i = optind; i < ac; i++)
                    423:        {
                    424:          if (i > optind)
                    425:            buffer_append(&command, " ", 1);
                    426:          buffer_append(&command, av[i], strlen(av[i]));
                    427:        }
                    428:     }
                    429:
                    430:   /* Cannot fork to background if no command. */
                    431:   if (fork_after_authentication_flag && buffer_len(&command) == 0)
                    432:     fatal("Cannot fork into background without a command to execute.");
                    433:
                    434:   /* Allocate a tty by default if no command specified. */
                    435:   if (buffer_len(&command) == 0)
                    436:     tty_flag = 1;
                    437:
                    438:   /* Do not allocate a tty if stdin is not a tty. */
                    439:   if (!isatty(fileno(stdin)))
                    440:     {
                    441:       if (tty_flag)
                    442:        fprintf(stderr, "Pseudo-terminal will not be allocated because stdin is not a terminal.\n");
                    443:       tty_flag = 0;
                    444:     }
                    445:
                    446:   /* Get user data. */
                    447:   pw = getpwuid(original_real_uid);
                    448:   if (!pw)
                    449:     {
                    450:       fprintf(stderr, "You don't exist, go away!\n");
                    451:       exit(1);
                    452:     }
                    453:
                    454:   /* Take a copy of the returned structure. */
                    455:   memset(&pwcopy, 0, sizeof(pwcopy));
                    456:   pwcopy.pw_name = xstrdup(pw->pw_name);
                    457:   pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
                    458:   pwcopy.pw_uid = pw->pw_uid;
                    459:   pwcopy.pw_gid = pw->pw_gid;
                    460:   pwcopy.pw_dir = xstrdup(pw->pw_dir);
                    461:   pwcopy.pw_shell = xstrdup(pw->pw_shell);
                    462:   pw = &pwcopy;
                    463:
                    464:   /* Initialize "log" output.  Since we are the client all output actually
                    465:      goes to the terminal. */
                    466:   log_init(av[0], 1, debug_flag, quiet_flag, SYSLOG_FACILITY_USER);
                    467:
                    468:   /* Read per-user configuration file. */
1.11      deraadt   469:   snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_CONFFILE);
1.1       deraadt   470:   read_config_file(buf, host, &options);
                    471:
                    472:   /* Read systemwide configuration file. */
                    473:   read_config_file(HOST_CONFIG_FILE, host, &options);
                    474:
                    475:   /* Fill configuration defaults. */
                    476:   fill_default_options(&options);
                    477:   if (options.user == NULL)
                    478:     options.user = xstrdup(pw->pw_name);
                    479:
                    480:   if (options.hostname != NULL)
                    481:     host = options.hostname;
                    482:
                    483:   /* Find canonic host name. */
                    484:   if (strchr(host, '.') == 0)
                    485:     {
                    486:       struct hostent *hp = gethostbyname(host);
                    487:       if (hp != 0)
                    488:        {
                    489:          if (strchr(hp->h_name, '.') != 0)
                    490:            host = xstrdup(hp->h_name);
                    491:          else if (hp->h_aliases != 0
                    492:                   && hp->h_aliases[0] != 0
                    493:                   && strchr(hp->h_aliases[0], '.') != 0)
                    494:            host = xstrdup(hp->h_aliases[0]);
                    495:        }
                    496:     }
                    497:
                    498:   /* Disable rhosts authentication if not running as root. */
                    499:   if (original_effective_uid != 0)
                    500:     {
                    501:       options.rhosts_authentication = 0;
                    502:       options.rhosts_rsa_authentication = 0;
                    503:     }
                    504:
                    505:   /* If using rsh has been selected, exec it now (without trying anything
                    506:      else).  Note that we must release privileges first. */
                    507:   if (options.use_rsh)
                    508:     {
                    509:       /* Restore our superuser privileges.  This must be done before
                    510:          permanently setting the uid. */
                    511:       restore_uid();
                    512:
                    513:       /* Switch to the original uid permanently. */
                    514:       permanently_set_uid(original_real_uid);
                    515:
                    516:       /* Execute rsh. */
                    517:       rsh_connect(host, options.user, &command);
                    518:       fatal("rsh_connect returned");
                    519:     }
                    520:
                    521:   /* Restore our superuser privileges. */
                    522:   restore_uid();
                    523:
                    524:   /* Open a connection to the remote host.  This needs root privileges if
1.2       provos    525:      rhosts_authentication is true. */
1.22    ! provos    526:   ok = ssh_connect(host, &hostaddr, options.port, options.connection_attempts,
1.1       deraadt   527:                   !options.rhosts_authentication &&
                    528:                   !options.rhosts_rsa_authentication,
1.2       provos    529:                   original_real_uid, options.proxy_command);
1.1       deraadt   530:
                    531:   /* If we successfully made the connection, load the host private key in
                    532:      case we will need it later for combined rsa-rhosts authentication.
                    533:      This must be done before releasing extra privileges, because the file
                    534:      is only readable by root. */
                    535:   if (ok)
                    536:     {
1.2       provos    537:       host_private_key = RSA_new();
                    538:       if (load_private_key(HOST_KEY_FILE, "", host_private_key, NULL))
1.1       deraadt   539:        host_private_key_loaded = 1;
                    540:     }
                    541:
                    542:   /* Get rid of any extra privileges that we may have.  We will no longer need
                    543:      them.  Also, extra privileges could make it very hard to read identity
                    544:      files and other non-world-readable files from the user's home directory
                    545:      if it happens to be on a NFS volume where root is mapped to nobody. */
                    546:   permanently_set_uid(original_real_uid);
                    547:
                    548:   /* Now that we are back to our own permissions, create ~/.ssh directory
                    549:      if it doesn\'t already exist. */
1.11      deraadt   550:   snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_DIR);
1.1       deraadt   551:   if (stat(buf, &st) < 0)
                    552:     if (mkdir(buf, 0755) < 0)
                    553:       error("Could not create directory '%.200s'.", buf);
                    554:
                    555:   /* Check if the connection failed, and try "rsh" if appropriate. */
                    556:   if (!ok)
                    557:     {
                    558:       if (options.port != 0)
                    559:        log("Secure connection to %.100s on port %d refused%.100s.",
                    560:            host, options.port,
                    561:            options.fallback_to_rsh ? "; reverting to insecure method" : "");
                    562:       else
                    563:        log("Secure connection to %.100s refused%.100s.", host,
                    564:            options.fallback_to_rsh ? "; reverting to insecure method" : "");
                    565:
                    566:       if (options.fallback_to_rsh)
                    567:        {
                    568:          rsh_connect(host, options.user, &command);
                    569:          fatal("rsh_connect returned");
                    570:        }
                    571:       exit(1);
                    572:     }
                    573:
                    574:   /* Expand ~ in options.identity_files. */
                    575:   for (i = 0; i < options.num_identity_files; i++)
                    576:     options.identity_files[i] =
                    577:       tilde_expand_filename(options.identity_files[i], original_real_uid);
                    578:
                    579:   /* Expand ~ in known host file names. */
                    580:   options.system_hostfile = tilde_expand_filename(options.system_hostfile,
                    581:                                                  original_real_uid);
                    582:   options.user_hostfile = tilde_expand_filename(options.user_hostfile,
                    583:                                                original_real_uid);
                    584:
1.2       provos    585:   /* Log into the remote system.  This never returns if the login fails. */
                    586:   ssh_login(host_private_key_loaded, host_private_key,
1.22    ! provos    587:            host, &hostaddr, &options, original_real_uid);
1.1       deraadt   588:
                    589:   /* We no longer need the host private key.  Clear it now. */
                    590:   if (host_private_key_loaded)
1.2       provos    591:     RSA_free(host_private_key); /* Destroys contents safely */
1.1       deraadt   592:
                    593:   /* Close connection cleanly after attack. */
                    594:   cipher_attack_detected = packet_disconnect;
                    595:
                    596:   /* If requested, fork and let ssh continue in the background. */
                    597:   if (fork_after_authentication_flag)
                    598:     {
                    599:       int ret = fork();
                    600:       if (ret == -1)
                    601:        fatal("fork failed: %.100s", strerror(errno));
                    602:       if (ret != 0)
                    603:        exit(0);
                    604:       setsid();
                    605:     }
                    606:
                    607:   /* Enable compression if requested. */
                    608:   if (options.compression)
                    609:     {
                    610:       debug("Requesting compression at level %d.", options.compression_level);
                    611:
                    612:       if (options.compression_level < 1 || options.compression_level > 9)
                    613:        fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
                    614:
                    615:       /* Send the request. */
                    616:       packet_start(SSH_CMSG_REQUEST_COMPRESSION);
                    617:       packet_put_int(options.compression_level);
                    618:       packet_send();
                    619:       packet_write_wait();
                    620:       type = packet_read(&plen);
                    621:       if (type == SSH_SMSG_SUCCESS)
                    622:        packet_start_compression(options.compression_level);
                    623:       else if (type == SSH_SMSG_FAILURE)
                    624:        log("Warning: Remote host refused compression.");
                    625:       else
                    626:        packet_disconnect("Protocol error waiting for compression response.");
                    627:     }
                    628:
                    629:   /* Allocate a pseudo tty if appropriate. */
                    630:   if (tty_flag)
                    631:     {
                    632:       debug("Requesting pty.");
                    633:
                    634:       /* Start the packet. */
                    635:       packet_start(SSH_CMSG_REQUEST_PTY);
                    636:
                    637:       /* Store TERM in the packet.  There is no limit on the length of the
                    638:          string. */
                    639:       cp = getenv("TERM");
                    640:       if (!cp)
                    641:        cp = "";
                    642:       packet_put_string(cp, strlen(cp));
                    643:
                    644:       /* Store window size in the packet. */
                    645:       if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
                    646:        memset(&ws, 0, sizeof(ws));
                    647:       packet_put_int(ws.ws_row);
                    648:       packet_put_int(ws.ws_col);
                    649:       packet_put_int(ws.ws_xpixel);
                    650:       packet_put_int(ws.ws_ypixel);
                    651:
                    652:       /* Store tty modes in the packet. */
                    653:       tty_make_modes(fileno(stdin));
                    654:
                    655:       /* Send the packet, and wait for it to leave. */
                    656:       packet_send();
                    657:       packet_write_wait();
                    658:
                    659:       /* Read response from the server. */
                    660:       type = packet_read(&plen);
                    661:       if (type == SSH_SMSG_SUCCESS)
                    662:        interactive = 1;
                    663:       else if (type == SSH_SMSG_FAILURE)
                    664:        log("Warning: Remote host failed or refused to allocate a pseudo tty.");
                    665:       else
                    666:        packet_disconnect("Protocol error waiting for pty request response.");
                    667:     }
                    668:
                    669:   /* Request X11 forwarding if enabled and DISPLAY is set. */
                    670:   if (options.forward_x11 && getenv("DISPLAY") != NULL)
                    671:     {
                    672:       char line[512], proto[512], data[512];
                    673:       FILE *f;
                    674:       int forwarded = 0, got_data = 0, i;
                    675:
                    676: #ifdef XAUTH_PATH
                    677:       /* Try to get Xauthority information for the display. */
1.11      deraadt   678:       snprintf(line, sizeof line, "%.100s list %.200s 2>/dev/null",
1.1       deraadt   679:              XAUTH_PATH, getenv("DISPLAY"));
                    680:       f = popen(line, "r");
                    681:       if (f && fgets(line, sizeof(line), f) &&
                    682:          sscanf(line, "%*s %s %s", proto, data) == 2)
                    683:        got_data = 1;
                    684:       if (f)
                    685:        pclose(f);
                    686: #endif /* XAUTH_PATH */
                    687:       /* If we didn't get authentication data, just make up some data.  The
                    688:         forwarding code will check the validity of the response anyway, and
                    689:         substitute this data.  The X11 server, however, will ignore this
                    690:         fake data and use whatever authentication mechanisms it was using
                    691:         otherwise for the local connection. */
                    692:       if (!got_data)
                    693:        {
1.9       dugsong   694:           u_int32_t rand = 0;
1.2       provos    695:
1.11      deraadt   696:          strlcpy(proto, "MIT-MAGIC-COOKIE-1", sizeof proto);
1.2       provos    697:           for (i = 0; i < 16; i++) {
                    698:             if (i % 4 == 0)
                    699:               rand = arc4random();
1.11      deraadt   700:             snprintf(data + 2 * i, sizeof data - 2 * i, "%02x", rand & 0xff);
1.2       provos    701:             rand >>= 8;
                    702:           }
1.1       deraadt   703:        }
                    704:
                    705:       /* Got local authentication reasonable information.  Request forwarding
                    706:         with authentication spoofing. */
                    707:       debug("Requesting X11 forwarding with authentication spoofing.");
1.2       provos    708:       x11_request_forwarding_with_spoofing(proto, data);
1.1       deraadt   709:
                    710:       /* Read response from the server. */
                    711:       type = packet_read(&plen);
                    712:       if (type == SSH_SMSG_SUCCESS)
                    713:        {
                    714:          forwarded = 1;
                    715:          interactive = 1;
                    716:        }
                    717:       else if (type == SSH_SMSG_FAILURE)
                    718:        log("Warning: Remote host denied X11 forwarding.");
                    719:       else
                    720:        packet_disconnect("Protocol error waiting for X11 forwarding");
                    721:     }
                    722:
                    723:   /* Tell the packet module whether this is an interactive session. */
                    724:   packet_set_interactive(interactive, options.keepalives);
                    725:
                    726:   /* Clear agent forwarding if we don\'t have an agent. */
                    727:   authfd = ssh_get_authentication_fd();
                    728:   if (authfd < 0)
                    729:     options.forward_agent = 0;
                    730:   else
                    731:     ssh_close_authentication_socket(authfd);
                    732:
                    733:   /* Request authentication agent forwarding if appropriate. */
                    734:   if (options.forward_agent)
                    735:     {
                    736:       debug("Requesting authentication agent forwarding.");
                    737:       auth_request_forwarding();
                    738:
                    739:       /* Read response from the server. */
                    740:       type = packet_read(&plen);
                    741:       packet_integrity_check(plen, 0, type);
                    742:       if (type != SSH_SMSG_SUCCESS)
                    743:        log("Warning: Remote host denied authentication agent forwarding.");
                    744:     }
                    745:
                    746:   /* Initiate local TCP/IP port forwardings. */
                    747:   for (i = 0; i < options.num_local_forwards; i++)
                    748:     {
                    749:       debug("Connections to local port %d forwarded to remote address %.200s:%d",
                    750:            options.local_forwards[i].port, options.local_forwards[i].host,
                    751:            options.local_forwards[i].host_port);
                    752:       channel_request_local_forwarding(options.local_forwards[i].port,
                    753:                                       options.local_forwards[i].host,
                    754:                                       options.local_forwards[i].host_port);
                    755:     }
                    756:
                    757:   /* Initiate remote TCP/IP port forwardings. */
                    758:   for (i = 0; i < options.num_remote_forwards; i++)
                    759:     {
                    760:       debug("Connections to remote port %d forwarded to local address %.200s:%d",
                    761:            options.remote_forwards[i].port, options.remote_forwards[i].host,
                    762:            options.remote_forwards[i].host_port);
                    763:       channel_request_remote_forwarding(options.remote_forwards[i].port,
                    764:                                        options.remote_forwards[i].host,
                    765:                                        options.remote_forwards[i].host_port);
                    766:     }
                    767:
                    768:   /* If a command was specified on the command line, execute the command now.
                    769:      Otherwise request the server to start a shell. */
                    770:   if (buffer_len(&command) > 0)
                    771:     {
                    772:       int len = buffer_len(&command);
                    773:       if (len > 900)
                    774:        len = 900;
                    775:       debug("Sending command: %.*s", len, buffer_ptr(&command));
                    776:       packet_start(SSH_CMSG_EXEC_CMD);
                    777:       packet_put_string(buffer_ptr(&command), buffer_len(&command));
                    778:       packet_send();
                    779:       packet_write_wait();
                    780:     }
                    781:   else
                    782:     {
                    783:       debug("Requesting shell.");
                    784:       packet_start(SSH_CMSG_EXEC_SHELL);
                    785:       packet_send();
                    786:       packet_write_wait();
                    787:     }
                    788:
                    789:   /* Enter the interactive session. */
                    790:   exit_status = client_loop(tty_flag, tty_flag ? options.escape_char : -1);
                    791:
                    792:   /* Close the connection to the remote host. */
                    793:   packet_close();
                    794:
                    795:   /* Exit with the status returned by the program on the remote side. */
                    796:   exit(exit_status);
                    797: }