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

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