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

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.50    ! markus     14: RCSID("$Id: ssh.c,v 1.49 2000/04/26 20:56:30 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);
                    362:                        } else {
                    363:                                /* SSH1 only */
                    364:                                options.cipher = cipher_number(optarg);
                    365:                                if (options.cipher == -1) {
                    366:                                        fprintf(stderr, "Unknown cipher type '%s'\n", optarg);
                    367:                                        exit(1);
                    368:                                }
1.31      markus    369:                        }
                    370:                        break;
                    371:                case 'p':
                    372:                        options.port = atoi(optarg);
                    373:                        break;
                    374:                case 'l':
                    375:                        options.user = optarg;
                    376:                        break;
                    377:                case 'R':
1.37      markus    378:                        if (sscanf(optarg, "%hu/%255[^/]/%hu", &fwd_port, buf,
                    379:                            &fwd_host_port) != 3 &&
                    380:                            sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf,
                    381:                            &fwd_host_port) != 3) {
1.31      markus    382:                                fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
                    383:                                usage();
                    384:                                /* NOTREACHED */
                    385:                        }
                    386:                        add_remote_forward(&options, fwd_port, buf, fwd_host_port);
                    387:                        break;
                    388:                case 'L':
1.37      markus    389:                        if (sscanf(optarg, "%hu/%255[^/]/%hu", &fwd_port, buf,
                    390:                            &fwd_host_port) != 3 &&
                    391:                            sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf,
                    392:                            &fwd_host_port) != 3) {
1.31      markus    393:                                fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
                    394:                                usage();
                    395:                                /* NOTREACHED */
                    396:                        }
                    397:                        add_local_forward(&options, fwd_port, buf, fwd_host_port);
                    398:                        break;
                    399:                case 'C':
                    400:                        options.compression = 1;
                    401:                        break;
1.45      markus    402:                case 'N':
                    403:                        no_shell_flag = 1;
                    404:                        no_tty_flag = 1;
                    405:                        break;
                    406:                case 'T':
                    407:                        no_tty_flag = 1;
                    408:                        break;
1.31      markus    409:                case 'o':
                    410:                        dummy = 1;
                    411:                        if (process_config_line(&options, host ? host : "", optarg,
                    412:                                         "command-line", 0, &dummy) != 0)
                    413:                                exit(1);
                    414:                        break;
                    415:                default:
                    416:                        usage();
1.1       deraadt   417:                }
1.31      markus    418:        }
                    419:
                    420:        /* Check that we got a host name. */
                    421:        if (!host)
                    422:                usage();
                    423:
1.49      markus    424:         OpenSSL_add_all_algorithms();
1.31      markus    425:
                    426:        /* Initialize the command to execute on remote host. */
                    427:        buffer_init(&command);
1.1       deraadt   428:
1.33      markus    429:        /*
                    430:         * Save the command to execute on the remote host in a buffer. There
                    431:         * is no limit on the length of the command, except by the maximum
                    432:         * packet size.  Also sets the tty flag if there is no command.
                    433:         */
1.31      markus    434:        if (optind == ac) {
                    435:                /* No command specified - execute shell on a tty. */
                    436:                tty_flag = 1;
                    437:        } else {
                    438:                /* A command has been specified.  Store it into the
                    439:                   buffer. */
                    440:                for (i = optind; i < ac; i++) {
                    441:                        if (i > optind)
                    442:                                buffer_append(&command, " ", 1);
                    443:                        buffer_append(&command, av[i], strlen(av[i]));
                    444:                }
                    445:        }
                    446:
                    447:        /* Cannot fork to background if no command. */
                    448:        if (fork_after_authentication_flag && buffer_len(&command) == 0)
                    449:                fatal("Cannot fork into background without a command to execute.");
                    450:
                    451:        /* Allocate a tty by default if no command specified. */
                    452:        if (buffer_len(&command) == 0)
                    453:                tty_flag = 1;
                    454:
                    455:        /* Do not allocate a tty if stdin is not a tty. */
                    456:        if (!isatty(fileno(stdin))) {
                    457:                if (tty_flag)
                    458:                        fprintf(stderr, "Pseudo-terminal will not be allocated because stdin is not a terminal.\n");
                    459:                tty_flag = 0;
                    460:        }
