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

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