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

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