1.45      markus    461:        /* force */
                    462:        if (no_tty_flag)
                    463:                tty_flag = 0;
                    464:
1.31      markus    465:        /* Get user data. */
                    466:        pw = getpwuid(original_real_uid);
                    467:        if (!pw) {
                    468:                fprintf(stderr, "You don't exist, go away!\n");
                    469:                exit(1);
                    470:        }
                    471:        /* Take a copy of the returned structure. */
                    472:        memset(&pwcopy, 0, sizeof(pwcopy));
                    473:        pwcopy.pw_name = xstrdup(pw->pw_name);
                    474:        pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
                    475:        pwcopy.pw_uid = pw->pw_uid;
                    476:        pwcopy.pw_gid = pw->pw_gid;
                    477:        pwcopy.pw_dir = xstrdup(pw->pw_dir);
                    478:        pwcopy.pw_shell = xstrdup(pw->pw_shell);
                    479:        pw = &pwcopy;
                    480:
                    481:        /* Initialize "log" output.  Since we are the client all output
                    482:           actually goes to the terminal. */
                    483:        log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 0);
                    484:
                    485:        /* Read per-user configuration file. */
                    486:        snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_CONFFILE);
                    487:        read_config_file(buf, host, &options);
                    488:
                    489:        /* Read systemwide configuration file. */
                    490:        read_config_file(HOST_CONFIG_FILE, host, &options);
                    491:
                    492:        /* Fill configuration defaults. */
                    493:        fill_default_options(&options);
                    494:
                    495:        /* reinit */
                    496:        log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 0);
                    497:
1.49      markus    498:        /* check if RSA support exists */
                    499:        if ((options.protocol & SSH_PROTO_1) &&
                    500:            rsa_alive() == 0) {
                    501:                log("%s: no RSA support in libssl and libcrypto.  See ssl(8).",
                    502:                    __progname);
                    503:                log("Disabling protocol version 1");
                    504:                options.protocol &= ~ (SSH_PROTO_1|SSH_PROTO_1_PREFERRED);
                    505:        }
                    506:        if (! options.protocol & (SSH_PROTO_1|SSH_PROTO_2)) {
                    507:                fprintf(stderr, "%s: No protocol version available.\n",
                    508:                    __progname);
                    509:                exit(1);
                    510:        }
                    511:
1.31      markus    512:        if (options.user == NULL)
                    513:                options.user = xstrdup(pw->pw_name);
                    514:
                    515:        if (options.hostname != NULL)
                    516:                host = options.hostname;
                    517:
                    518:        /* Find canonic host name. */
                    519:        if (strchr(host, '.') == 0) {
1.37      markus    520:                struct addrinfo hints;
                    521:                struct addrinfo *ai = NULL;
                    522:                int errgai;
                    523:                memset(&hints, 0, sizeof(hints));
1.40      markus    524:                hints.ai_family = IPv4or6;
1.37      markus    525:                hints.ai_flags = AI_CANONNAME;
1.39      markus    526:                hints.ai_socktype = SOCK_STREAM;
1.37      markus    527:                errgai = getaddrinfo(host, NULL, &hints, &ai);
                    528:                if (errgai == 0) {
                    529:                        if (ai->ai_canonname != NULL)
                    530:                                host = xstrdup(ai->ai_canonname);
                    531:                        freeaddrinfo(ai);
1.31      markus    532:                }
                    533:        }
                    534:        /* Disable rhosts authentication if not running as root. */
                    535:        if (original_effective_uid != 0 || !options.use_privileged_port) {
                    536:                options.rhosts_authentication = 0;
                    537:                options.rhosts_rsa_authentication = 0;
                    538:        }
