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

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