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

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