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

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