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

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