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

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