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

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