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

1.335   ! djm         1: /* $OpenBSD: ssh.c,v 1.334 2010/02/08 22:03:05 jmc Exp $ */
1.1       deraadt     2: /*
1.32      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
                      6:  * Ssh client program.  This program can be used to log into a remote machine.
                      7:  * The software supports strong authentication, encryption, and forwarding
                      8:  * of X11, TCP/IP, and authentication connections.
                      9:  *
1.64      deraadt    10:  * As far as I am concerned, the code I have written for this software
                     11:  * can be used freely for any purpose.  Any derived versions of this
                     12:  * software must be clearly marked as such, and if the derived work is
                     13:  * incompatible with the protocol description in the RFC file, it must be
                     14:  * called by a name other than "ssh" or "Secure Shell".
                     15:  *
                     16:  * Copyright (c) 1999 Niels Provos.  All rights reserved.
1.202     markus     17:  * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl.  All rights reserved.
1.64      deraadt    18:  *
                     19:  * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
                     20:  * in Canada (German citizen).
                     21:  *
                     22:  * Redistribution and use in source and binary forms, with or without
                     23:  * modification, are permitted provided that the following conditions
                     24:  * are met:
                     25:  * 1. Redistributions of source code must retain the above copyright
                     26:  *    notice, this list of conditions and the following disclaimer.
                     27:  * 2. Redistributions in binary form must reproduce the above copyright
                     28:  *    notice, this list of conditions and the following disclaimer in the
                     29:  *    documentation and/or other materials provided with the distribution.
                     30:  *
                     31:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     32:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     33:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     34:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     35:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     36:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     37:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     38:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     39:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     40:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.32      deraadt    41:  */
1.1       deraadt    42:
1.293     deraadt    43: #include <sys/types.h>
1.312     djm        44: #include <sys/ioctl.h>
1.326     dtucker    45: #include <sys/param.h>
1.312     djm        46: #include <sys/queue.h>
1.259     stevesk    47: #include <sys/resource.h>
1.280     stevesk    48: #include <sys/socket.h>
1.264     stevesk    49: #include <sys/stat.h>
1.312     djm        50: #include <sys/types.h>
                     51: #include <sys/time.h>
1.258     stevesk    52:
1.265     stevesk    53: #include <ctype.h>
1.285     stevesk    54: #include <errno.h>
1.281     stevesk    55: #include <fcntl.h>
1.286     stevesk    56: #include <netdb.h>
1.258     stevesk    57: #include <paths.h>
1.279     stevesk    58: #include <pwd.h>
1.263     stevesk    59: #include <signal.h>
1.287     stevesk    60: #include <stddef.h>
1.291     stevesk    61: #include <stdio.h>
1.290     stevesk    62: #include <stdlib.h>
1.289     stevesk    63: #include <string.h>
1.288     stevesk    64: #include <unistd.h>
1.49      markus     65:
                     66: #include <openssl/evp.h>
1.72      markus     67: #include <openssl/err.h>
1.1       deraadt    68:
1.293     deraadt    69: #include "xmalloc.h"
1.84      markus     70: #include "ssh.h"
                     71: #include "ssh1.h"
                     72: #include "ssh2.h"
                     73: #include "compat.h"
                     74: #include "cipher.h"
1.1       deraadt    75: #include "packet.h"
                     76: #include "buffer.h"
1.123     markus     77: #include "channels.h"
1.49      markus     78: #include "key.h"
1.58      markus     79: #include "authfd.h"
1.49      markus     80: #include "authfile.h"
1.83      markus     81: #include "pathnames.h"
1.214     djm        82: #include "dispatch.h"
1.81      markus     83: #include "clientloop.h"
1.84      markus     84: #include "log.h"
                     85: #include "readconf.h"
                     86: #include "sshconnect.h"
                     87: #include "misc.h"
1.95      markus     88: #include "kex.h"
                     89: #include "mac.h"
1.213     deraadt    90: #include "sshpty.h"
1.212     djm        91: #include "match.h"
1.214     djm        92: #include "msg.h"
1.225     dtucker    93: #include "uidswap.h"
1.327     andreas    94: #include "roaming.h"
1.278     stevesk    95: #include "version.h"
1.49      markus     96:
1.333     markus     97: #ifdef ENABLE_PKCS11
                     98: #include "ssh-pkcs11.h"
1.137     jakob      99: #endif
1.127     markus    100:
1.49      markus    101: extern char *__progname;
1.1       deraadt   102:
1.316     djm       103: /* Flag indicating whether debug mode is on.  May be set on the command line. */
1.1       deraadt   104: int debug_flag = 0;
                    105:
1.46      markus    106: /* Flag indicating whether a tty should be allocated */
1.1       deraadt   107: int tty_flag = 0;
1.79      markus    108: int no_tty_flag = 0;
                    109: int force_tty_flag = 0;
1.1       deraadt   110:
1.45      markus    111: /* don't exec a shell */
                    112: int no_shell_flag = 0;
                    113:
1.33      markus    114: /*
                    115:  * Flag indicating that nothing should be read from stdin.  This can be set
                    116:  * on the command line.
                    117:  */
1.1       deraadt   118: int stdin_null_flag = 0;
                    119:
1.33      markus    120: /*
                    121:  * Flag indicating that ssh should fork after authentication.  This is useful
1.172     deraadt   122:  * so that the passphrase can be entered manually, and then ssh goes to the
1.33      markus    123:  * background.
                    124:  */
1.1       deraadt   125: int fork_after_authentication_flag = 0;
                    126:
1.331     dtucker   127: /* forward stdio to remote host and port */
                    128: char *stdio_forward_host = NULL;
                    129: int stdio_forward_port = 0;
                    130:
1.33      markus    131: /*
                    132:  * General data structure for command line options and options configurable
                    133:  * in configuration files.  See readconf.h.
                    134:  */
1.1       deraadt   135: Options options;
                    136:
1.139     markus    137: /* optional user configfile */
                    138: char *config = NULL;
                    139:
1.33      markus    140: /*
                    141:  * Name of the host we are connecting to.  This is the name given on the
                    142:  * command line, or the HostName specified for the user-supplied name in a
                    143:  * configuration file.
                    144:  */
1.1       deraadt   145: char *host;
                    146:
1.22      provos    147: /* socket address the host resolves to */
1.37      markus    148: struct sockaddr_storage hostaddr;
1.1       deraadt   149:
1.112     markus    150: /* Private host keys. */
1.173     markus    151: Sensitive sensitive_data;
1.1       deraadt   152:
1.10      dugsong   153: /* Original real UID. */
                    154: uid_t original_real_uid;
1.177     markus    155: uid_t original_effective_uid;
1.1       deraadt   156:
1.45      markus    157: /* command to be executed */
                    158: Buffer command;
                    159:
1.85      djm       160: /* Should we execute a command or invoke a subsystem? */
                    161: int subsystem_flag = 0;
                    162:
1.170     markus    163: /* # of replies received for global requests */
1.315     djm       164: static int remote_forward_confirms_received = 0;
1.170     markus    165:
1.186     djm       166: /* pid of proxycommand child process */
                    167: pid_t proxy_command_pid = 0;
1.313     djm       168:
                    169: /* mux.c */
                    170: extern int muxserver_sock;
                    171: extern u_int muxclient_command;
                    172:
1.186     djm       173:
1.1       deraadt   174: /* Prints a help message to the user.  This function never returns. */
                    175:
1.126     itojun    176: static void
1.93      itojun    177: usage(void)
1.1       deraadt   178: {
1.208     markus    179:        fprintf(stderr,
1.321     jmc       180: "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
1.251     jmc       181: "           [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
1.334     jmc       182: "           [-I pkcs11] [-i identity_file]\n"
                    183: "           [-L [bind_address:]port:host:hostport]\n"
1.232     djm       184: "           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
1.233     jmc       185: "           [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
1.331     dtucker   186: "           [-W host:port] [-w local_tun[:remote_tun]]\n"
                    187: "           [user@]hostname [command]\n"
1.208     markus    188:        );
1.257     dtucker   189:        exit(255);
1.1       deraadt   190: }
                    191:
