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

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