1.33      markus    539:        /*
                    540:         * If using rsh has been selected, exec it now (without trying
                    541:         * anything else).  Note that we must release privileges first.
                    542:         */
1.31      markus    543:        if (options.use_rsh) {
1.33      markus    544:                /*
                    545:                 * Restore our superuser privileges.  This must be done
                    546:                 * before permanently setting the uid.
                    547:                 */
1.31      markus    548:                restore_uid();
                    549:
                    550:                /* Switch to the original uid permanently. */
                    551:                permanently_set_uid(original_real_uid);
                    552:
                    553:                /* Execute rsh. */
                    554:                rsh_connect(host, options.user, &command);
                    555:                fatal("rsh_connect returned");
                    556:        }
                    557:        /* Restore our superuser privileges. */
                    558:        restore_uid();
                    559:
1.33      markus    560:        /*
                    561:         * Open a connection to the remote host.  This needs root privileges
                    562:         * if rhosts_{rsa_}authentication is enabled.
                    563:         */
1.31      markus    564:
                    565:        ok = ssh_connect(host, &hostaddr, options.port,
                    566:                         options.connection_attempts,
                    567:                         !options.rhosts_authentication &&
                    568:                         !options.rhosts_rsa_authentication,
                    569:                         original_real_uid,
                    570:                         options.proxy_command);
                    571:
1.33      markus    572:        /*
                    573:         * If we successfully made the connection, load the host private key
                    574:         * in case we will need it later for combined rsa-rhosts
                    575:         * authentication. This must be done before releasing extra
                    576:         * privileges, because the file is only readable by root.
                    577:         */
1.49      markus    578:        if (ok && (options.protocol & SSH_PROTO_1)) {
                    579:                Key k;
1.31      markus    580:                host_private_key = RSA_new();
1.49      markus    581:                k.type = KEY_RSA;
                    582:                k.rsa = host_private_key;
                    583:                if (load_private_key(HOST_KEY_FILE, "", &k, NULL))
1.31      markus    584:                        host_private_key_loaded = 1;
                    585:        }
1.33      markus    586:        /*
                    587:         * Get rid of any extra privileges that we may have.  We will no
                    588:         * longer need them.  Also, extra privileges could make it very hard
                    589:         * to read identity files and other non-world-readable files from the
                    590:         * user's home directory if it happens to be on a NFS volume where
                    591:         * root is mapped to nobody.
                    592:         */
                    593:
                    594:        /*
                    595:         * Note that some legacy systems need to postpone the following call
                    596:         * to permanently_set_uid() until the private hostkey is destroyed
                    597:         * with RSA_free().  Otherwise the calling user could ptrace() the
                    598:         * process, read the private hostkey and impersonate the host.
                    599:         * OpenBSD does not allow ptracing of setuid processes.
                    600:         */
1.31      markus    601:        permanently_set_uid(original_real_uid);
                    602:
1.33      markus    603:        /*
                    604:         * Now that we are back to our own permissions, create ~/.ssh
                    605:         * directory if it doesn\'t already exist.
                    606:         */
1.31      markus    607:        snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_DIR);
                    608:        if (stat(buf, &st) < 0)
                    609:                if (mkdir(buf, 0755) < 0)
                    610:                        error("Could not create directory '%.200s'.", buf);
                    611:
                    612:        /* Check if the connection failed, and try "rsh" if appropriate. */
                    613:        if (!ok) {
                    614:                if (options.port != 0)
1.35      markus    615:                        log("Secure connection to %.100s on port %hu refused%.100s.",
1.31      markus    616:                            host, options.port,
                    617:                            options.fallback_to_rsh ? "; reverting to insecure method" : "");
                    618:                else
                    619:                        log("Secure connection to %.100s refused%.100s.", host,
                    620:                            options.fallback_to_rsh ? "; reverting to insecure method" : "");
                    621:
                    622:                if (options.fallback_to_rsh) {
                    623:                        rsh_connect(host, options.user, &command);
                    624:                        fatal("rsh_connect returned");
                    625:                }
                    626:                exit(1);
                    627:        }
                    628:        /* Expand ~ in options.identity_files. */