1.126     itojun    192: static int ssh_session(void);
                    193: static int ssh_session2(void);
                    194: static void load_public_identity_files(void);
1.312     djm       195:
                    196: /* from muxclient.c */
                    197: void muxclient(const char *);
                    198: void muxserver_listen(void);
1.45      markus    199:
1.32      deraadt   200: /*
                    201:  * Main program for the ssh client.
                    202:  */
1.2       provos    203: int
                    204: main(int ac, char **av)
1.1       deraadt   205: {
1.326     dtucker   206:        int i, r, opt, exit_status, use_syslog;
                    207:        char *p, *cp, *line, *argv0, buf[MAXPATHLEN];
1.31      markus    208:        struct stat st;
1.98      markus    209:        struct passwd *pw;
1.303     djm       210:        int dummy, timeout_ms;
1.144     stevesk   211:        extern int optind, optreset;
                    212:        extern char *optarg;
1.244     djm       213:        struct servent *sp;
1.232     djm       214:        Forward fwd;
1.250     djm       215:
                    216:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                    217:        sanitise_stdfd();
1.31      markus    218:
1.33      markus    219:        /*
                    220:         * Save the original real uid.  It will be needed later (uid-swapping
                    221:         * may clobber the real uid).
                    222:         */
1.31      markus    223:        original_real_uid = getuid();
                    224:        original_effective_uid = geteuid();
                    225:
1.184     stevesk   226:        /*
                    227:         * Use uid-swapping to give up root privileges for the duration of
                    228:         * option processing.  We will re-instantiate the rights when we are
                    229:         * ready to create the privileged port, and will permanently drop
                    230:         * them when the port has been created (actually, when the connection
                    231:         * has been made, as we may need to create the port several times).
                    232:         */
                    233:        PRIV_END;
                    234:
1.31      markus    235:        /* If we are installed setuid root be careful to not drop core. */
                    236:        if (original_real_uid != original_effective_uid) {
                    237:                struct rlimit rlim;
                    238:                rlim.rlim_cur = rlim.rlim_max = 0;
                    239:                if (setrlimit(RLIMIT_CORE, &rlim) < 0)
                    240:                        fatal("setrlimit failed: %.100s", strerror(errno));
1.1       deraadt   241:        }
1.107     markus    242:        /* Get user data. */
                    243:        pw = getpwuid(original_real_uid);
                    244:        if (!pw) {
1.191     itojun    245:                logit("You don't exist, go away!");
1.257     dtucker   246:                exit(255);
1.107     markus    247:        }
                    248:        /* Take a copy of the returned structure. */
                    249:        pw = pwcopy(pw);
1.31      markus    250:
1.33      markus    251:        /*
                    252:         * Set our umask to something reasonable, as some files are created
                    253:         * with the default umask.  This will make them world-readable but
                    254:         * writable only by the owner, which is ok for all files for which we
                    255:         * don't set the modes explicitly.
                    256:         */
1.31      markus    257:        umask(022);
                    258:
1.316     djm       259:        /*
                    260:         * Initialize option structure to indicate that no values have been
                    261:         * set.
                    262:         */
1.31      markus    263:        initialize_options(&options);
                    264:
                    265:        /* Parse command-line arguments. */
                    266:        host = NULL;
1.320     djm       267:        use_syslog = 0;
1.325     markus    268:        argv0 = av[0];
1.31      markus    269:
1.266     djm       270:  again:
1.316     djm       271:        while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
1.331     dtucker   272:            "ACD:F:I:KL:MNO:PR:S:TVw:W:XYy")) != -1) {
1.31      markus    273:                switch (opt) {
1.91      jakob     274:                case '1':
                    275:                        options.protocol = SSH_PROTO_1;
                    276:                        break;
1.47      markus    277:                case '2':
                    278:                        options.protocol = SSH_PROTO_2;
                    279:                        break;
1.37      markus    280:                case '4':
1.196     djm       281:                        options.address_family = AF_INET;
1.37      markus    282:                        break;
                    283:                case '6':
1.196     djm       284:                        options.address_family = AF_INET6;
1.37      markus    285:                        break;
1.31      markus    286:                case 'n':
                    287:                        stdin_null_flag = 1;
                    288:                        break;
                    289:                case 'f':
                    290:                        fork_after_authentication_flag = 1;
                    291:                        stdin_null_flag = 1;
                    292:                        break;
                    293:                case 'x':
                    294:                        options.forward_x11 = 0;
                    295:                        break;
                    296:                case 'X':
                    297:                        options.forward_x11 = 1;
                    298:                        break;
1.320     djm       299:                case 'y':
                    300:                        use_syslog = 1;
                    301:                        break;
1.202     markus    302:                case 'Y':
                    303:                        options.forward_x11 = 1;
                    304:                        options.forward_x11_trusted = 1;
                    305:                        break;
1.31      markus    306:                case 'g':
                    307:                        options.gateway_ports = 1;
                    308:                        break;
1.229     djm       309:                case 'O':
1.332     djm       310:                        if (stdio_forward_host != NULL)
                    311:                                fatal("Cannot specify multiplexing "
                    312:                                    "command with -W");
                    313:                        else if (muxclient_command != 0)
                    314:                                fatal("Multiplexing command already specified");
1.229     djm       315:                        if (strcmp(optarg, "check") == 0)
1.312     djm       316:                                muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
1.229     djm       317:                        else if (strcmp(optarg, "exit") == 0)
1.312     djm       318:                                muxclient_command = SSHMUX_COMMAND_TERMINATE;
1.229     djm       319:                        else
                    320:                                fatal("Invalid multiplex command.");
                    321:                        break;
1.183     stevesk   322:                case 'P':       /* deprecated */
1.31      markus    323:                        options.use_privileged_port = 0;
                    324:                        break;
                    325:                case 'a':
                    326:                        options.forward_agent = 0;
1.53      markus    327:                        break;
                    328:                case 'A':
                    329:                        options.forward_agent = 1;
1.31      markus    330:                        break;
                    331:                case 'k':
1.204     dtucker   332:                        options.gss_deleg_creds = 0;
1.297     djm       333:                        break;
                    334:                case 'K':
                    335:                        options.gss_authentication = 1;
                    336:                        options.gss_deleg_creds = 1;
1.31      markus    337:                        break;
                    338:                case 'i':
                    339:                        if (stat(optarg, &st) < 0) {
1.128     fgsch     340:                                fprintf(stderr, "Warning: Identity file %s "
1.231     otto      341:                                    "not accessible: %s.\n", optarg,
                    342:                                    strerror(errno));
1.31      markus    343:                                break;
                    344:                        }
1.128     fgsch     345:                        if (options.num_identity_files >=
                    346:                            SSH_MAX_IDENTITY_FILES)
                    347:                                fatal("Too many identity files specified "
                    348:                                    "(max %d)", SSH_MAX_IDENTITY_FILES);
                    349:                        options.identity_files[options.num_identity_files++] =
                    350:                            xstrdup(optarg);
1.31      markus    351:                        break;
1.127     markus    352:                case 'I':
1.333     markus    353: #ifdef ENABLE_PKCS11
                    354:                        options.pkcs11_provider = xstrdup(optarg);
1.137     jakob     355: #else
1.333     markus    356:                        fprintf(stderr, "no support for PKCS#11.\n");
1.137     jakob     357: #endif
1.127     markus    358:                        break;
1.31      markus    359:                case 't':
1.79      markus    360:                        if (tty_flag)
                    361:                                force_tty_flag = 1;
1.31      markus    362:                        tty_flag = 1;
                    363:                        break;
                    364:                case 'v':
1.197     markus    365:                        if (debug_flag == 0) {
1.66      markus    366:                                debug_flag = 1;
                    367:                                options.log_level = SYSLOG_LEVEL_DEBUG1;
1.197     markus    368:                        } else {
                    369:                                if (options.log_level < SYSLOG_LEVEL_DEBUG3)
                    370:                                        options.log_level++;
1.66      markus    371:                                break;
1.197     markus    372:                        }
1.227     deraadt   373:                        /* FALLTHROUGH */
1.31      markus    374:                case 'V':
1.209     markus    375:                        fprintf(stderr, "%s, %s\n",
                    376:                            SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
1.31      markus    377:                        if (opt == 'V')
                    378:                                exit(0);
                    379:                        break;
1.255     reyk      380:                case 'w':
1.256     reyk      381:                        if (options.tun_open == -1)
                    382:                                options.tun_open = SSH_TUNMODE_DEFAULT;
1.255     reyk      383:                        options.tun_local = a2tun(optarg, &options.tun_remote);
1.256     reyk      384:                        if (options.tun_local == SSH_TUNID_ERR) {
1.316     djm       385:                                fprintf(stderr,
                    386:                                    "Bad tun device '%s'\n", optarg);
1.257     dtucker   387:                                exit(255);
1.255     reyk      388:                        }
                    389:                        break;
1.331     dtucker   390:                case 'W':
1.332     djm       391:                        if (stdio_forward_host != NULL)
                    392:                                fatal("stdio forward already specified");
                    393:                        if (muxclient_command != 0)
                    394:                                fatal("Cannot specify stdio forward with -O");
1.331     dtucker   395:                        if (parse_forward(&fwd, optarg, 1, 0)) {
                    396:                                stdio_forward_host = fwd.listen_host;
                    397:                                stdio_forward_port = fwd.listen_port;
                    398:                                xfree(fwd.connect_host);
                    399:                        } else {
                    400:                                fprintf(stderr,
                    401:                                    "Bad stdio forwarding specification '%s'\n",
                    402:                                    optarg);
                    403:                                exit(255);
                    404:                        }
                    405:                        no_tty_flag = 1;
                    406:                        no_shell_flag = 1;
                    407:                        options.clear_forwardings = 1;
                    408:                        options.exit_on_forward_failure = 1;
                    409:                        break;
1.31      markus    410:                case 'q':
                    411:                        options.log_level = SYSLOG_LEVEL_QUIET;
                    412:                        break;
                    413:                case 'e':
                    414:                        if (optarg[0] == '^' && optarg[2] == 0 &&
1.128     fgsch     415:                            (u_char) optarg[1] >= 64 &&
                    416:                            (u_char) optarg[1] < 128)
1.78      markus    417:                                options.escape_char = (u_char) optarg[1] & 31;
1.31      markus    418:                        else if (strlen(optarg) == 1)
1.78      markus    419:                                options.escape_char = (u_char) optarg[0];
1.31      markus    420:                        else if (strcmp(optarg, "none") == 0)
1.119     stevesk   421:                                options.escape_char = SSH_ESCAPECHAR_NONE;
1.31      markus    422:                        else {
1.128     fgsch     423:                                fprintf(stderr, "Bad escape character '%s'.\n",
                    424:                                    optarg);
1.257     dtucker   425:                                exit(255);
1.31      markus    426:                        }
                    427:                        break;
                    428:                case 'c':
1.49      markus    429:                        if (ciphers_valid(optarg)) {
                    430:                                /* SSH2 only */
                    431:                                options.ciphers = xstrdup(optarg);
1.224     markus    432:                                options.cipher = SSH_CIPHER_INVALID;
1.49      markus    433:                        } else {
                    434:                                /* SSH1 only */
1.74      markus    435:                                options.cipher = cipher_number(optarg);
                    436:                                if (options.cipher == -1) {
1.128     fgsch     437:                                        fprintf(stderr,
                    438:                                            "Unknown cipher type '%s'\n",
                    439:                                            optarg);
1.257     dtucker   440:                                        exit(255);
1.49      markus    441:                                }
1.128     fgsch     442:                                if (options.cipher == SSH_CIPHER_3DES)
1.74      markus    443:                                        options.ciphers = "3des-cbc";
1.128     fgsch     444:                                else if (options.cipher == SSH_CIPHER_BLOWFISH)
1.74      markus    445:                                        options.ciphers = "blowfish-cbc";
1.128     fgsch     446:                                else
1.74      markus    447:                                        options.ciphers = (char *)-1;
1.95      markus    448:                        }
                    449:                        break;
                    450:                case 'm':
                    451:                        if (mac_valid(optarg))
                    452:                                options.macs = xstrdup(optarg);
                    453:                        else {
1.128     fgsch     454:                                fprintf(stderr, "Unknown mac type '%s'\n",
                    455:                                    optarg);
1.257     dtucker   456:                                exit(255);
1.31      markus    457:                        }
                    458:                        break;
1.214     djm       459:                case 'M':
1.242     djm       460:                        if (options.control_master == SSHCTL_MASTER_YES)
                    461:                                options.control_master = SSHCTL_MASTER_ASK;
                    462:                        else
                    463:                                options.control_master = SSHCTL_MASTER_YES;
1.214     djm       464:                        break;
1.31      markus    465:                case 'p':
1.113     stevesk   466:                        options.port = a2port(optarg);
1.323     djm       467:                        if (options.port <= 0) {
1.109     markus    468:                                fprintf(stderr, "Bad port '%s'\n", optarg);
1.257     dtucker   469:                                exit(255);
1.109     markus    470:                        }
1.31      markus    471:                        break;
                    472:                case 'l':
                    473:                        options.user = optarg;
                    474:                        break;
1.141     stevesk   475:
                    476:                case 'L':
1.324     djm       477:                        if (parse_forward(&fwd, optarg, 0, 0))
1.232     djm       478:                                add_local_forward(&options, &fwd);
                    479:                        else {
1.128     fgsch     480:                                fprintf(stderr,
1.232     djm       481:                                    "Bad local forwarding specification '%s'\n",
1.128     fgsch     482:                                    optarg);
1.257     dtucker   483:                                exit(255);
1.31      markus    484:                        }
1.232     djm       485:                        break;
                    486:
                    487:                case 'R':
1.324     djm       488:                        if (parse_forward(&fwd, optarg, 0, 1)) {
1.232     djm       489:                                add_remote_forward(&options, &fwd);
                    490:                        } else {
1.128     fgsch     491:                                fprintf(stderr,
1.232     djm       492:                                    "Bad remote forwarding specification "
                    493:                                    "'%s'\n", optarg);
1.257     dtucker   494:                                exit(255);
1.31      markus    495:                        }
                    496:                        break;
1.108     markus    497:
                    498:                case 'D':
1.324     djm       499:                        if (parse_forward(&fwd, optarg, 1, 0)) {
1.322     stevesk   500:                                add_local_forward(&options, &fwd);
1.232     djm       501:                        } else {
1.322     stevesk   502:                                fprintf(stderr,
                    503:                                    "Bad dynamic forwarding specification "
                    504:                                    "'%s'\n", optarg);
1.257     dtucker   505:                                exit(255);
1.109     markus    506:                        }
1.108     markus    507:                        break;
                    508:
1.31      markus    509:                case 'C':
                    510:                        options.compression = 1;
                    511:                        break;
1.45      markus    512:                case 'N':
                    513:                        no_shell_flag = 1;
                    514:                        no_tty_flag = 1;
                    515:                        break;
                    516:                case 'T':
                    517:                        no_tty_flag = 1;
                    518:                        break;
1.31      markus    519:                case 'o':
                    520:                        dummy = 1;
1.205     markus    521:                        line = xstrdup(optarg);
1.128     fgsch     522:                        if (process_config_line(&options, host ? host : "",
1.205     markus    523:                            line, "command-line", 0, &dummy) != 0)
1.257     dtucker   524:                                exit(255);
1.205     markus    525:                        xfree(line);
1.31      markus    526:                        break;
1.85      djm       527:                case 's':
                    528:                        subsystem_flag = 1;
1.117     markus    529:                        break;
1.214     djm       530:                case 'S':
                    531:                        if (options.control_path != NULL)
                    532:                                free(options.control_path);
                    533:                        options.control_path = xstrdup(optarg);
                    534:                        break;
1.117     markus    535:                case 'b':
                    536:                        options.bind_address = optarg;
1.85      djm       537:                        break;
1.139     markus    538:                case 'F':
                    539:                        config = optarg;
                    540:                        break;
1.31      markus    541:                default:
                    542:                        usage();
1.1       deraadt   543:                }
1.31      markus    544:        }
                    545:
1.128     fgsch     546:        ac -= optind;
                    547:        av += optind;
                    548:
1.329     guenther  549:        if (ac > 0 && !host) {
1.188     markus    550:                if (strrchr(*av, '@')) {
1.128     fgsch     551:                        p = xstrdup(*av);
1.188     markus    552:                        cp = strrchr(p, '@');
1.128     fgsch     553:                        if (cp == NULL || cp == p)
                    554:                                usage();
                    555:                        options.user = p;
                    556:                        *cp = '\0';
                    557:                        host = ++cp;
                    558:                } else
                    559:                        host = *av;
1.189     millert   560:                if (ac > 1) {
                    561:                        optind = optreset = 1;
1.128     fgsch     562:                        goto again;
                    563:                }
1.189     millert   564:                ac--, av++;
1.128     fgsch     565:        }
                    566:
1.31      markus    567:        /* Check that we got a host name. */
                    568:        if (!host)
                    569:                usage();
                    570:
1.54      markus    571:        SSLeay_add_all_algorithms();
1.72      markus    572:        ERR_load_crypto_strings();
1.31      markus    573:
                    574:        /* Initialize the command to execute on remote host. */
                    575:        buffer_init(&command);
1.1       deraadt   576:
1.33      markus    577:        /*
                    578:         * Save the command to execute on the remote host in a buffer. There
                    579:         * is no limit on the length of the command, except by the maximum
                    580:         * packet size.  Also sets the tty flag if there is no command.
                    581:         */
1.128     fgsch     582:        if (!ac) {
1.31      markus    583:                /* No command specified - execute shell on a tty. */
                    584:                tty_flag = 1;
1.85      djm       585:                if (subsystem_flag) {
1.128     fgsch     586:                        fprintf(stderr,
                    587:                            "You must specify a subsystem to invoke.\n");
1.85      djm       588:                        usage();
                    589:                }
1.31      markus    590:        } else {
1.128     fgsch     591:                /* A command has been specified.  Store it into the buffer. */
                    592:                for (i = 0; i < ac; i++) {
                    593:                        if (i)
1.31      markus    594:                                buffer_append(&command, " ", 1);
                    595:                        buffer_append(&command, av[i], strlen(av[i]));
                    596:                }
                    597:        }
                    598:
                    599:        /* Cannot fork to background if no command. */
1.316     djm       600:        if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
                    601:            !no_shell_flag)
                    602:                fatal("Cannot fork into background without a command "
                    603:                    "to execute.");
