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

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