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

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