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

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