1.31      markus    604:
                    605:        /* Allocate a tty by default if no command specified. */
                    606:        if (buffer_len(&command) == 0)
                    607:                tty_flag = 1;
                    608:
1.180     deraadt   609:        /* Force no tty */
1.75      markus    610:        if (no_tty_flag)
                    611:                tty_flag = 0;
1.31      markus    612:        /* Do not allocate a tty if stdin is not a tty. */
1.236     djm       613:        if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
1.31      markus    614:                if (tty_flag)
1.316     djm       615:                        logit("Pseudo-terminal will not be allocated because "
                    616:                            "stdin is not a terminal.");
1.31      markus    617:                tty_flag = 0;
                    618:        }
1.45      markus    619:
1.101     markus    620:        /*
                    621:         * Initialize "log" output.  Since we are the client all output
                    622:         * actually goes to stderr.
                    623:         */
1.325     markus    624:        log_init(argv0,
1.316     djm       625:            options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
1.320     djm       626:            SYSLOG_FACILITY_USER, !use_syslog);
1.31      markus    627:
1.139     markus    628:        /*
                    629:         * Read per-user configuration file.  Ignore the system wide config
                    630:         * file if the user specifies a config file on the command line.
                    631:         */
                    632:        if (config != NULL) {
1.211     djm       633:                if (!read_config_file(config, host, &options, 0))
1.142     stevesk   634:                        fatal("Can't open user config file %.100s: "
                    635:                            "%.100s", config, strerror(errno));
1.295     stevesk   636:        } else {
1.326     dtucker   637:                r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
1.139     markus    638:                    _PATH_SSH_USER_CONFFILE);
1.326     dtucker   639:                if (r > 0 && (size_t)r < sizeof(buf))
                    640:                        (void)read_config_file(buf, host, &options, 1);
