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

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