1.49      markus    629:        /* XXX mem-leaks */
1.31      markus    630:        for (i = 0; i < options.num_identity_files; i++)
                    631:                options.identity_files[i] =
                    632:                        tilde_expand_filename(options.identity_files[i], original_real_uid);
1.49      markus    633:        for (i = 0; i < options.num_identity_files2; i++)
                    634:                options.identity_files2[i] =
                    635:                        tilde_expand_filename(options.identity_files2[i], original_real_uid);
1.31      markus    636:        /* Expand ~ in known host file names. */
                    637:        options.system_hostfile = tilde_expand_filename(options.system_hostfile,
1.49      markus    638:            original_real_uid);
1.31      markus    639:        options.user_hostfile = tilde_expand_filename(options.user_hostfile,
1.49      markus    640:            original_real_uid);
                    641:        options.system_hostfile2 = tilde_expand_filename(options.system_hostfile2,
                    642:            original_real_uid);
                    643:        options.user_hostfile2 = tilde_expand_filename(options.user_hostfile2,
                    644:            original_real_uid);
1.31      markus    645:
                    646:        /* Log into the remote system.  This never returns if the login fails. */
                    647:        ssh_login(host_private_key_loaded, host_private_key,
1.37      markus    648:                  host, (struct sockaddr *)&hostaddr, original_real_uid);
1.31      markus    649:
                    650:        /* We no longer need the host private key.  Clear it now. */
                    651:        if (host_private_key_loaded)
                    652:                RSA_free(host_private_key);     /* Destroys contents safely */
                    653:
1.45      markus    654:        exit_status = compat20 ? ssh_session2() : ssh_session();
                    655:        packet_close();
                    656:        return exit_status;
                    657: }
                    658:
1.50    ! markus    659: void
        !           660: x11_get_proto(char *proto, int proto_len, char *data, int data_len)
        !           661: {
        !           662:        char line[512];
        !           663:        FILE *f;
        !           664:        int got_data = 0, i;
        !           665:
        !           666: #ifdef XAUTH_PATH
        !           667:        /* Try to get Xauthority information for the display. */
        !           668:        snprintf(line, sizeof line, "%.100s list %.200s 2>/dev/null",
        !           669:                 XAUTH_PATH, getenv("DISPLAY"));
        !           670:        f = popen(line, "r");
        !           671:        if (f && fgets(line, sizeof(line), f) &&
        !           672:            sscanf(line, "%*s %s %s", proto, data) == 2)
        !           673:                got_data = 1;
        !           674:        if (f)
        !           675:                pclose(f);
        !           676: #endif /* XAUTH_PATH */
        !           677:        /*
        !           678:         * If we didn't get authentication data, just make up some
        !           679:         * data.  The forwarding code will check the validity of the
        !           680:         * response anyway, and substitute this data.  The X11
        !           681:         * server, however, will ignore this fake data and use
        !           682:         * whatever authentication mechanisms it was using otherwise
        !           683:         * for the local connection.
        !           684:         */
        !           685:        if (!got_data) {
        !           686:                u_int32_t rand = 0;
        !           687:
        !           688:                strlcpy(proto, "MIT-MAGIC-COOKIE-1", proto_len);
        !           689:                for (i = 0; i < 16; i++) {
        !           690:                        if (i % 4 == 0)
        !           691:                                rand = arc4random();
        !           692:                        snprintf(data + 2 * i, data_len - 2 * i, "%02x", rand & 0xff);
        !           693:                        rand >>= 8;
        !           694:                }
        !           695:        }
        !           696: }
        !           697:
