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

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