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

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