1.139     markus    641:
1.145     markus    642:                /* Read systemwide configuration file after use config. */
1.223     deraadt   643:                (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
1.210     djm       644:                    &options, 0);
1.139     markus    645:        }
1.31      markus    646:
                    647:        /* Fill configuration defaults. */
                    648:        fill_default_options(&options);
                    649:
1.196     djm       650:        channel_set_af(options.address_family);
                    651:
1.31      markus    652:        /* reinit */
1.325     markus    653:        log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
1.31      markus    654:
                    655:        if (options.user == NULL)
                    656:                options.user = xstrdup(pw->pw_name);
                    657:
1.317     dtucker   658:        /* Get default port if port has not been set. */
                    659:        if (options.port == 0) {
                    660:                sp = getservbyname(SSH_SERVICE_NAME, "tcp");
                    661:                options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
                    662:        }
                    663:
                    664:        if (options.local_command != NULL) {
                    665:                char thishost[NI_MAXHOST];
                    666:
                    667:                if (gethostname(thishost, sizeof(thishost)) == -1)
                    668:                        fatal("gethostname: %s", strerror(errno));
                    669:                snprintf(buf, sizeof(buf), "%d", options.port);
                    670:                debug3("expanding LocalCommand: %s", options.local_command);
                    671:                cp = options.local_command;
                    672:                options.local_command = percent_expand(cp, "d", pw->pw_dir,
                    673:                    "h", options.hostname? options.hostname : host,
                    674:                     "l", thishost, "n", host, "r", options.user, "p", buf,
                    675:                     "u", pw->pw_name, (char *)NULL);
                    676:                debug3("expanded LocalCommand: %s", options.local_command);
                    677:                xfree(cp);
                    678:        }
                    679:
1.31      markus    680:        if (options.hostname != NULL)
                    681:                host = options.hostname;
1.195     markus    682:
                    683:        /* force lowercase for hostkey matching */
                    684:        if (options.host_key_alias != NULL) {
                    685:                for (p = options.host_key_alias; *p; p++)
                    686:                        if (isupper(*p))
1.271     deraadt   687:                                *p = (char)tolower(*p);
1.246     djm       688:        }
                    689:
1.190     markus    690:        if (options.proxy_command != NULL &&
1.304     dtucker   691:            strcmp(options.proxy_command, "none") == 0) {
                    692:                xfree(options.proxy_command);
1.190     markus    693:                options.proxy_command = NULL;
1.304     dtucker   694:        }
1.245     djm       695:        if (options.control_path != NULL &&
1.304     dtucker   696:            strcmp(options.control_path, "none") == 0) {
                    697:                xfree(options.control_path);
1.245     djm       698:                options.control_path = NULL;
1.304     dtucker   699:        }
1.31      markus    700:
1.214     djm       701:        if (options.control_path != NULL) {
1.275     djm       702:                char thishost[NI_MAXHOST];
1.261     djm       703:
1.275     djm       704:                if (gethostname(thishost, sizeof(thishost)) == -1)
1.261     djm       705:                        fatal("gethostname: %s", strerror(errno));
1.241     djm       706:                snprintf(buf, sizeof(buf), "%d", options.port);
                    707:                cp = tilde_expand_filename(options.control_path,
                    708:                    original_real_uid);
1.304     dtucker   709:                xfree(options.control_path);
1.241     djm       710:                options.control_path = percent_expand(cp, "p", buf, "h", host,
1.275     djm       711:                    "r", options.user, "l", thishost, (char *)NULL);
1.241     djm       712:                xfree(cp);
1.214     djm       713:        }
1.312     djm       714:        if (muxclient_command != 0 && options.control_path == NULL)
1.240     djm       715:                fatal("No ControlPath specified for \"-O\" command");
1.242     djm       716:        if (options.control_path != NULL)
1.312     djm       717:                muxclient(options.control_path);
1.214     djm       718:
1.303     djm       719:        timeout_ms = options.connection_timeout * 1000;
                    720:
1.77      markus    721:        /* Open a connection to the remote host. */
1.203     djm       722:        if (ssh_connect(host, &hostaddr, options.port,
1.303     djm       723:            options.address_family, options.connection_attempts, &timeout_ms,
                    724:            options.tcp_keep_alive,
1.177     markus    725:            original_effective_uid == 0 && options.use_privileged_port,
1.179     markus    726:            options.proxy_command) != 0)
1.257     dtucker   727:                exit(255);
1.31      markus    728:
1.303     djm       729:        if (timeout_ms > 0)
                    730:                debug3("timeout: %d ms remain after connect", timeout_ms);
                    731:
1.33      markus    732:        /*
                    733:         * If we successfully made the connection, load the host private key
                    734:         * in case we will need it later for combined rsa-rhosts
                    735:         * authentication. This must be done before releasing extra
                    736:         * privileges, because the file is only readable by root.
1.174     markus    737:         * If we cannot access the private keys, load the public keys
                    738:         * instead and try to execute the ssh-keysign helper instead.
1.33      markus    739:         */
1.112     markus    740:        sensitive_data.nkeys = 0;
                    741:        sensitive_data.keys = NULL;
1.173     markus    742:        sensitive_data.external_keysign = 0;
1.178     markus    743:        if (options.rhosts_rsa_authentication ||
                    744:            options.hostbased_authentication) {
1.112     markus    745:                sensitive_data.nkeys = 3;
1.274     deraadt   746:                sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1.180     deraadt   747:                    sizeof(Key));
1.177     markus    748:
                    749:                PRIV_START;
1.112     markus    750:                sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1.276     dtucker   751:                    _PATH_HOST_KEY_FILE, "", NULL, NULL);
1.112     markus    752:                sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
1.276     dtucker   753:                    _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1.112     markus    754:                sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
1.276     dtucker   755:                    _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1.177     markus    756:                PRIV_END;
1.173     markus    757:
1.181     markus    758:                if (options.hostbased_authentication == 1 &&
                    759:                    sensitive_data.keys[0] == NULL &&
1.173     markus    760:                    sensitive_data.keys[1] == NULL &&
                    761:                    sensitive_data.keys[2] == NULL) {
                    762:                        sensitive_data.keys[1] = key_load_public(
                    763:                            _PATH_HOST_DSA_KEY_FILE, NULL);
                    764:                        sensitive_data.keys[2] = key_load_public(
                    765:                            _PATH_HOST_RSA_KEY_FILE, NULL);
                    766:                        sensitive_data.external_keysign = 1;
                    767:                }
1.31      markus    768:        }
1.33      markus    769:        /*
                    770:         * Get rid of any extra privileges that we may have.  We will no
                    771:         * longer need them.  Also, extra privileges could make it very hard
                    772:         * to read identity files and other non-world-readable files from the
                    773:         * user's home directory if it happens to be on a NFS volume where
                    774:         * root is mapped to nobody.
                    775:         */
1.225     dtucker   776:        if (original_effective_uid == 0) {
                    777:                PRIV_START;
                    778:                permanently_set_uid(pw);
                    779:        }
1.31      markus    780:
1.33      markus    781:        /*
                    782:         * Now that we are back to our own permissions, create ~/.ssh
1.254     djm       783:         * directory if it doesn't already exist.
1.33      markus    784:         */
1.326     dtucker   785:        r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1.316     djm       786:            strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1.326     dtucker   787:        if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0)
1.57      djm       788:                if (mkdir(buf, 0700) < 0)
1.31      markus    789:                        error("Could not create directory '%.200s'.", buf);
                    790:
1.104     markus    791:        /* load options.identity_files */
                    792:        load_public_identity_files();
                    793:
                    794:        /* Expand ~ in known host file names. */
                    795:        /* XXX mem-leaks: */
1.72      markus    796:        options.system_hostfile =
                    797:            tilde_expand_filename(options.system_hostfile, original_real_uid);
                    798:        options.user_hostfile =
                    799:            tilde_expand_filename(options.user_hostfile, original_real_uid);
                    800:        options.system_hostfile2 =
                    801:            tilde_expand_filename(options.system_hostfile2, original_real_uid);
                    802:        options.user_hostfile2 =
                    803:            tilde_expand_filename(options.user_hostfile2, original_real_uid);
1.149     markus    804:
                    805:        signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1.31      markus    806:
1.316     djm       807:        /* Log into the remote system.  Never returns if the login fails. */
1.303     djm       808:        ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
                    809:            pw, timeout_ms);
1.31      markus    810:
1.112     markus    811:        /* We no longer need the private host keys.  Clear them now. */
                    812:        if (sensitive_data.nkeys != 0) {
                    813:                for (i = 0; i < sensitive_data.nkeys; i++) {
                    814:                        if (sensitive_data.keys[i] != NULL) {
                    815:                                /* Destroys contents safely */
                    816:                                debug3("clear hostkey %d", i);
                    817:                                key_free(sensitive_data.keys[i]);
                    818:                                sensitive_data.keys[i] = NULL;
                    819:                        }
                    820:                }
                    821:                xfree(sensitive_data.keys);
1.134     markus    822:        }
                    823:        for (i = 0; i < options.num_identity_files; i++) {
                    824:                if (options.identity_files[i]) {
                    825:                        xfree(options.identity_files[i]);
                    826:                        options.identity_files[i] = NULL;
                    827:                }
                    828:                if (options.identity_keys[i]) {
                    829:                        key_free(options.identity_keys[i]);
                    830:                        options.identity_keys[i] = NULL;
                    831:                }
1.112     markus    832:        }
1.31      markus    833:
1.45      markus    834:        exit_status = compat20 ? ssh_session2() : ssh_session();
                    835:        packet_close();
1.186     djm       836:
1.312     djm       837:        if (options.control_path != NULL && muxserver_sock != -1)
1.214     djm       838:                unlink(options.control_path);
                    839:
1.186     djm       840:        /*
1.203     djm       841:         * Send SIGHUP to proxy command if used. We don't wait() in
1.186     djm       842:         * case it hangs and instead rely on init to reap the child
                    843:         */
                    844:        if (proxy_command_pid > 1)
                    845:                kill(proxy_command_pid, SIGHUP);
                    846:
1.45      markus    847:        return exit_status;
                    848: }
                    849:
1.315     djm       850: /* Callback for remote forward global requests */
                    851: static void
                    852: ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
                    853: {
                    854:        Forward *rfwd = (Forward *)ctxt;
                    855:
1.324     djm       856:        /* XXX verbose() on failure? */
1.315     djm       857:        debug("remote forward %s for: listen %d, connect %s:%d",
                    858:            type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
                    859:            rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
1.324     djm       860:        if (type == SSH2_MSG_REQUEST_SUCCESS && rfwd->listen_port == 0) {
                    861:                logit("Allocated port %u for remote forward to %s:%d",
                    862:                        packet_get_int(),
                    863:                        rfwd->connect_host, rfwd->connect_port);
                    864:        }
                    865:
1.315     djm       866:        if (type == SSH2_MSG_REQUEST_FAILURE) {
                    867:                if (options.exit_on_forward_failure)
                    868:                        fatal("Error: remote port forwarding failed for "
                    869:                            "listen port %d", rfwd->listen_port);
                    870:                else
                    871:                        logit("Warning: remote port forwarding failed for "
                    872:                            "listen port %d", rfwd->listen_port);
                    873:        }
1.318     djm       874:        if (++remote_forward_confirms_received == options.num_remote_forwards) {
1.315     djm       875:                debug("All remote forwarding requests processed");
1.318     djm       876:                if (fork_after_authentication_flag) {
                    877:                        fork_after_authentication_flag = 0;
                    878:                        if (daemon(1, 1) < 0)
                    879:                                fatal("daemon() failed: %.200s",
                    880:                                    strerror(errno));
                    881:                }
                    882:        }
1.315     djm       883: }
                    884:
1.126     itojun    885: static void
1.331     dtucker   886: client_cleanup_stdio_fwd(int id, void *arg)
                    887: {
                    888:        debug("stdio forwarding: done");
                    889:        cleanup_exit(0);
                    890: }
                    891:
                    892: static int
                    893: client_setup_stdio_fwd(const char *host_to_connect, u_short port_to_connect)
                    894: {
                    895:        Channel *c;
1.332     djm       896:        int in, out;
1.331     dtucker   897:
                    898:        debug3("client_setup_stdio_fwd %s:%d", host_to_connect,
                    899:            port_to_connect);
1.332     djm       900:
                    901:        in = dup(STDIN_FILENO);
                    902:        out = dup(STDOUT_FILENO);
                    903:        if (in < 0 || out < 0)
                    904:                fatal("channel_connect_stdio_fwd: dup() in/out failed");
                    905:
                    906:        if ((c = channel_connect_stdio_fwd(host_to_connect, port_to_connect,
                    907:            in, out)) == NULL)
1.331     dtucker   908:                return 0;
                    909:        channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
                    910:        return 1;
                    911: }
                    912:
                    913: static void
1.70      markus    914: ssh_init_forwarding(void)
                    915: {
1.86      markus    916:        int success = 0;
1.70      markus    917:        int i;
1.331     dtucker   918:
                    919:        if (stdio_forward_host != NULL) {
                    920:                if (!compat20) {
                    921:                        fatal("stdio forwarding require Protocol 2");
                    922:                }
                    923:                if (!client_setup_stdio_fwd(stdio_forward_host,
                    924:                    stdio_forward_port))
                    925:                        fatal("Failed to connect in stdio forward mode.");
                    926:        }
1.86      markus    927:
1.70      markus    928:        /* Initiate local TCP/IP port forwardings. */
                    929:        for (i = 0; i < options.num_local_forwards; i++) {
1.232     djm       930:                debug("Local connections to %.200s:%d forwarded to remote "
                    931:                    "address %.200s:%d",
1.234     deraadt   932:                    (options.local_forwards[i].listen_host == NULL) ?
                    933:                    (options.gateway_ports ? "*" : "LOCALHOST") :
1.232     djm       934:                    options.local_forwards[i].listen_host,
                    935:                    options.local_forwards[i].listen_port,
                    936:                    options.local_forwards[i].connect_host,
                    937:                    options.local_forwards[i].connect_port);
1.158     markus    938:                success += channel_setup_local_fwd_listener(
1.232     djm       939:                    options.local_forwards[i].listen_host,
                    940:                    options.local_forwards[i].listen_port,
                    941:                    options.local_forwards[i].connect_host,
                    942:                    options.local_forwards[i].connect_port,
1.70      markus    943:                    options.gateway_ports);
                    944:        }
1.283     markus    945:        if (i > 0 && success != i && options.exit_on_forward_failure)
                    946:                fatal("Could not request local forwarding.");
1.86      markus    947:        if (i > 0 && success == 0)
                    948:                error("Could not request local forwarding.");
1.70      markus    949:
                    950:        /* Initiate remote TCP/IP port forwardings. */
                    951:        for (i = 0; i < options.num_remote_forwards; i++) {
1.232     djm       952:                debug("Remote connections from %.200s:%d forwarded to "
                    953:                    "local address %.200s:%d",
1.248     djm       954:                    (options.remote_forwards[i].listen_host == NULL) ?
1.253     djm       955:                    "LOCALHOST" : options.remote_forwards[i].listen_host,
1.232     djm       956:                    options.remote_forwards[i].listen_port,
                    957:                    options.remote_forwards[i].connect_host,
                    958:                    options.remote_forwards[i].connect_port);
1.283     markus    959:                if (channel_request_remote_forwarding(
1.232     djm       960:                    options.remote_forwards[i].listen_host,
                    961:                    options.remote_forwards[i].listen_port,
                    962:                    options.remote_forwards[i].connect_host,
1.283     markus    963:                    options.remote_forwards[i].connect_port) < 0) {
                    964:                        if (options.exit_on_forward_failure)
                    965:                                fatal("Could not request remote forwarding.");
                    966:                        else
                    967:                                logit("Warning: Could not request remote "
                    968:                                    "forwarding.");
                    969:                }
1.315     djm       970:                client_register_global_confirm(ssh_confirm_remote_forward,
                    971:                    &options.remote_forwards[i]);
1.70      markus    972:        }
1.301     djm       973:
                    974:        /* Initiate tunnel forwarding. */
                    975:        if (options.tun_open != SSH_TUNMODE_NO) {
                    976:                if (client_request_tun_fwd(options.tun_open,
                    977:                    options.tun_local, options.tun_remote) == -1) {
                    978:                        if (options.exit_on_forward_failure)
                    979:                                fatal("Could not request tunnel forwarding.");
                    980:                        else
                    981:                                error("Could not request tunnel forwarding.");
                    982:                }
                    983:        }
1.70      markus    984: }
                    985:
1.126     itojun    986: static void
1.70      markus    987: check_agent_present(void)
                    988: {
                    989:        if (options.forward_agent) {
1.254     djm       990:                /* Clear agent forwarding if we don't have an agent. */
1.185     stevesk   991:                if (!ssh_agent_present())
1.70      markus    992:                        options.forward_agent = 0;
                    993:        }
                    994: }
                    995:
1.126     itojun    996: static int
1.45      markus    997: ssh_session(void)
                    998: {
                    999:        int type;
                   1000:        int interactive = 0;
                   1001:        int have_tty = 0;
                   1002:        struct winsize ws;
                   1003:        char *cp;
1.243     djm      1004:        const char *display;
1.45      markus   1005:
1.31      markus   1006:        /* Enable compression if requested. */
                   1007:        if (options.compression) {
1.316     djm      1008:                debug("Requesting compression at level %d.",
                   1009:                    options.compression_level);
1.31      markus   1010:
1.316     djm      1011:                if (options.compression_level < 1 ||
                   1012:                    options.compression_level > 9)
                   1013:                        fatal("Compression level must be from 1 (fast) to "
                   1014:                            "9 (slow, best).");
1.31      markus   1015:
                   1016:                /* Send the request. */
                   1017:                packet_start(SSH_CMSG_REQUEST_COMPRESSION);
                   1018:                packet_put_int(options.compression_level);
                   1019:                packet_send();
                   1020:                packet_write_wait();
1.156     markus   1021:                type = packet_read();
1.31      markus   1022:                if (type == SSH_SMSG_SUCCESS)
                   1023:                        packet_start_compression(options.compression_level);
                   1024:                else if (type == SSH_SMSG_FAILURE)
1.191     itojun   1025:                        logit("Warning: Remote host refused compression.");
1.31      markus   1026:                else
1.316     djm      1027:                        packet_disconnect("Protocol error waiting for "
                   1028:                            "compression response.");
1.31      markus   1029:        }
                   1030:        /* Allocate a pseudo tty if appropriate. */
                   1031:        if (tty_flag) {
                   1032:                debug("Requesting pty.");
                   1033:
                   1034:                /* Start the packet. */
                   1035:                packet_start(SSH_CMSG_REQUEST_PTY);
                   1036:
                   1037:                /* Store TERM in the packet.  There is no limit on the
                   1038:                   length of the string. */
                   1039:                cp = getenv("TERM");
                   1040:                if (!cp)
                   1041:                        cp = "";
1.124     markus   1042:                packet_put_cstring(cp);
1.31      markus   1043:
                   1044:                /* Store window size in the packet. */
                   1045:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
                   1046:                        memset(&ws, 0, sizeof(ws));
1.269     deraadt  1047:                packet_put_int((u_int)ws.ws_row);
                   1048:                packet_put_int((u_int)ws.ws_col);
                   1049:                packet_put_int((u_int)ws.ws_xpixel);
                   1050:                packet_put_int((u_int)ws.ws_ypixel);
1.31      markus   1051:
                   1052:                /* Store tty modes in the packet. */
1.115     stevesk  1053:                tty_make_modes(fileno(stdin), NULL);
1.31      markus   1054:
                   1055:                /* Send the packet, and wait for it to leave. */
                   1056:                packet_send();
                   1057:                packet_write_wait();
                   1058:
                   1059:                /* Read response from the server. */
1.156     markus   1060:                type = packet_read();
1.43      markus   1061:                if (type == SSH_SMSG_SUCCESS) {
1.31      markus   1062:                        interactive = 1;
1.45      markus   1063:                        have_tty = 1;
1.43      markus   1064:                } else if (type == SSH_SMSG_FAILURE)
1.316     djm      1065:                        logit("Warning: Remote host failed or refused to "
                   1066:                            "allocate a pseudo tty.");
1.31      markus   1067:                else
1.316     djm      1068:                        packet_disconnect("Protocol error waiting for pty "
                   1069:                            "request response.");
1.31      markus   1070:        }
                   1071:        /* Request X11 forwarding if enabled and DISPLAY is set. */
1.243     djm      1072:        display = getenv("DISPLAY");
                   1073:        if (options.forward_x11 && display != NULL) {
1.150     stevesk  1074:                char *proto, *data;
1.50      markus   1075:                /* Get reasonable local authentication information. */
1.243     djm      1076:                client_x11_get_proto(display, options.xauth_location,
                   1077:                    options.forward_x11_trusted, &proto, &data);
1.50      markus   1078:                /* Request forwarding with authentication spoofing. */
1.316     djm      1079:                debug("Requesting X11 forwarding with authentication "
                   1080:                    "spoofing.");
1.243     djm      1081:                x11_request_forwarding_with_spoofing(0, display, proto, data);
1.31      markus   1082:
                   1083:                /* Read response from the server. */
1.156     markus   1084:                type = packet_read();
1.31      markus   1085:                if (type == SSH_SMSG_SUCCESS) {
                   1086:                        interactive = 1;
1.50      markus   1087:                } else if (type == SSH_SMSG_FAILURE) {
1.191     itojun   1088:                        logit("Warning: Remote host denied X11 forwarding.");
1.50      markus   1089:                } else {
1.316     djm      1090:                        packet_disconnect("Protocol error waiting for X11 "
                   1091:                            "forwarding");
1.50      markus   1092:                }
1.31      markus   1093:        }
                   1094:        /* Tell the packet module whether this is an interactive session. */
1.80      markus   1095:        packet_set_interactive(interactive);
1.31      markus   1096:
                   1097:        /* Request authentication agent forwarding if appropriate. */
1.70      markus   1098:        check_agent_present();
                   1099:
1.31      markus   1100:        if (options.forward_agent) {
                   1101:                debug("Requesting authentication agent forwarding.");
                   1102:                auth_request_forwarding();
                   1103:
                   1104:                /* Read response from the server. */
1.156     markus   1105:                type = packet_read();
1.155     markus   1106:                packet_check_eom();
1.31      markus   1107:                if (type != SSH_SMSG_SUCCESS)
1.191     itojun   1108:                        logit("Warning: Remote host denied authentication agent forwarding.");
1.31      markus   1109:        }
                   1110:
1.70      markus   1111:        /* Initiate port forwardings. */
                   1112:        ssh_init_forwarding();
1.305     dtucker  1113:
                   1114:        /* Execute a local command */
                   1115:        if (options.local_command != NULL &&
                   1116:            options.permit_local_command)
                   1117:                ssh_local_cmd(options.local_command);
1.34      markus   1118:
1.318     djm      1119:        /*
                   1120:         * If requested and we are not interested in replies to remote
                   1121:         * forwarding requests, then let ssh continue in the background.
                   1122:         */
                   1123:        if (fork_after_authentication_flag &&
                   1124:            (!options.exit_on_forward_failure ||
                   1125:            options.num_remote_forwards == 0)) {
                   1126:                fork_after_authentication_flag = 0;
1.34      markus   1127:                if (daemon(1, 1) < 0)
                   1128:                        fatal("daemon() failed: %.200s", strerror(errno));
1.318     djm      1129:        }
1.31      markus   1130:
1.33      markus   1131:        /*
                   1132:         * If a command was specified on the command line, execute the
                   1133:         * command now. Otherwise request the server to start a shell.
                   1134:         */
1.31      markus   1135:        if (buffer_len(&command) > 0) {
                   1136:                int len = buffer_len(&command);
                   1137:                if (len > 900)
                   1138:                        len = 900;
1.316     djm      1139:                debug("Sending command: %.*s", len,
                   1140:                    (u_char *)buffer_ptr(&command));
1.31      markus   1141:                packet_start(SSH_CMSG_EXEC_CMD);
                   1142:                packet_put_string(buffer_ptr(&command), buffer_len(&command));
                   1143:                packet_send();
                   1144:                packet_write_wait();
                   1145:        } else {
                   1146:                debug("Requesting shell.");
                   1147:                packet_start(SSH_CMSG_EXEC_SHELL);
                   1148:                packet_send();
                   1149:                packet_write_wait();
                   1150:        }
                   1151:
                   1152:        /* Enter the interactive session. */
1.119     stevesk  1153:        return client_loop(have_tty, tty_flag ?
                   1154:            options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1.89      markus   1155: }
                   1156:
1.214     djm      1157: /* request pty/x11/agent/tcpfwd/shell for channel */
                   1158: static void
                   1159: ssh_session2_setup(int id, void *arg)
                   1160: {
1.215     djm      1161:        extern char **environ;
1.243     djm      1162:        const char *display;
                   1163:        int interactive = tty_flag;
1.215     djm      1164:
1.248     djm      1165:        display = getenv("DISPLAY");
1.243     djm      1166:        if (options.forward_x11 && display != NULL) {
1.150     stevesk  1167:                char *proto, *data;
1.50      markus   1168:                /* Get reasonable local authentication information. */
1.243     djm      1169:                client_x11_get_proto(display, options.xauth_location,
                   1170:                    options.forward_x11_trusted, &proto, &data);
1.50      markus   1171:                /* Request forwarding with authentication spoofing. */
1.316     djm      1172:                debug("Requesting X11 forwarding with authentication "
                   1173:                    "spoofing.");
1.243     djm      1174:                x11_request_forwarding_with_spoofing(id, display, proto, data);
1.80      markus   1175:                interactive = 1;
1.50      markus   1176:                /* XXX wait for reply */
                   1177:        }
                   1178:
1.70      markus   1179:        check_agent_present();
                   1180:        if (options.forward_agent) {
                   1181:                debug("Requesting authentication agent forwarding.");
                   1182:                channel_request_start(id, "auth-agent-req@openssh.com", 0);
                   1183:                packet_send();
1.212     djm      1184:        }
                   1185:
1.214     djm      1186:        client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1.311     djm      1187:            NULL, fileno(stdin), &command, environ);
1.90      markus   1188:
1.80      markus   1189:        packet_set_interactive(interactive);
1.45      markus   1190: }
                   1191:
1.143     markus   1192: /* open new channel for a session */
1.126     itojun   1193: static int
1.143     markus   1194: ssh_session2_open(void)
1.45      markus   1195: {
1.118     markus   1196:        Channel *c;
                   1197:        int window, packetmax, in, out, err;
1.60      markus   1198:
1.62      markus   1199:        if (stdin_null_flag) {
1.93      itojun   1200:                in = open(_PATH_DEVNULL, O_RDONLY);
1.62      markus   1201:        } else {
                   1202:                in = dup(STDIN_FILENO);
                   1203:        }
1.60      markus   1204:        out = dup(STDOUT_FILENO);
                   1205:        err = dup(STDERR_FILENO);
1.45      markus   1206:
                   1207:        if (in < 0 || out < 0 || err < 0)
1.62      markus   1208:                fatal("dup() in/out/err failed");
1.45      markus   1209:
1.69      markus   1210:        /* enable nonblocking unless tty */
                   1211:        if (!isatty(in))
                   1212:                set_nonblock(in);
                   1213:        if (!isatty(out))
                   1214:                set_nonblock(out);
                   1215:        if (!isatty(err))
                   1216:                set_nonblock(err);
                   1217:
1.65      markus   1218:        window = CHAN_SES_WINDOW_DEFAULT;
                   1219:        packetmax = CHAN_SES_PACKET_DEFAULT;
1.164     markus   1220:        if (tty_flag) {
                   1221:                window >>= 1;
                   1222:                packetmax >>= 1;
1.45      markus   1223:        }
1.118     markus   1224:        c = channel_new(
1.45      markus   1225:            "session", SSH_CHANNEL_OPENING, in, out, err,
1.65      markus   1226:            window, packetmax, CHAN_EXTENDED_WRITE,
1.192     markus   1227:            "client-session", /*nonblock*/0);
1.45      markus   1228:
1.143     markus   1229:        debug3("ssh_session2_open: channel_new: %d", c->self);
1.106     markus   1230:
1.122     markus   1231:        channel_send_open(c->self);
1.143     markus   1232:        if (!no_shell_flag)
1.310     djm      1233:                channel_register_open_confirm(c->self,
                   1234:                    ssh_session2_setup, NULL);
1.106     markus   1235:
1.118     markus   1236:        return c->self;
1.106     markus   1237: }
                   1238:
1.126     itojun   1239: static int
1.106     markus   1240: ssh_session2(void)
                   1241: {
1.143     markus   1242:        int id = -1;
1.106     markus   1243:
                   1244:        /* XXX should be pre-session */
                   1245:        ssh_init_forwarding();
                   1246:
1.143     markus   1247:        if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
                   1248:                id = ssh_session2_open();
1.314     djm      1249:
                   1250:        /* If we don't expect to open a new session, then disallow it */
1.319     markus   1251:        if (options.control_master == SSHCTL_MASTER_NO &&
                   1252:            (datafellows & SSH_NEW_OPENSSH)) {
1.314     djm      1253:                debug("Requesting no-more-sessions@openssh.com");
                   1254:                packet_start(SSH2_MSG_GLOBAL_REQUEST);
                   1255:                packet_put_cstring("no-more-sessions@openssh.com");
                   1256:                packet_put_char(0);
                   1257:                packet_send();
                   1258:        }
1.255     reyk     1259:
                   1260:        /* Execute a local command */
                   1261:        if (options.local_command != NULL &&
                   1262:            options.permit_local_command)
                   1263:                ssh_local_cmd(options.local_command);
1.301     djm      1264:
                   1265:        /* Start listening for multiplex clients */
1.312     djm      1266:        muxserver_listen();
1.106     markus   1267:
                   1268:        /* If requested, let ssh continue in the background. */
1.318     djm      1269:        if (fork_after_authentication_flag) {
                   1270:                fork_after_authentication_flag = 0;
1.106     markus   1271:                if (daemon(1, 1) < 0)
                   1272:                        fatal("daemon() failed: %.200s", strerror(errno));
1.318     djm      1273:        }
1.327     andreas  1274:
                   1275:        if (options.use_roaming)
                   1276:                request_roaming();
1.31      markus   1277:
1.119     stevesk  1278:        return client_loop(tty_flag, tty_flag ?
                   1279:            options.escape_char : SSH_ESCAPECHAR_NONE, id);
1.72      markus   1280: }
                   1281:
1.126     itojun   1282: static void
1.104     markus   1283: load_public_identity_files(void)
                   1284: {
1.275     djm      1285:        char *filename, *cp, thishost[NI_MAXHOST];
1.306     deraadt  1286:        char *pwdir = NULL, *pwname = NULL;
1.167     markus   1287:        int i = 0;
1.104     markus   1288:        Key *public;
1.275     djm      1289:        struct passwd *pw;
1.335   ! djm      1290:        u_int n_ids;
        !          1291:        char *identity_files[SSH_MAX_IDENTITY_FILES];
        !          1292:        Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1.333     markus   1293: #ifdef ENABLE_PKCS11
1.167     markus   1294:        Key **keys;
1.333     markus   1295:        int nkeys;
1.335   ! djm      1296: #endif /* PKCS11 */
1.104     markus   1297:
1.335   ! djm      1298:        n_ids = 0;
        !          1299:        bzero(identity_files, sizeof(identity_files));
        !          1300:        bzero(identity_keys, sizeof(identity_keys));
        !          1301:
        !          1302: #ifdef ENABLE_PKCS11
1.333     markus   1303:        if (options.pkcs11_provider != NULL &&
1.167     markus   1304:            options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1.333     markus   1305:            (pkcs11_init(!options.batch_mode) == 0) &&
                   1306:            (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
                   1307:            &keys)) > 0) {
                   1308:                for (i = 0; i < nkeys; i++) {
1.335   ! djm      1309:                        if (n_ids >= SSH_MAX_IDENTITY_FILES) {
        !          1310:                                key_free(keys[i]);
        !          1311:                                continue;
        !          1312:                        }
        !          1313:                        identity_keys[n_ids] = keys[i];
        !          1314:                        identity_files[n_ids] =
1.333     markus   1315:                            xstrdup(options.pkcs11_provider); /* XXX */
1.335   ! djm      1316:                        n_ids++;
1.167     markus   1317:                }
                   1318:                xfree(keys);
1.127     markus   1319:        }
1.333     markus   1320: #endif /* ENABLE_PKCS11 */
1.275     djm      1321:        if ((pw = getpwuid(original_real_uid)) == NULL)
                   1322:                fatal("load_public_identity_files: getpwuid failed");
1.307     dtucker  1323:        pwname = xstrdup(pw->pw_name);
                   1324:        pwdir = xstrdup(pw->pw_dir);
1.275     djm      1325:        if (gethostname(thishost, sizeof(thishost)) == -1)
                   1326:                fatal("load_public_identity_files: gethostname: %s",
                   1327:                    strerror(errno));
1.335   ! djm      1328:        for (i = 0; i < options.num_identity_files; i++) {
        !          1329:                if (n_ids >= SSH_MAX_IDENTITY_FILES) {
        !          1330:                        xfree(options.identity_files[i]);
        !          1331:                        continue;
        !          1332:                }
1.275     djm      1333:                cp = tilde_expand_filename(options.identity_files[i],
1.131     millert  1334:                    original_real_uid);
1.306     deraadt  1335:                filename = percent_expand(cp, "d", pwdir,
                   1336:                    "u", pwname, "l", thishost, "h", host,
1.275     djm      1337:                    "r", options.user, (char *)NULL);
                   1338:                xfree(cp);
1.131     millert  1339:                public = key_load_public(filename, NULL);
                   1340:                debug("identity file %s type %d", filename,
                   1341:                    public ? public->type : -1);
                   1342:                xfree(options.identity_files[i]);
1.335   ! djm      1343:                identity_files[n_ids] = filename;
        !          1344:                identity_keys[n_ids] = public;
        !          1345:
        !          1346:                if (++n_ids >= SSH_MAX_IDENTITY_FILES)
        !          1347:                        continue;
        !          1348:
        !          1349:                /* Try to add the certificate variant too */
        !          1350:                xasprintf(&cp, "%s-cert", filename);
        !          1351:                public = key_load_public(cp, NULL);
        !          1352:                debug("identity file %s type %d", cp,
        !          1353:                    public ? public->type : -1);
        !          1354:                if (public == NULL) {
        !          1355:                        xfree(cp);
        !          1356:                        continue;
        !          1357:                }
        !          1358:                if (!key_is_cert(public)) {
        !          1359:                        debug("%s: key %s type %s is not a certificate",
        !          1360:                            __func__, cp, key_type(public));
        !          1361:                        key_free(public);
        !          1362:                        xfree(cp);
        !          1363:                        continue;
        !          1364:                }
        !          1365:                identity_keys[n_ids] = public;
        !          1366:                /* point to the original path, most likely the private key */
        !          1367:                identity_files[n_ids] = xstrdup(filename);
        !          1368:                n_ids++;
        !          1369:        }
        !          1370:        options.num_identity_files = n_ids;
        !          1371:        memcpy(options.identity_files, identity_files, sizeof(identity_files));
        !          1372:        memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
        !          1373:
1.306     deraadt  1374:        bzero(pwname, strlen(pwname));
1.307     dtucker  1375:        xfree(pwname);
1.306     deraadt  1376:        bzero(pwdir, strlen(pwdir));
1.307     dtucker  1377:        xfree(pwdir);
1.214     djm      1378: }