1.45      markus    698: int
                    699: ssh_session(void)
                    700: {
                    701:        int type;
                    702:        int i;
                    703:        int plen;
                    704:        int interactive = 0;
                    705:        int have_tty = 0;
                    706:        struct winsize ws;
                    707:        int authfd;
                    708:        char *cp;
                    709:
1.31      markus    710:        /* Enable compression if requested. */
                    711:        if (options.compression) {
                    712:                debug("Requesting compression at level %d.", options.compression_level);
                    713:
                    714:                if (options.compression_level < 1 || options.compression_level > 9)
                    715:                        fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
                    716:
                    717:                /* Send the request. */
                    718:                packet_start(SSH_CMSG_REQUEST_COMPRESSION);
                    719:                packet_put_int(options.compression_level);
                    720:                packet_send();
                    721:                packet_write_wait();
                    722:                type = packet_read(&plen);
                    723:                if (type == SSH_SMSG_SUCCESS)
                    724:                        packet_start_compression(options.compression_level);
                    725:                else if (type == SSH_SMSG_FAILURE)
                    726:                        log("Warning: Remote host refused compression.");
                    727:                else
                    728:                        packet_disconnect("Protocol error waiting for compression response.");
                    729:        }
                    730:        /* Allocate a pseudo tty if appropriate. */
                    731:        if (tty_flag) {
                    732:                debug("Requesting pty.");
                    733:
                    734:                /* Start the packet. */
                    735:                packet_start(SSH_CMSG_REQUEST_PTY);
                    736:
                    737:                /* Store TERM in the packet.  There is no limit on the
                    738:                   length of the string. */
                    739:                cp = getenv("TERM");
                    740:                if (!cp)
                    741:                        cp = "";
                    742:                packet_put_string(cp, strlen(cp));
                    743:
                    744:                /* Store window size in the packet. */
                    745:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
                    746:                        memset(&ws, 0, sizeof(ws));
                    747:                packet_put_int(ws.ws_row);
                    748:                packet_put_int(ws.ws_col);
                    749:                packet_put_int(ws.ws_xpixel);
                    750:                packet_put_int(ws.ws_ypixel);
                    751:
                    752:                /* Store tty modes in the packet. */
                    753:                tty_make_modes(fileno(stdin));
                    754:
                    755:                /* Send the packet, and wait for it to leave. */
                    756:                packet_send();
                    757:                packet_write_wait();
                    758:
                    759:                /* Read response from the server. */
                    760:                type = packet_read(&plen);
1.43      markus    761:                if (type == SSH_SMSG_SUCCESS) {
1.31      markus    762:                        interactive = 1;
1.45      markus    763:                        have_tty = 1;
1.43      markus    764:                } else if (type == SSH_SMSG_FAILURE)
1.31      markus    765:                        log("Warning: Remote host failed or refused to allocate a pseudo tty.");
                    766:                else
                    767:                        packet_disconnect("Protocol error waiting for pty request response.");
                    768:        }
                    769:        /* Request X11 forwarding if enabled and DISPLAY is set. */
                    770:        if (options.forward_x11 && getenv("DISPLAY") != NULL) {
1.50    ! markus    771:                char proto[512], data[512];
        !           772:                /* Get reasonable local authentication information. */
        !           773:                x11_get_proto(proto, sizeof proto, data, sizeof data);
        !           774:                /* Request forwarding with authentication spoofing. */
1.31      markus    775:                debug("Requesting X11 forwarding with authentication spoofing.");
1.50    ! markus    776:                x11_request_forwarding_with_spoofing(0, proto, data);
1.31      markus    777:
                    778:                /* Read response from the server. */
                    779:                type = packet_read(&plen);
                    780:                if (type == SSH_SMSG_SUCCESS) {
                    781:                        interactive = 1;
1.50    ! markus    782:                } else if (type == SSH_SMSG_FAILURE) {
1.31      markus    783:                        log("Warning: Remote host denied X11 forwarding.");
1.50    ! markus    784:                } else {
1.31      markus    785:                        packet_disconnect("Protocol error waiting for X11 forwarding");
1.50    ! markus    786:                }
1.31      markus    787:        }
                    788:        /* Tell the packet module whether this is an interactive session. */
                    789:        packet_set_interactive(interactive, options.keepalives);
                    790:
                    791:        /* Clear agent forwarding if we don\'t have an agent. */
                    792:        authfd = ssh_get_authentication_socket();
                    793:        if (authfd < 0)
                    794:                options.forward_agent = 0;
                    795:        else
                    796:                ssh_close_authentication_socket(authfd);
                    797:
                    798:        /* Request authentication agent forwarding if appropriate. */
                    799:        if (options.forward_agent) {
                    800:                debug("Requesting authentication agent forwarding.");
                    801:                auth_request_forwarding();
                    802:
                    803:                /* Read response from the server. */
                    804:                type = packet_read(&plen);
                    805:                packet_integrity_check(plen, 0, type);
                    806:                if (type != SSH_SMSG_SUCCESS)
                    807:                        log("Warning: Remote host denied authentication agent forwarding.");
                    808:        }
                    809:        /* Initiate local TCP/IP port forwardings. */
                    810:        for (i = 0; i < options.num_local_forwards; i++) {
                    811:                debug("Connections to local port %d forwarded to remote address %.200s:%d",
                    812:                      options.local_forwards[i].port,
                    813:                      options.local_forwards[i].host,
                    814:                      options.local_forwards[i].host_port);
                    815:                channel_request_local_forwarding(options.local_forwards[i].port,
1.48      markus    816:                                                 options.local_forwards[i].host,
1.36      markus    817:                                                 options.local_forwards[i].host_port,
                    818:                                                 options.gateway_ports);
1.31      markus    819:        }
                    820:
                    821:        /* Initiate remote TCP/IP port forwardings. */
                    822:        for (i = 0; i < options.num_remote_forwards; i++) {
                    823:                debug("Connections to remote port %d forwarded to local address %.200s:%d",
                    824:                      options.remote_forwards[i].port,
                    825:                      options.remote_forwards[i].host,
                    826:                      options.remote_forwards[i].host_port);
                    827:                channel_request_remote_forwarding(options.remote_forwards[i].port,
                    828:                                                  options.remote_forwards[i].host,
1.48      markus    829:                                                  options.remote_forwards[i].host_port);
1.31      markus    830:        }
1.34      markus    831:
                    832:        /* If requested, let ssh continue in the background. */
1.48      markus    833:        if (fork_after_authentication_flag)
1.34      markus    834:                if (daemon(1, 1) < 0)
                    835:                        fatal("daemon() failed: %.200s", strerror(errno));
1.31      markus    836:
1.33      markus    837:        /*
                    838:         * If a command was specified on the command line, execute the
                    839:         * command now. Otherwise request the server to start a shell.
                    840:         */
1.31      markus    841:        if (buffer_len(&command) > 0) {
                    842:                int len = buffer_len(&command);
                    843:                if (len > 900)
                    844:                        len = 900;
                    845:                debug("Sending command: %.*s", len, buffer_ptr(&command));
                    846:                packet_start(SSH_CMSG_EXEC_CMD);
                    847:                packet_put_string(buffer_ptr(&command), buffer_len(&command));
                    848:                packet_send();
                    849:                packet_write_wait();
                    850:        } else {
                    851:                debug("Requesting shell.");
                    852:                packet_start(SSH_CMSG_EXEC_SHELL);
                    853:                packet_send();
                    854:                packet_write_wait();
                    855:        }
                    856:
                    857:        /* Enter the interactive session. */
1.45      markus    858:        return client_loop(have_tty, tty_flag ? options.escape_char : -1);
                    859: }
                    860:
                    861: void
                    862: init_local_fwd(void)
                    863: {
                    864:        int i;
                    865:        /* Initiate local TCP/IP port forwardings. */
                    866:        for (i = 0; i < options.num_local_forwards; i++) {
                    867:                debug("Connections to local port %d forwarded to remote address %.200s:%d",
                    868:                      options.local_forwards[i].port,
                    869:                      options.local_forwards[i].host,
                    870:                      options.local_forwards[i].host_port);
                    871:                channel_request_local_forwarding(options.local_forwards[i].port,
1.48      markus    872:                                                 options.local_forwards[i].host,
1.45      markus    873:                                                 options.local_forwards[i].host_port,
                    874:                                                 options.gateway_ports);
                    875:        }
                    876: }
                    877:
                    878: extern void client_set_session_ident(int id);
                    879:
                    880: void
                    881: client_init(int id, void *arg)
                    882: {
                    883:        int len;
                    884:        debug("client_init id %d arg %d", id, (int)arg);
1.31      markus    885:
1.45      markus    886:        if (no_shell_flag)
                    887:                goto done;
                    888:
                    889:        if (tty_flag) {
                    890:                struct winsize ws;
                    891:                char *cp;
                    892:                cp = getenv("TERM");
                    893:                if (!cp)
                    894:                        cp = "";
                    895:                /* Store window size in the packet. */
                    896:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
                    897:                        memset(&ws, 0, sizeof(ws));
                    898:
                    899:                channel_request_start(id, "pty-req", 0);
                    900:                packet_put_cstring(cp);
                    901:                packet_put_int(ws.ws_col);
                    902:                packet_put_int(ws.ws_row);
                    903:                packet_put_int(ws.ws_xpixel);
                    904:                packet_put_int(ws.ws_ypixel);
                    905:                packet_put_cstring("");         /* XXX: encode terminal modes */
                    906:                packet_send();
                    907:                /* XXX wait for reply */
                    908:        }
1.50    ! markus    909:        if (options.forward_x11 &&
        !           910:            getenv("DISPLAY") != NULL) {
        !           911:                char proto[512], data[512];
        !           912:                /* Get reasonable local authentication information. */
        !           913:                x11_get_proto(proto, sizeof proto, data, sizeof data);
        !           914:                /* Request forwarding with authentication spoofing. */
        !           915:                debug("Requesting X11 forwarding with authentication spoofing.");
        !           916:                x11_request_forwarding_with_spoofing(id, proto, data);
        !           917:                /* XXX wait for reply */
        !           918:        }
        !           919:
1.45      markus    920:        len = buffer_len(&command);
                    921:        if (len > 0) {
                    922:                if (len > 900)
                    923:                        len = 900;
                    924:                debug("Sending command: %.*s", len, buffer_ptr(&command));
                    925:                channel_request_start(id, "exec", 0);
                    926:                packet_put_string(buffer_ptr(&command), len);
                    927:                packet_send();
                    928:        } else {
                    929:                channel_request(id, "shell", 0);
                    930:        }
                    931:        /* channel_callback(id, SSH2_MSG_OPEN_CONFIGMATION, client_init, 0); */
                    932: done:
                    933:        /* register different callback, etc. XXX */
                    934:        client_set_session_ident(id);
                    935: }
                    936:
                    937: int
                    938: ssh_session2(void)
                    939: {
                    940:        int window, packetmax, id;
                    941:        int in  = dup(STDIN_FILENO);
                    942:        int out = dup(STDOUT_FILENO);
                    943:        int err = dup(STDERR_FILENO);
                    944:
                    945:        if (in < 0 || out < 0 || err < 0)
                    946:                fatal("dump in/out/err failed");
                    947:
                    948:        /* should be pre-session */
                    949:        init_local_fwd();
                    950:
                    951:        window = 32*1024;
                    952:        if (tty_flag) {
                    953:                packetmax = window/8;
                    954:        } else {
                    955:                window *= 2;
                    956:                packetmax = window/2;
                    957:        }
                    958:
                    959:        id = channel_new(
                    960:            "session", SSH_CHANNEL_OPENING, in, out, err,
                    961:            window, packetmax, CHAN_EXTENDED_WRITE, xstrdup("client-session"));
                    962:
                    963:
                    964:        channel_open(id);
                    965:        channel_register_callback(id, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, client_init, (void *)0);
1.31      markus    966:
1.45      markus    967:        return client_loop(tty_flag, tty_flag ? options.escape_char : -1);
1.1       deraadt   968: }