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

1.402   ! markus      1: /* $OpenBSD: ssh.c,v 1.401 2014/02/26 20:18:37 djm 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.352     djm        52: #include <sys/wait.h>
1.258     stevesk    53:
1.265     stevesk    54: #include <ctype.h>
1.285     stevesk    55: #include <errno.h>
1.281     stevesk    56: #include <fcntl.h>
1.286     stevesk    57: #include <netdb.h>
1.258     stevesk    58: #include <paths.h>
1.279     stevesk    59: #include <pwd.h>
1.263     stevesk    60: #include <signal.h>
1.287     stevesk    61: #include <stddef.h>
1.291     stevesk    62: #include <stdio.h>
1.290     stevesk    63: #include <stdlib.h>
1.289     stevesk    64: #include <string.h>
1.288     stevesk    65: #include <unistd.h>
1.49      markus     66:
1.402   ! markus     67: #ifdef WITH_OPENSSL
1.49      markus     68: #include <openssl/evp.h>
1.72      markus     69: #include <openssl/err.h>
1.402   ! markus     70: #endif
1.1       deraadt    71:
1.293     deraadt    72: #include "xmalloc.h"
1.84      markus     73: #include "ssh.h"
                     74: #include "ssh1.h"
                     75: #include "ssh2.h"
1.341     djm        76: #include "canohost.h"
1.84      markus     77: #include "compat.h"
                     78: #include "cipher.h"
1.1       deraadt    79: #include "packet.h"
                     80: #include "buffer.h"
1.123     markus     81: #include "channels.h"
1.49      markus     82: #include "key.h"
1.58      markus     83: #include "authfd.h"
1.49      markus     84: #include "authfile.h"
1.83      markus     85: #include "pathnames.h"
1.214     djm        86: #include "dispatch.h"
1.81      markus     87: #include "clientloop.h"
1.84      markus     88: #include "log.h"
                     89: #include "readconf.h"
                     90: #include "sshconnect.h"
                     91: #include "misc.h"
1.95      markus     92: #include "kex.h"
                     93: #include "mac.h"
1.213     deraadt    94: #include "sshpty.h"
1.212     djm        95: #include "match.h"
1.214     djm        96: #include "msg.h"
1.225     dtucker    97: #include "uidswap.h"
1.327     andreas    98: #include "roaming.h"
1.278     stevesk    99: #include "version.h"
1.49      markus    100:
1.333     markus    101: #ifdef ENABLE_PKCS11
                    102: #include "ssh-pkcs11.h"
1.137     jakob     103: #endif
1.127     markus    104:
1.49      markus    105: extern char *__progname;
1.1       deraadt   106:
1.316     djm       107: /* Flag indicating whether debug mode is on.  May be set on the command line. */
1.1       deraadt   108: int debug_flag = 0;
                    109:
1.359     djm       110: /* Flag indicating whether a tty should be requested */
1.1       deraadt   111: int tty_flag = 0;
                    112:
1.45      markus    113: /* don't exec a shell */
                    114: int no_shell_flag = 0;
                    115:
1.33      markus    116: /*
                    117:  * Flag indicating that nothing should be read from stdin.  This can be set
                    118:  * on the command line.
                    119:  */
1.1       deraadt   120: int stdin_null_flag = 0;
                    121:
1.33      markus    122: /*
1.344     djm       123:  * Flag indicating that the current process should be backgrounded and
                    124:  * a new slave launched in the foreground for ControlPersist.
                    125:  */
                    126: int need_controlpersist_detach = 0;
                    127:
                    128: /* Copies of flags for ControlPersist foreground slave */
1.359     djm       129: int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty;
1.344     djm       130:
                    131: /*
1.33      markus    132:  * Flag indicating that ssh should fork after authentication.  This is useful
1.172     deraadt   133:  * so that the passphrase can be entered manually, and then ssh goes to the
1.33      markus    134:  * background.
                    135:  */
1.1       deraadt   136: int fork_after_authentication_flag = 0;
                    137:
1.331     dtucker   138: /* forward stdio to remote host and port */
                    139: char *stdio_forward_host = NULL;
                    140: int stdio_forward_port = 0;
                    141:
1.33      markus    142: /*
                    143:  * General data structure for command line options and options configurable
                    144:  * in configuration files.  See readconf.h.
                    145:  */
1.1       deraadt   146: Options options;
                    147:
1.139     markus    148: /* optional user configfile */
                    149: char *config = NULL;
                    150:
1.33      markus    151: /*
                    152:  * Name of the host we are connecting to.  This is the name given on the
                    153:  * command line, or the HostName specified for the user-supplied name in a
                    154:  * configuration file.
                    155:  */
1.1       deraadt   156: char *host;
                    157:
1.22      provos    158: /* socket address the host resolves to */
1.37      markus    159: struct sockaddr_storage hostaddr;
1.1       deraadt   160:
1.112     markus    161: /* Private host keys. */
1.173     markus    162: Sensitive sensitive_data;
1.1       deraadt   163:
1.10      dugsong   164: /* Original real UID. */
                    165: uid_t original_real_uid;
1.177     markus    166: uid_t original_effective_uid;
1.1       deraadt   167:
1.45      markus    168: /* command to be executed */
                    169: Buffer command;
                    170:
1.85      djm       171: /* Should we execute a command or invoke a subsystem? */
                    172: int subsystem_flag = 0;
                    173:
1.170     markus    174: /* # of replies received for global requests */
1.315     djm       175: static int remote_forward_confirms_received = 0;
1.170     markus    176:
1.313     djm       177: /* mux.c */
                    178: extern int muxserver_sock;
                    179: extern u_int muxclient_command;
                    180:
1.186     djm       181:
1.1       deraadt   182: /* Prints a help message to the user.  This function never returns. */
                    183:
1.126     itojun    184: static void
1.93      itojun    185: usage(void)
1.1       deraadt   186: {
1.208     markus    187:        fprintf(stderr,
1.321     jmc       188: "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
1.375     dtucker   189: "           [-D [bind_address:]port] [-E log_file] [-e escape_char]\n"
                    190: "           [-F configfile] [-I pkcs11] [-i identity_file]\n"
1.394     deraadt   191: "           [-L [bind_address:]port:host:hostport] [-l login_name] [-m mac_spec]\n"
1.395     jmc       192: "           [-O ctl_cmd] [-o option] [-p port]\n"
                    193: "           [-Q cipher | cipher-auth | mac | kex | key]\n"
                    194: "           [-R [bind_address:]port:host:hostport] [-S ctl_path] [-W host:port]\n"
                    195: "           [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
1.208     markus    196:        );
1.257     dtucker   197:        exit(255);
1.1       deraadt   198: }
                    199:
1.126     itojun    200: static int ssh_session(void);
                    201: static int ssh_session2(void);
                    202: static void load_public_identity_files(void);
1.352     djm       203: static void main_sigchld_handler(int);
1.312     djm       204:
                    205: /* from muxclient.c */
                    206: void muxclient(const char *);
                    207: void muxserver_listen(void);
1.45      markus    208:
1.361     djm       209: /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
                    210: static void
                    211: tilde_expand_paths(char **paths, u_int num_paths)
                    212: {
                    213:        u_int i;
                    214:        char *cp;
                    215:
                    216:        for (i = 0; i < num_paths; i++) {
                    217:                cp = tilde_expand_filename(paths[i], original_real_uid);
1.378     djm       218:                free(paths[i]);
1.361     djm       219:                paths[i] = cp;
                    220:        }
                    221: }
                    222:
1.400     djm       223: /*
                    224:  * Attempt to resolve a host name / port to a set of addresses and
                    225:  * optionally return any CNAMEs encountered along the way.
                    226:  * Returns NULL on failure.
                    227:  * NB. this function must operate with a options having undefined members.
                    228:  */
1.385     djm       229: static struct addrinfo *
1.400     djm       230: resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
1.385     djm       231: {
                    232:        char strport[NI_MAXSERV];
                    233:        struct addrinfo hints, *res;
                    234:        int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1;
                    235:
1.400     djm       236:        if (port <= 0)
                    237:                port = default_ssh_port();
                    238:
1.385     djm       239:        snprintf(strport, sizeof strport, "%u", port);
1.398     tedu      240:        memset(&hints, 0, sizeof(hints));
1.400     djm       241:        hints.ai_family = options.address_family == -1 ?
                    242:            AF_UNSPEC : options.address_family;
1.385     djm       243:        hints.ai_socktype = SOCK_STREAM;
                    244:        if (cname != NULL)
                    245:                hints.ai_flags = AI_CANONNAME;
                    246:        if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
                    247:                if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
                    248:                        loglevel = SYSLOG_LEVEL_ERROR;
                    249:                do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
                    250:                    __progname, name, ssh_gai_strerror(gaierr));
                    251:                return NULL;
                    252:        }
                    253:        if (cname != NULL && res->ai_canonname != NULL) {
                    254:                if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
                    255:                        error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
                    256:                            __func__, name,  res->ai_canonname, (u_long)clen);
                    257:                        if (clen > 0)
                    258:                                *cname = '\0';
                    259:                }
                    260:        }
                    261:        return res;
                    262: }
                    263:
                    264: /*
                    265:  * Check whether the cname is a permitted replacement for the hostname
                    266:  * and perform the replacement if it is.
1.400     djm       267:  * NB. this function must operate with a options having undefined members.
1.385     djm       268:  */
                    269: static int
                    270: check_follow_cname(char **namep, const char *cname)
                    271: {
                    272:        int i;
                    273:        struct allowed_cname *rule;
                    274:
                    275:        if (*cname == '\0' || options.num_permitted_cnames == 0 ||
                    276:            strcmp(*namep, cname) == 0)
                    277:                return 0;
1.386     djm       278:        if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
1.385     djm       279:                return 0;
                    280:        /*
1.386     djm       281:         * Don't attempt to canonicalize names that will be interpreted by
1.385     djm       282:         * a proxy unless the user specifically requests so.
                    283:         */
1.400     djm       284:        if (!option_clear_or_none(options.proxy_command) &&
1.386     djm       285:            options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
1.385     djm       286:                return 0;
                    287:        debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
                    288:        for (i = 0; i < options.num_permitted_cnames; i++) {
                    289:                rule = options.permitted_cnames + i;
                    290:                if (match_pattern_list(*namep, rule->source_list,
                    291:                    strlen(rule->source_list), 1) != 1 ||
                    292:                    match_pattern_list(cname, rule->target_list,
                    293:                    strlen(rule->target_list), 1) != 1)
                    294:                        continue;
1.386     djm       295:                verbose("Canonicalized DNS aliased hostname "
1.385     djm       296:                    "\"%s\" => \"%s\"", *namep, cname);
                    297:                free(*namep);
                    298:                *namep = xstrdup(cname);
                    299:                return 1;
                    300:        }
                    301:        return 0;
                    302: }
                    303:
                    304: /*
                    305:  * Attempt to resolve the supplied hostname after applying the user's
1.387     djm       306:  * canonicalization rules. Returns the address list for the host or NULL
                    307:  * if no name was found after canonicalization.
1.400     djm       308:  * NB. this function must operate with a options having undefined members.
1.385     djm       309:  */
                    310: static struct addrinfo *
1.400     djm       311: resolve_canonicalize(char **hostp, int port)
1.385     djm       312: {
                    313:        int i, ndots;
                    314:        char *cp, *fullhost, cname_target[NI_MAXHOST];
                    315:        struct addrinfo *addrs;
                    316:
1.386     djm       317:        if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
1.385     djm       318:                return NULL;
1.400     djm       319:
1.385     djm       320:        /*
1.386     djm       321:         * Don't attempt to canonicalize names that will be interpreted by
1.385     djm       322:         * a proxy unless the user specifically requests so.
                    323:         */
1.400     djm       324:        if (!option_clear_or_none(options.proxy_command) &&
1.386     djm       325:            options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
1.385     djm       326:                return NULL;
1.400     djm       327:
1.387     djm       328:        /* Don't apply canonicalization to sufficiently-qualified hostnames */
1.385     djm       329:        ndots = 0;
                    330:        for (cp = *hostp; *cp != '\0'; cp++) {
                    331:                if (*cp == '.')
                    332:                        ndots++;
                    333:        }
1.386     djm       334:        if (ndots > options.canonicalize_max_dots) {
                    335:                debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
                    336:                    __func__, *hostp, options.canonicalize_max_dots);
1.385     djm       337:                return NULL;
                    338:        }
                    339:        /* Attempt each supplied suffix */
                    340:        for (i = 0; i < options.num_canonical_domains; i++) {
                    341:                *cname_target = '\0';
                    342:                xasprintf(&fullhost, "%s.%s.", *hostp,
                    343:                    options.canonical_domains[i]);
1.400     djm       344:                debug3("%s: attempting \"%s\" => \"%s\"", __func__,
                    345:                    *hostp, fullhost);
                    346:                if ((addrs = resolve_host(fullhost, port, 0,
1.385     djm       347:                    cname_target, sizeof(cname_target))) == NULL) {
                    348:                        free(fullhost);
                    349:                        continue;
                    350:                }
                    351:                /* Remove trailing '.' */
                    352:                fullhost[strlen(fullhost) - 1] = '\0';
                    353:                /* Follow CNAME if requested */
                    354:                if (!check_follow_cname(&fullhost, cname_target)) {
1.386     djm       355:                        debug("Canonicalized hostname \"%s\" => \"%s\"",
1.385     djm       356:                            *hostp, fullhost);
                    357:                }
                    358:                free(*hostp);
                    359:                *hostp = fullhost;
                    360:                return addrs;
                    361:        }
1.386     djm       362:        if (!options.canonicalize_fallback_local)
1.400     djm       363:                fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
                    364:        debug2("%s: host %s not found in any suffix", __func__, *hostp);
1.385     djm       365:        return NULL;
                    366: }
                    367:
1.32      deraadt   368: /*
1.400     djm       369:  * Read per-user configuration file.  Ignore the system wide config
                    370:  * file if the user specifies a config file on the command line.
                    371:  */
                    372: static void
                    373: process_config_files(struct passwd *pw)
                    374: {
                    375:        char buf[MAXPATHLEN];
                    376:        int r;
                    377:
                    378:        if (config != NULL) {
                    379:                if (strcasecmp(config, "none") != 0 &&
                    380:                    !read_config_file(config, pw, host, &options,
                    381:                    SSHCONF_USERCONF))
                    382:                        fatal("Can't open user config file %.100s: "
                    383:                            "%.100s", config, strerror(errno));
                    384:        } else {
                    385:                r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
                    386:                    _PATH_SSH_USER_CONFFILE);
                    387:                if (r > 0 && (size_t)r < sizeof(buf))
                    388:                        (void)read_config_file(buf, pw, host, &options,
                    389:                             SSHCONF_CHECKPERM|SSHCONF_USERCONF);
                    390:
                    391:                /* Read systemwide configuration file after user config. */
                    392:                (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw, host,
                    393:                    &options, 0);
                    394:        }
                    395: }
                    396:
                    397: /*
1.32      deraadt   398:  * Main program for the ssh client.
                    399:  */
1.2       provos    400: int
                    401: main(int ac, char **av)
1.1       deraadt   402: {
1.326     dtucker   403:        int i, r, opt, exit_status, use_syslog;
1.375     dtucker   404:        char *p, *cp, *line, *argv0, buf[MAXPATHLEN], *host_arg, *logfile;
1.358     djm       405:        char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
1.385     djm       406:        char cname[NI_MAXHOST];
1.31      markus    407:        struct stat st;
1.98      markus    408:        struct passwd *pw;
1.382     djm       409:        int timeout_ms;
1.144     stevesk   410:        extern int optind, optreset;
                    411:        extern char *optarg;
1.232     djm       412:        Forward fwd;
1.385     djm       413:        struct addrinfo *addrs = NULL;
1.250     djm       414:
                    415:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                    416:        sanitise_stdfd();
1.31      markus    417:
1.33      markus    418:        /*
1.346     djm       419:         * Discard other fds that are hanging around. These can cause problem
                    420:         * with backgrounded ssh processes started by ControlPersist.
                    421:         */
                    422:        closefrom(STDERR_FILENO + 1);
                    423:
                    424:        /*
1.33      markus    425:         * Save the original real uid.  It will be needed later (uid-swapping
                    426:         * may clobber the real uid).
                    427:         */
1.31      markus    428:        original_real_uid = getuid();
                    429:        original_effective_uid = geteuid();
                    430:
1.184     stevesk   431:        /*
                    432:         * Use uid-swapping to give up root privileges for the duration of
                    433:         * option processing.  We will re-instantiate the rights when we are
                    434:         * ready to create the privileged port, and will permanently drop
                    435:         * them when the port has been created (actually, when the connection
                    436:         * has been made, as we may need to create the port several times).
                    437:         */
                    438:        PRIV_END;
                    439:
1.31      markus    440:        /* If we are installed setuid root be careful to not drop core. */
                    441:        if (original_real_uid != original_effective_uid) {
                    442:                struct rlimit rlim;
                    443:                rlim.rlim_cur = rlim.rlim_max = 0;
                    444:                if (setrlimit(RLIMIT_CORE, &rlim) < 0)
                    445:                        fatal("setrlimit failed: %.100s", strerror(errno));
1.1       deraadt   446:        }
1.107     markus    447:        /* Get user data. */
                    448:        pw = getpwuid(original_real_uid);
                    449:        if (!pw) {
1.380     djm       450:                logit("No user exists for uid %lu", (u_long)original_real_uid);
1.257     dtucker   451:                exit(255);
1.107     markus    452:        }
                    453:        /* Take a copy of the returned structure. */
                    454:        pw = pwcopy(pw);
1.31      markus    455:
1.33      markus    456:        /*
                    457:         * Set our umask to something reasonable, as some files are created
                    458:         * with the default umask.  This will make them world-readable but
                    459:         * writable only by the owner, which is ok for all files for which we
                    460:         * don't set the modes explicitly.
                    461:         */
1.31      markus    462:        umask(022);
                    463:
1.316     djm       464:        /*
                    465:         * Initialize option structure to indicate that no values have been
                    466:         * set.
                    467:         */
1.31      markus    468:        initialize_options(&options);
                    469:
                    470:        /* Parse command-line arguments. */
                    471:        host = NULL;
1.320     djm       472:        use_syslog = 0;
1.375     dtucker   473:        logfile = NULL;
1.325     markus    474:        argv0 = av[0];
1.31      markus    475:
1.266     djm       476:  again:
1.316     djm       477:        while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
1.376     djm       478:            "ACD:E:F:I:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
1.31      markus    479:                switch (opt) {
1.91      jakob     480:                case '1':
                    481:                        options.protocol = SSH_PROTO_1;
                    482:                        break;
1.47      markus    483:                case '2':
                    484:                        options.protocol = SSH_PROTO_2;
                    485:                        break;
1.37      markus    486:                case '4':
1.196     djm       487:                        options.address_family = AF_INET;
1.37      markus    488:                        break;
                    489:                case '6':
1.196     djm       490:                        options.address_family = AF_INET6;
1.37      markus    491:                        break;
1.31      markus    492:                case 'n':
                    493:                        stdin_null_flag = 1;
                    494:                        break;
                    495:                case 'f':
                    496:                        fork_after_authentication_flag = 1;
                    497:                        stdin_null_flag = 1;
                    498:                        break;
                    499:                case 'x':
                    500:                        options.forward_x11 = 0;
                    501:                        break;
                    502:                case 'X':
                    503:                        options.forward_x11 = 1;
                    504:                        break;
1.320     djm       505:                case 'y':
                    506:                        use_syslog = 1;
                    507:                        break;
1.375     dtucker   508:                case 'E':
                    509:                        logfile = xstrdup(optarg);
                    510:                        break;
1.202     markus    511:                case 'Y':
                    512:                        options.forward_x11 = 1;
                    513:                        options.forward_x11_trusted = 1;
                    514:                        break;
1.31      markus    515:                case 'g':
                    516:                        options.gateway_ports = 1;
                    517:                        break;
1.229     djm       518:                case 'O':
1.332     djm       519:                        if (stdio_forward_host != NULL)
                    520:                                fatal("Cannot specify multiplexing "
                    521:                                    "command with -W");
                    522:                        else if (muxclient_command != 0)
                    523:                                fatal("Multiplexing command already specified");
1.229     djm       524:                        if (strcmp(optarg, "check") == 0)
1.312     djm       525:                                muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
1.338     markus    526:                        else if (strcmp(optarg, "forward") == 0)
                    527:                                muxclient_command = SSHMUX_COMMAND_FORWARD;
1.229     djm       528:                        else if (strcmp(optarg, "exit") == 0)
1.312     djm       529:                                muxclient_command = SSHMUX_COMMAND_TERMINATE;
1.357     djm       530:                        else if (strcmp(optarg, "stop") == 0)
                    531:                                muxclient_command = SSHMUX_COMMAND_STOP;
1.365     djm       532:                        else if (strcmp(optarg, "cancel") == 0)
                    533:                                muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
1.229     djm       534:                        else
                    535:                                fatal("Invalid multiplex command.");
                    536:                        break;
1.183     stevesk   537:                case 'P':       /* deprecated */
1.31      markus    538:                        options.use_privileged_port = 0;
1.376     djm       539:                        break;
1.394     deraadt   540:                case 'Q':
1.376     djm       541:                        cp = NULL;
1.394     deraadt   542:                        if (strcmp(optarg, "cipher") == 0)
1.393     djm       543:                                cp = cipher_alg_list('\n', 0);
1.394     deraadt   544:                        else if (strcmp(optarg, "cipher-auth") == 0)
1.393     djm       545:                                cp = cipher_alg_list('\n', 1);
1.394     deraadt   546:                        else if (strcmp(optarg, "mac") == 0)
1.392     dtucker   547:                                cp = mac_alg_list('\n');
1.394     deraadt   548:                        else if (strcmp(optarg, "kex") == 0)
1.392     dtucker   549:                                cp = kex_alg_list('\n');
1.394     deraadt   550:                        else if (strcmp(optarg, "key") == 0)
1.396     markus    551:                                cp = key_alg_list(0, 0);
                    552:                        else if (strcmp(optarg, "key-cert") == 0)
                    553:                                cp = key_alg_list(1, 0);
                    554:                        else if (strcmp(optarg, "key-plain") == 0)
                    555:                                cp = key_alg_list(0, 1);
1.376     djm       556:                        if (cp == NULL)
                    557:                                fatal("Unsupported query \"%s\"", optarg);
                    558:                        printf("%s\n", cp);
                    559:                        free(cp);
                    560:                        exit(0);
1.31      markus    561:                        break;
                    562:                case 'a':
                    563:                        options.forward_agent = 0;
1.53      markus    564:                        break;
                    565:                case 'A':
                    566:                        options.forward_agent = 1;
1.31      markus    567:                        break;
                    568:                case 'k':
1.204     dtucker   569:                        options.gss_deleg_creds = 0;
1.297     djm       570:                        break;
                    571:                case 'K':
                    572:                        options.gss_authentication = 1;
                    573:                        options.gss_deleg_creds = 1;
1.31      markus    574:                        break;
                    575:                case 'i':
                    576:                        if (stat(optarg, &st) < 0) {
1.128     fgsch     577:                                fprintf(stderr, "Warning: Identity file %s "
1.231     otto      578:                                    "not accessible: %s.\n", optarg,
                    579:                                    strerror(errno));
1.31      markus    580:                                break;
                    581:                        }
1.371     dtucker   582:                        add_identity_file(&options, NULL, optarg, 1);
1.31      markus    583:                        break;
1.127     markus    584:                case 'I':
1.333     markus    585: #ifdef ENABLE_PKCS11
                    586:                        options.pkcs11_provider = xstrdup(optarg);
1.137     jakob     587: #else
1.333     markus    588:                        fprintf(stderr, "no support for PKCS#11.\n");
1.137     jakob     589: #endif
1.127     markus    590:                        break;
1.31      markus    591:                case 't':
1.359     djm       592:                        if (options.request_tty == REQUEST_TTY_YES)
                    593:                                options.request_tty = REQUEST_TTY_FORCE;
                    594:                        else
                    595:                                options.request_tty = REQUEST_TTY_YES;
1.31      markus    596:                        break;
                    597:                case 'v':
1.197     markus    598:                        if (debug_flag == 0) {
1.66      markus    599:                                debug_flag = 1;
                    600:                                options.log_level = SYSLOG_LEVEL_DEBUG1;
1.197     markus    601:                        } else {
                    602:                                if (options.log_level < SYSLOG_LEVEL_DEBUG3)
                    603:                                        options.log_level++;
                    604:                        }
1.375     dtucker   605:                        break;
1.31      markus    606:                case 'V':
1.209     markus    607:                        fprintf(stderr, "%s, %s\n",
1.402   ! markus    608:                            SSH_VERSION,
        !           609: #ifdef WITH_OPENSSL
        !           610:                            SSLeay_version(SSLEAY_VERSION)
        !           611: #else
        !           612:                            "without OpenSSL"
        !           613: #endif
        !           614:                        );
1.31      markus    615:                        if (opt == 'V')
                    616:                                exit(0);
                    617:                        break;
1.255     reyk      618:                case 'w':
1.256     reyk      619:                        if (options.tun_open == -1)
                    620:                                options.tun_open = SSH_TUNMODE_DEFAULT;
1.255     reyk      621:                        options.tun_local = a2tun(optarg, &options.tun_remote);
1.256     reyk      622:                        if (options.tun_local == SSH_TUNID_ERR) {
1.316     djm       623:                                fprintf(stderr,
                    624:                                    "Bad tun device '%s'\n", optarg);
1.257     dtucker   625:                                exit(255);
1.255     reyk      626:                        }
                    627:                        break;
1.331     dtucker   628:                case 'W':
1.332     djm       629:                        if (stdio_forward_host != NULL)
                    630:                                fatal("stdio forward already specified");
                    631:                        if (muxclient_command != 0)
                    632:                                fatal("Cannot specify stdio forward with -O");
1.331     dtucker   633:                        if (parse_forward(&fwd, optarg, 1, 0)) {
                    634:                                stdio_forward_host = fwd.listen_host;
                    635:                                stdio_forward_port = fwd.listen_port;
1.378     djm       636:                                free(fwd.connect_host);
1.331     dtucker   637:                        } else {
                    638:                                fprintf(stderr,
                    639:                                    "Bad stdio forwarding specification '%s'\n",
                    640:                                    optarg);
                    641:                                exit(255);
                    642:                        }
1.359     djm       643:                        options.request_tty = REQUEST_TTY_NO;
1.331     dtucker   644:                        no_shell_flag = 1;
                    645:                        options.clear_forwardings = 1;
                    646:                        options.exit_on_forward_failure = 1;
                    647:                        break;
1.31      markus    648:                case 'q':
                    649:                        options.log_level = SYSLOG_LEVEL_QUIET;
                    650:                        break;
                    651:                case 'e':
                    652:                        if (optarg[0] == '^' && optarg[2] == 0 &&
1.128     fgsch     653:                            (u_char) optarg[1] >= 64 &&
                    654:                            (u_char) optarg[1] < 128)
1.78      markus    655:                                options.escape_char = (u_char) optarg[1] & 31;
1.31      markus    656:                        else if (strlen(optarg) == 1)
1.78      markus    657:                                options.escape_char = (u_char) optarg[0];
1.31      markus    658:                        else if (strcmp(optarg, "none") == 0)
1.119     stevesk   659:                                options.escape_char = SSH_ESCAPECHAR_NONE;
1.31      markus    660:                        else {
1.128     fgsch     661:                                fprintf(stderr, "Bad escape character '%s'.\n",
                    662:                                    optarg);
1.257     dtucker   663:                                exit(255);
1.31      markus    664:                        }
                    665:                        break;
                    666:                case 'c':
1.49      markus    667:                        if (ciphers_valid(optarg)) {
                    668:                                /* SSH2 only */
                    669:                                options.ciphers = xstrdup(optarg);
1.224     markus    670:                                options.cipher = SSH_CIPHER_INVALID;
1.49      markus    671:                        } else {
                    672:                                /* SSH1 only */
1.74      markus    673:                                options.cipher = cipher_number(optarg);
                    674:                                if (options.cipher == -1) {
1.128     fgsch     675:                                        fprintf(stderr,
                    676:                                            "Unknown cipher type '%s'\n",
                    677:                                            optarg);
1.257     dtucker   678:                                        exit(255);
1.49      markus    679:                                }
1.128     fgsch     680:                                if (options.cipher == SSH_CIPHER_3DES)
1.74      markus    681:                                        options.ciphers = "3des-cbc";
1.128     fgsch     682:                                else if (options.cipher == SSH_CIPHER_BLOWFISH)
1.74      markus    683:                                        options.ciphers = "blowfish-cbc";
1.128     fgsch     684:                                else
1.74      markus    685:                                        options.ciphers = (char *)-1;
1.95      markus    686:                        }
                    687:                        break;
                    688:                case 'm':
                    689:                        if (mac_valid(optarg))
                    690:                                options.macs = xstrdup(optarg);
                    691:                        else {
1.128     fgsch     692:                                fprintf(stderr, "Unknown mac type '%s'\n",
                    693:                                    optarg);
1.257     dtucker   694:                                exit(255);
1.31      markus    695:                        }
                    696:                        break;
1.214     djm       697:                case 'M':
1.242     djm       698:                        if (options.control_master == SSHCTL_MASTER_YES)
                    699:                                options.control_master = SSHCTL_MASTER_ASK;
                    700:                        else
                    701:                                options.control_master = SSHCTL_MASTER_YES;
1.214     djm       702:                        break;
1.31      markus    703:                case 'p':
1.113     stevesk   704:                        options.port = a2port(optarg);
1.323     djm       705:                        if (options.port <= 0) {
1.109     markus    706:                                fprintf(stderr, "Bad port '%s'\n", optarg);
1.257     dtucker   707:                                exit(255);
1.109     markus    708:                        }
1.31      markus    709:                        break;
                    710:                case 'l':
                    711:                        options.user = optarg;
                    712:                        break;
1.141     stevesk   713:
                    714:                case 'L':
1.324     djm       715:                        if (parse_forward(&fwd, optarg, 0, 0))
1.232     djm       716:                                add_local_forward(&options, &fwd);
                    717:                        else {
1.128     fgsch     718:                                fprintf(stderr,
1.232     djm       719:                                    "Bad local forwarding specification '%s'\n",
1.128     fgsch     720:                                    optarg);
1.257     dtucker   721:                                exit(255);
1.31      markus    722:                        }
1.232     djm       723:                        break;
                    724:
                    725:                case 'R':
1.324     djm       726:                        if (parse_forward(&fwd, optarg, 0, 1)) {
1.232     djm       727:                                add_remote_forward(&options, &fwd);
                    728:                        } else {
1.128     fgsch     729:                                fprintf(stderr,
1.232     djm       730:                                    "Bad remote forwarding specification "
                    731:                                    "'%s'\n", optarg);
1.257     dtucker   732:                                exit(255);
1.31      markus    733:                        }
                    734:                        break;
1.108     markus    735:
                    736:                case 'D':
1.324     djm       737:                        if (parse_forward(&fwd, optarg, 1, 0)) {
1.322     stevesk   738:                                add_local_forward(&options, &fwd);
1.232     djm       739:                        } else {
1.322     stevesk   740:                                fprintf(stderr,
                    741:                                    "Bad dynamic forwarding specification "
                    742:                                    "'%s'\n", optarg);
1.257     dtucker   743:                                exit(255);
1.109     markus    744:                        }
1.108     markus    745:                        break;
                    746:
1.31      markus    747:                case 'C':
                    748:                        options.compression = 1;
                    749:                        break;
1.45      markus    750:                case 'N':
                    751:                        no_shell_flag = 1;
1.359     djm       752:                        options.request_tty = REQUEST_TTY_NO;
1.45      markus    753:                        break;
                    754:                case 'T':
1.359     djm       755:                        options.request_tty = REQUEST_TTY_NO;
1.45      markus    756:                        break;
1.31      markus    757:                case 'o':
1.205     markus    758:                        line = xstrdup(optarg);
1.382     djm       759:                        if (process_config_line(&options, pw, host ? host : "",
                    760:                            line, "command-line", 0, NULL, SSHCONF_USERCONF)
1.372     dtucker   761:                            != 0)
1.257     dtucker   762:                                exit(255);
1.378     djm       763:                        free(line);
1.31      markus    764:                        break;
1.85      djm       765:                case 's':
                    766:                        subsystem_flag = 1;
1.117     markus    767:                        break;
1.214     djm       768:                case 'S':
                    769:                        if (options.control_path != NULL)
                    770:                                free(options.control_path);
                    771:                        options.control_path = xstrdup(optarg);
                    772:                        break;
1.117     markus    773:                case 'b':
                    774:                        options.bind_address = optarg;
1.85      djm       775:                        break;
1.139     markus    776:                case 'F':
                    777:                        config = optarg;
                    778:                        break;
1.31      markus    779:                default:
                    780:                        usage();
1.1       deraadt   781:                }
1.31      markus    782:        }
                    783:
1.128     fgsch     784:        ac -= optind;
                    785:        av += optind;
                    786:
1.329     guenther  787:        if (ac > 0 && !host) {
1.188     markus    788:                if (strrchr(*av, '@')) {
1.128     fgsch     789:                        p = xstrdup(*av);
1.188     markus    790:                        cp = strrchr(p, '@');
1.128     fgsch     791:                        if (cp == NULL || cp == p)
                    792:                                usage();
                    793:                        options.user = p;
                    794:                        *cp = '\0';
1.385     djm       795:                        host = xstrdup(++cp);
1.128     fgsch     796:                } else
1.385     djm       797:                        host = xstrdup(*av);
1.189     millert   798:                if (ac > 1) {
                    799:                        optind = optreset = 1;
1.128     fgsch     800:                        goto again;
                    801:                }
1.189     millert   802:                ac--, av++;
1.128     fgsch     803:        }
                    804:
1.31      markus    805:        /* Check that we got a host name. */
                    806:        if (!host)
                    807:                usage();
                    808:
1.385     djm       809:        host_arg = xstrdup(host);
                    810:
1.402   ! markus    811: #ifdef WITH_OPENSSL
1.350     djm       812:        OpenSSL_add_all_algorithms();
1.72      markus    813:        ERR_load_crypto_strings();
1.402   ! markus    814: #endif
1.31      markus    815:
                    816:        /* Initialize the command to execute on remote host. */
                    817:        buffer_init(&command);
1.1       deraadt   818:
1.33      markus    819:        /*
                    820:         * Save the command to execute on the remote host in a buffer. There
                    821:         * is no limit on the length of the command, except by the maximum
                    822:         * packet size.  Also sets the tty flag if there is no command.
                    823:         */
1.128     fgsch     824:        if (!ac) {
1.31      markus    825:                /* No command specified - execute shell on a tty. */
1.85      djm       826:                if (subsystem_flag) {
1.128     fgsch     827:                        fprintf(stderr,
                    828:                            "You must specify a subsystem to invoke.\n");
1.85      djm       829:                        usage();
                    830:                }
1.31      markus    831:        } else {
1.128     fgsch     832:                /* A command has been specified.  Store it into the buffer. */
                    833:                for (i = 0; i < ac; i++) {
                    834:                        if (i)
1.31      markus    835:                                buffer_append(&command, " ", 1);
                    836:                        buffer_append(&command, av[i], strlen(av[i]));
                    837:                }
                    838:        }
                    839:
                    840:        /* Cannot fork to background if no command. */
1.316     djm       841:        if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
                    842:            !no_shell_flag)
                    843:                fatal("Cannot fork into background without a command "
                    844:                    "to execute.");
1.31      markus    845:
1.101     markus    846:        /*
                    847:         * Initialize "log" output.  Since we are the client all output
1.375     dtucker   848:         * goes to stderr unless otherwise specified by -y or -E.
1.101     markus    849:         */
1.375     dtucker   850:        if (use_syslog && logfile != NULL)
                    851:                fatal("Can't specify both -y and -E");
                    852:        if (logfile != NULL) {
                    853:                log_redirect_stderr_to(logfile);
1.378     djm       854:                free(logfile);
1.375     dtucker   855:        }
1.325     markus    856:        log_init(argv0,
1.316     djm       857:            options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
1.320     djm       858:            SYSLOG_FACILITY_USER, !use_syslog);
1.375     dtucker   859:
                    860:        if (debug_flag)
1.402   ! markus    861:                logit("%s, %s", SSH_VERSION,
        !           862: #ifdef WITH_OPENSSL
        !           863:                    SSLeay_version(SSLEAY_VERSION)
        !           864: #else
        !           865:                    "without OpenSSL"
        !           866: #endif
        !           867:                );
1.31      markus    868:
1.400     djm       869:        /* Parse the configuration files */
                    870:        process_config_files(pw);
                    871:
                    872:        /* Hostname canonicalisation needs a few options filled. */
                    873:        fill_default_options_for_canonicalization(&options);
                    874:
                    875:        /* If the user has replaced the hostname then take it into use now */
                    876:        if (options.hostname != NULL) {
                    877:                /* NB. Please keep in sync with readconf.c:match_cfg_line() */
                    878:                cp = percent_expand(options.hostname,
                    879:                    "h", host, (char *)NULL);
                    880:                free(host);
                    881:                host = cp;
                    882:        }
                    883:
                    884:        /* If canonicalization requested then try to apply it */
                    885:        lowercase(host);
                    886:        if (options.canonicalize_hostname != SSH_CANONICALISE_NO)
                    887:                addrs = resolve_canonicalize(&host, options.port);
                    888:
1.139     markus    889:        /*
1.401     djm       890:         * If CanonicalizePermittedCNAMEs have been specified but
                    891:         * other canonicalization did not happen (by not being requested
                    892:         * or by failing with fallback) then the hostname may still be changed
                    893:         * as a result of CNAME following.
                    894:         *
                    895:         * Try to resolve the bare hostname name using the system resolver's
                    896:         * usual search rules and then apply the CNAME follow rules.
                    897:         *
                    898:         * Skip the lookup if a ProxyCommand is being used unless the user
                    899:         * has specifically requested canonicalisation for this case via
                    900:         * CanonicalizeHostname=always
1.139     markus    901:         */
1.401     djm       902:        if (addrs == NULL && options.num_permitted_cnames != 0 &&
                    903:            (option_clear_or_none(options.proxy_command) ||
1.400     djm       904:             options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
                    905:                if ((addrs = resolve_host(host, options.port, 1,
                    906:                    cname, sizeof(cname))) == NULL)
                    907:                        cleanup_exit(255); /* resolve_host logs the error */
                    908:                check_follow_cname(&host, cname);
                    909:        }
1.139     markus    910:
1.400     djm       911:        /*
                    912:         * If the target hostname has changed as a result of canonicalisation
                    913:         * then re-parse the configuration files as new stanzas may match.
                    914:         */
                    915:        if (strcasecmp(host_arg, host) != 0) {
                    916:                debug("Hostname has changed; re-reading configuration");
                    917:                process_config_files(pw);
1.139     markus    918:        }
1.31      markus    919:
                    920:        /* Fill configuration defaults. */
                    921:        fill_default_options(&options);
                    922:
1.400     djm       923:        if (options.port == 0)
                    924:                options.port = default_ssh_port();
1.196     djm       925:        channel_set_af(options.address_family);
                    926:
1.383     djm       927:        /* Tidy and check options */
                    928:        if (options.host_key_alias != NULL)
                    929:                lowercase(options.host_key_alias);
                    930:        if (options.proxy_command != NULL &&
                    931:            strcmp(options.proxy_command, "-") == 0 &&
                    932:            options.proxy_use_fdpass)
                    933:                fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1.388     djm       934:        if (original_effective_uid != 0)
                    935:                options.use_privileged_port = 0;
1.383     djm       936:
1.31      markus    937:        /* reinit */
1.325     markus    938:        log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
1.370     djm       939:
                    940:        if (options.request_tty == REQUEST_TTY_YES ||
                    941:            options.request_tty == REQUEST_TTY_FORCE)
                    942:                tty_flag = 1;
                    943:
                    944:        /* Allocate a tty by default if no command specified. */
                    945:        if (buffer_len(&command) == 0)
                    946:                tty_flag = options.request_tty != REQUEST_TTY_NO;
                    947:
                    948:        /* Force no tty */
                    949:        if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
                    950:                tty_flag = 0;
                    951:        /* Do not allocate a tty if stdin is not a tty. */
                    952:        if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
                    953:            options.request_tty != REQUEST_TTY_FORCE) {
                    954:                if (tty_flag)
                    955:                        logit("Pseudo-terminal will not be allocated because "
                    956:                            "stdin is not a terminal.");
                    957:                tty_flag = 0;
                    958:        }
1.31      markus    959:
                    960:        if (options.user == NULL)
                    961:                options.user = xstrdup(pw->pw_name);
1.343     djm       962:
1.358     djm       963:        if (gethostname(thishost, sizeof(thishost)) == -1)
                    964:                fatal("gethostname: %s", strerror(errno));
                    965:        strlcpy(shorthost, thishost, sizeof(shorthost));
                    966:        shorthost[strcspn(thishost, ".")] = '\0';
                    967:        snprintf(portstr, sizeof(portstr), "%d", options.port);
                    968:
1.317     dtucker   969:        if (options.local_command != NULL) {
                    970:                debug3("expanding LocalCommand: %s", options.local_command);
                    971:                cp = options.local_command;
                    972:                options.local_command = percent_expand(cp, "d", pw->pw_dir,
1.356     djm       973:                    "h", host, "l", thishost, "n", host_arg, "r", options.user,
1.358     djm       974:                    "p", portstr, "u", pw->pw_name, "L", shorthost,
                    975:                    (char *)NULL);
1.317     dtucker   976:                debug3("expanded LocalCommand: %s", options.local_command);
1.378     djm       977:                free(cp);
1.304     dtucker   978:        }
1.31      markus    979:
1.214     djm       980:        if (options.control_path != NULL) {
1.241     djm       981:                cp = tilde_expand_filename(options.control_path,
                    982:                    original_real_uid);
1.378     djm       983:                free(options.control_path);
1.358     djm       984:                options.control_path = percent_expand(cp, "h", host,
                    985:                    "l", thishost, "n", host_arg, "r", options.user,
                    986:                    "p", portstr, "u", pw->pw_name, "L", shorthost,
                    987:                    (char *)NULL);
1.378     djm       988:                free(cp);
1.214     djm       989:        }
1.312     djm       990:        if (muxclient_command != 0 && options.control_path == NULL)
1.240     djm       991:                fatal("No ControlPath specified for \"-O\" command");
1.242     djm       992:        if (options.control_path != NULL)
1.312     djm       993:                muxclient(options.control_path);
1.401     djm       994:
                    995:        /*
                    996:         * If hostname canonicalisation was not enabled, then we may not
                    997:         * have yet resolved the hostname. Do so now.
                    998:         */
                    999:        if (addrs == NULL && options.proxy_command == NULL) {
                   1000:                if ((addrs = resolve_host(host, options.port, 1,
                   1001:                    cname, sizeof(cname))) == NULL)
                   1002:                        cleanup_exit(255); /* resolve_host logs the error */
                   1003:        }
1.214     djm      1004:
1.303     djm      1005:        timeout_ms = options.connection_timeout * 1000;
                   1006:
1.77      markus   1007:        /* Open a connection to the remote host. */
1.385     djm      1008:        if (ssh_connect(host, addrs, &hostaddr, options.port,
                   1009:            options.address_family, options.connection_attempts,
                   1010:            &timeout_ms, options.tcp_keep_alive,
1.388     djm      1011:            options.use_privileged_port) != 0)
1.257     dtucker  1012:                exit(255);
1.31      markus   1013:
1.391     djm      1014:        if (addrs != NULL)
                   1015:                freeaddrinfo(addrs);
                   1016:
1.385     djm      1017:        packet_set_timeout(options.server_alive_interval,
                   1018:            options.server_alive_count_max);
                   1019:
1.303     djm      1020:        if (timeout_ms > 0)
                   1021:                debug3("timeout: %d ms remain after connect", timeout_ms);
                   1022:
1.33      markus   1023:        /*
                   1024:         * If we successfully made the connection, load the host private key
                   1025:         * in case we will need it later for combined rsa-rhosts
                   1026:         * authentication. This must be done before releasing extra
                   1027:         * privileges, because the file is only readable by root.
1.174     markus   1028:         * If we cannot access the private keys, load the public keys
                   1029:         * instead and try to execute the ssh-keysign helper instead.
1.33      markus   1030:         */
1.112     markus   1031:        sensitive_data.nkeys = 0;
                   1032:        sensitive_data.keys = NULL;
1.173     markus   1033:        sensitive_data.external_keysign = 0;
1.178     markus   1034:        if (options.rhosts_rsa_authentication ||
                   1035:            options.hostbased_authentication) {
1.397     djm      1036:                sensitive_data.nkeys = 9;
1.274     deraadt  1037:                sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1.180     deraadt  1038:                    sizeof(Key));
1.177     markus   1039:
                   1040:                PRIV_START;
1.112     markus   1041:                sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1.276     dtucker  1042:                    _PATH_HOST_KEY_FILE, "", NULL, NULL);
1.345     djm      1043:                sensitive_data.keys[1] = key_load_private_cert(KEY_DSA,
                   1044:                    _PATH_HOST_DSA_KEY_FILE, "", NULL);
1.349     djm      1045:                sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA,
                   1046:                    _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
                   1047:                sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
1.345     djm      1048:                    _PATH_HOST_RSA_KEY_FILE, "", NULL);
1.397     djm      1049:                sensitive_data.keys[4] = key_load_private_cert(KEY_ED25519,
                   1050:                    _PATH_HOST_ED25519_KEY_FILE, "", NULL);
                   1051:                sensitive_data.keys[5] = key_load_private_type(KEY_DSA,
1.276     dtucker  1052:                    _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1.397     djm      1053:                sensitive_data.keys[6] = key_load_private_type(KEY_ECDSA,
1.349     djm      1054:                    _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
1.397     djm      1055:                sensitive_data.keys[7] = key_load_private_type(KEY_RSA,
1.276     dtucker  1056:                    _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1.397     djm      1057:                sensitive_data.keys[8] = key_load_private_type(KEY_ED25519,
1.396     markus   1058:                    _PATH_HOST_ED25519_KEY_FILE, "", NULL, NULL);
1.177     markus   1059:                PRIV_END;
1.173     markus   1060:
1.181     markus   1061:                if (options.hostbased_authentication == 1 &&
                   1062:                    sensitive_data.keys[0] == NULL &&
1.349     djm      1063:                    sensitive_data.keys[5] == NULL &&
1.396     markus   1064:                    sensitive_data.keys[6] == NULL &&
1.397     djm      1065:                    sensitive_data.keys[7] == NULL &&
                   1066:                    sensitive_data.keys[8] == NULL) {
1.345     djm      1067:                        sensitive_data.keys[1] = key_load_cert(
                   1068:                            _PATH_HOST_DSA_KEY_FILE);
                   1069:                        sensitive_data.keys[2] = key_load_cert(
1.349     djm      1070:                            _PATH_HOST_ECDSA_KEY_FILE);
                   1071:                        sensitive_data.keys[3] = key_load_cert(
1.345     djm      1072:                            _PATH_HOST_RSA_KEY_FILE);
1.397     djm      1073:                        sensitive_data.keys[4] = key_load_cert(
                   1074:                            _PATH_HOST_ED25519_KEY_FILE);
                   1075:                        sensitive_data.keys[5] = key_load_public(
1.173     markus   1076:                            _PATH_HOST_DSA_KEY_FILE, NULL);
1.397     djm      1077:                        sensitive_data.keys[6] = key_load_public(
1.349     djm      1078:                            _PATH_HOST_ECDSA_KEY_FILE, NULL);
1.397     djm      1079:                        sensitive_data.keys[7] = key_load_public(
1.173     markus   1080:                            _PATH_HOST_RSA_KEY_FILE, NULL);
1.397     djm      1081:                        sensitive_data.keys[8] = key_load_public(
1.396     markus   1082:                            _PATH_HOST_ED25519_KEY_FILE, NULL);
1.173     markus   1083:                        sensitive_data.external_keysign = 1;
                   1084:                }
1.31      markus   1085:        }
1.33      markus   1086:        /*
                   1087:         * Get rid of any extra privileges that we may have.  We will no
                   1088:         * longer need them.  Also, extra privileges could make it very hard
                   1089:         * to read identity files and other non-world-readable files from the
                   1090:         * user's home directory if it happens to be on a NFS volume where
                   1091:         * root is mapped to nobody.
                   1092:         */
1.225     dtucker  1093:        if (original_effective_uid == 0) {
                   1094:                PRIV_START;
                   1095:                permanently_set_uid(pw);
                   1096:        }
1.31      markus   1097:
1.33      markus   1098:        /*
                   1099:         * Now that we are back to our own permissions, create ~/.ssh
1.254     djm      1100:         * directory if it doesn't already exist.
1.33      markus   1101:         */
1.367     djm      1102:        if (config == NULL) {
                   1103:                r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
                   1104:                    strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
                   1105:                if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0)
                   1106:                        if (mkdir(buf, 0700) < 0)
                   1107:                                error("Could not create directory '%.200s'.",
                   1108:                                    buf);
                   1109:        }
1.31      markus   1110:
1.104     markus   1111:        /* load options.identity_files */
                   1112:        load_public_identity_files();
                   1113:
                   1114:        /* Expand ~ in known host file names. */
1.361     djm      1115:        tilde_expand_paths(options.system_hostfiles,
                   1116:            options.num_system_hostfiles);
                   1117:        tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1.149     markus   1118:
                   1119:        signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1.352     djm      1120:        signal(SIGCHLD, main_sigchld_handler);
1.31      markus   1121:
1.316     djm      1122:        /* Log into the remote system.  Never returns if the login fails. */
1.303     djm      1123:        ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
1.355     djm      1124:            options.port, pw, timeout_ms);
1.339     djm      1125:
                   1126:        if (packet_connection_is_on_socket()) {
                   1127:                verbose("Authenticated to %s ([%s]:%d).", host,
                   1128:                    get_remote_ipaddr(), get_remote_port());
                   1129:        } else {
                   1130:                verbose("Authenticated to %s (via proxy).", host);
                   1131:        }
1.31      markus   1132:
1.112     markus   1133:        /* We no longer need the private host keys.  Clear them now. */
                   1134:        if (sensitive_data.nkeys != 0) {
                   1135:                for (i = 0; i < sensitive_data.nkeys; i++) {
                   1136:                        if (sensitive_data.keys[i] != NULL) {
                   1137:                                /* Destroys contents safely */
                   1138:                                debug3("clear hostkey %d", i);
                   1139:                                key_free(sensitive_data.keys[i]);
                   1140:                                sensitive_data.keys[i] = NULL;
                   1141:                        }
                   1142:                }
1.378     djm      1143:                free(sensitive_data.keys);
1.134     markus   1144:        }
                   1145:        for (i = 0; i < options.num_identity_files; i++) {
1.378     djm      1146:                free(options.identity_files[i]);
                   1147:                options.identity_files[i] = NULL;
1.134     markus   1148:                if (options.identity_keys[i]) {
                   1149:                        key_free(options.identity_keys[i]);
                   1150:                        options.identity_keys[i] = NULL;
                   1151:                }
1.112     markus   1152:        }
1.31      markus   1153:
1.45      markus   1154:        exit_status = compat20 ? ssh_session2() : ssh_session();
                   1155:        packet_close();
1.186     djm      1156:
1.312     djm      1157:        if (options.control_path != NULL && muxserver_sock != -1)
1.214     djm      1158:                unlink(options.control_path);
                   1159:
1.353     djm      1160:        /* Kill ProxyCommand if it is running. */
                   1161:        ssh_kill_proxy_command();
1.186     djm      1162:
1.45      markus   1163:        return exit_status;
                   1164: }
                   1165:
1.344     djm      1166: static void
                   1167: control_persist_detach(void)
                   1168: {
                   1169:        pid_t pid;
1.346     djm      1170:        int devnull;
1.344     djm      1171:
                   1172:        debug("%s: backgrounding master process", __func__);
                   1173:
                   1174:        /*
                   1175:         * master (current process) into the background, and make the
                   1176:         * foreground process a client of the backgrounded master.
                   1177:         */
                   1178:        switch ((pid = fork())) {
                   1179:        case -1:
                   1180:                fatal("%s: fork: %s", __func__, strerror(errno));
                   1181:        case 0:
                   1182:                /* Child: master process continues mainloop */
                   1183:                break;
                   1184:        default:
                   1185:                /* Parent: set up mux slave to connect to backgrounded master */
                   1186:                debug2("%s: background process is %ld", __func__, (long)pid);
                   1187:                stdin_null_flag = ostdin_null_flag;
1.359     djm      1188:                options.request_tty = orequest_tty;
1.344     djm      1189:                tty_flag = otty_flag;
                   1190:                close(muxserver_sock);
                   1191:                muxserver_sock = -1;
1.351     markus   1192:                options.control_master = SSHCTL_MASTER_NO;
1.344     djm      1193:                muxclient(options.control_path);
                   1194:                /* muxclient() doesn't return on success. */
                   1195:                fatal("Failed to connect to new control master");
                   1196:        }
1.346     djm      1197:        if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
                   1198:                error("%s: open(\"/dev/null\"): %s", __func__,
                   1199:                    strerror(errno));
                   1200:        } else {
                   1201:                if (dup2(devnull, STDIN_FILENO) == -1 ||
                   1202:                    dup2(devnull, STDOUT_FILENO) == -1)
                   1203:                        error("%s: dup2: %s", __func__, strerror(errno));
                   1204:                if (devnull > STDERR_FILENO)
                   1205:                        close(devnull);
                   1206:        }
1.381     djm      1207:        daemon(1, 1);
1.362     djm      1208:        setproctitle("%s [mux]", options.control_path);
1.344     djm      1209: }
                   1210:
                   1211: /* Do fork() after authentication. Used by "ssh -f" */
                   1212: static void
                   1213: fork_postauth(void)
                   1214: {
                   1215:        if (need_controlpersist_detach)
                   1216:                control_persist_detach();
                   1217:        debug("forking to background");
                   1218:        fork_after_authentication_flag = 0;
                   1219:        if (daemon(1, 1) < 0)
                   1220:                fatal("daemon() failed: %.200s", strerror(errno));
                   1221: }
                   1222:
1.315     djm      1223: /* Callback for remote forward global requests */
                   1224: static void
                   1225: ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
                   1226: {
                   1227:        Forward *rfwd = (Forward *)ctxt;
                   1228:
1.324     djm      1229:        /* XXX verbose() on failure? */
1.315     djm      1230:        debug("remote forward %s for: listen %d, connect %s:%d",
                   1231:            type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
                   1232:            rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
1.366     markus   1233:        if (rfwd->listen_port == 0) {
                   1234:                if (type == SSH2_MSG_REQUEST_SUCCESS) {
                   1235:                        rfwd->allocated_port = packet_get_int();
                   1236:                        logit("Allocated port %u for remote forward to %s:%d",
                   1237:                            rfwd->allocated_port,
                   1238:                            rfwd->connect_host, rfwd->connect_port);
                   1239:                        channel_update_permitted_opens(rfwd->handle,
                   1240:                            rfwd->allocated_port);
                   1241:                } else {
                   1242:                        channel_update_permitted_opens(rfwd->handle, -1);
                   1243:                }
1.324     djm      1244:        }
                   1245:
1.315     djm      1246:        if (type == SSH2_MSG_REQUEST_FAILURE) {
                   1247:                if (options.exit_on_forward_failure)
                   1248:                        fatal("Error: remote port forwarding failed for "
                   1249:                            "listen port %d", rfwd->listen_port);
                   1250:                else
                   1251:                        logit("Warning: remote port forwarding failed for "
                   1252:                            "listen port %d", rfwd->listen_port);
                   1253:        }
1.318     djm      1254:        if (++remote_forward_confirms_received == options.num_remote_forwards) {
1.315     djm      1255:                debug("All remote forwarding requests processed");
1.344     djm      1256:                if (fork_after_authentication_flag)
                   1257:                        fork_postauth();
1.318     djm      1258:        }
1.315     djm      1259: }
                   1260:
1.126     itojun   1261: static void
1.331     dtucker  1262: client_cleanup_stdio_fwd(int id, void *arg)
                   1263: {
                   1264:        debug("stdio forwarding: done");
                   1265:        cleanup_exit(0);
                   1266: }
                   1267:
1.368     djm      1268: static void
                   1269: ssh_init_stdio_forwarding(void)
1.331     dtucker  1270: {
                   1271:        Channel *c;
1.332     djm      1272:        int in, out;
1.331     dtucker  1273:
1.368     djm      1274:        if (stdio_forward_host == NULL)
                   1275:                return;
1.384     djm      1276:        if (!compat20)
1.368     djm      1277:                fatal("stdio forwarding require Protocol 2");
                   1278:
                   1279:        debug3("%s: %s:%d", __func__, stdio_forward_host, stdio_forward_port);
1.332     djm      1280:
1.368     djm      1281:        if ((in = dup(STDIN_FILENO)) < 0 ||
                   1282:            (out = dup(STDOUT_FILENO)) < 0)
1.332     djm      1283:                fatal("channel_connect_stdio_fwd: dup() in/out failed");
1.368     djm      1284:        if ((c = channel_connect_stdio_fwd(stdio_forward_host,
                   1285:            stdio_forward_port, in, out)) == NULL)
                   1286:                fatal("%s: channel_connect_stdio_fwd failed", __func__);
1.331     dtucker  1287:        channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
                   1288: }
                   1289:
                   1290: static void
1.70      markus   1291: ssh_init_forwarding(void)
                   1292: {
1.86      markus   1293:        int success = 0;
1.70      markus   1294:        int i;
1.331     dtucker  1295:
1.70      markus   1296:        /* Initiate local TCP/IP port forwardings. */
                   1297:        for (i = 0; i < options.num_local_forwards; i++) {
1.232     djm      1298:                debug("Local connections to %.200s:%d forwarded to remote "
                   1299:                    "address %.200s:%d",
1.234     deraadt  1300:                    (options.local_forwards[i].listen_host == NULL) ?
                   1301:                    (options.gateway_ports ? "*" : "LOCALHOST") :
1.232     djm      1302:                    options.local_forwards[i].listen_host,
                   1303:                    options.local_forwards[i].listen_port,
                   1304:                    options.local_forwards[i].connect_host,
                   1305:                    options.local_forwards[i].connect_port);
1.158     markus   1306:                success += channel_setup_local_fwd_listener(
1.232     djm      1307:                    options.local_forwards[i].listen_host,
                   1308:                    options.local_forwards[i].listen_port,
                   1309:                    options.local_forwards[i].connect_host,
                   1310:                    options.local_forwards[i].connect_port,
1.70      markus   1311:                    options.gateway_ports);
                   1312:        }
1.283     markus   1313:        if (i > 0 && success != i && options.exit_on_forward_failure)
                   1314:                fatal("Could not request local forwarding.");
1.86      markus   1315:        if (i > 0 && success == 0)
                   1316:                error("Could not request local forwarding.");
1.70      markus   1317:
                   1318:        /* Initiate remote TCP/IP port forwardings. */
                   1319:        for (i = 0; i < options.num_remote_forwards; i++) {
1.232     djm      1320:                debug("Remote connections from %.200s:%d forwarded to "
                   1321:                    "local address %.200s:%d",
1.248     djm      1322:                    (options.remote_forwards[i].listen_host == NULL) ?
1.253     djm      1323:                    "LOCALHOST" : options.remote_forwards[i].listen_host,
1.232     djm      1324:                    options.remote_forwards[i].listen_port,
                   1325:                    options.remote_forwards[i].connect_host,
                   1326:                    options.remote_forwards[i].connect_port);
1.366     markus   1327:                options.remote_forwards[i].handle =
                   1328:                    channel_request_remote_forwarding(
1.232     djm      1329:                    options.remote_forwards[i].listen_host,
                   1330:                    options.remote_forwards[i].listen_port,
                   1331:                    options.remote_forwards[i].connect_host,
1.366     markus   1332:                    options.remote_forwards[i].connect_port);
                   1333:                if (options.remote_forwards[i].handle < 0) {
1.283     markus   1334:                        if (options.exit_on_forward_failure)
                   1335:                                fatal("Could not request remote forwarding.");
                   1336:                        else
                   1337:                                logit("Warning: Could not request remote "
                   1338:                                    "forwarding.");
1.366     markus   1339:                } else {
                   1340:                        client_register_global_confirm(ssh_confirm_remote_forward,
                   1341:                            &options.remote_forwards[i]);
1.283     markus   1342:                }
1.70      markus   1343:        }
1.301     djm      1344:
                   1345:        /* Initiate tunnel forwarding. */
                   1346:        if (options.tun_open != SSH_TUNMODE_NO) {
                   1347:                if (client_request_tun_fwd(options.tun_open,
                   1348:                    options.tun_local, options.tun_remote) == -1) {
                   1349:                        if (options.exit_on_forward_failure)
                   1350:                                fatal("Could not request tunnel forwarding.");
                   1351:                        else
                   1352:                                error("Could not request tunnel forwarding.");
                   1353:                }
                   1354:        }
1.70      markus   1355: }
                   1356:
1.126     itojun   1357: static void
1.70      markus   1358: check_agent_present(void)
                   1359: {
                   1360:        if (options.forward_agent) {
1.254     djm      1361:                /* Clear agent forwarding if we don't have an agent. */
1.185     stevesk  1362:                if (!ssh_agent_present())
1.70      markus   1363:                        options.forward_agent = 0;
                   1364:        }
                   1365: }
                   1366:
1.126     itojun   1367: static int
1.45      markus   1368: ssh_session(void)
                   1369: {
                   1370:        int type;
                   1371:        int interactive = 0;
                   1372:        int have_tty = 0;
                   1373:        struct winsize ws;
                   1374:        char *cp;
1.243     djm      1375:        const char *display;
1.45      markus   1376:
1.31      markus   1377:        /* Enable compression if requested. */
                   1378:        if (options.compression) {
1.316     djm      1379:                debug("Requesting compression at level %d.",
                   1380:                    options.compression_level);
1.31      markus   1381:
1.316     djm      1382:                if (options.compression_level < 1 ||
                   1383:                    options.compression_level > 9)
                   1384:                        fatal("Compression level must be from 1 (fast) to "
                   1385:                            "9 (slow, best).");
1.31      markus   1386:
                   1387:                /* Send the request. */
                   1388:                packet_start(SSH_CMSG_REQUEST_COMPRESSION);
                   1389:                packet_put_int(options.compression_level);
                   1390:                packet_send();
                   1391:                packet_write_wait();
1.156     markus   1392:                type = packet_read();
1.31      markus   1393:                if (type == SSH_SMSG_SUCCESS)
                   1394:                        packet_start_compression(options.compression_level);
                   1395:                else if (type == SSH_SMSG_FAILURE)
1.191     itojun   1396:                        logit("Warning: Remote host refused compression.");
1.31      markus   1397:                else
1.316     djm      1398:                        packet_disconnect("Protocol error waiting for "
                   1399:                            "compression response.");
1.31      markus   1400:        }
                   1401:        /* Allocate a pseudo tty if appropriate. */
                   1402:        if (tty_flag) {
                   1403:                debug("Requesting pty.");
                   1404:
                   1405:                /* Start the packet. */
                   1406:                packet_start(SSH_CMSG_REQUEST_PTY);
                   1407:
                   1408:                /* Store TERM in the packet.  There is no limit on the
                   1409:                   length of the string. */
                   1410:                cp = getenv("TERM");
                   1411:                if (!cp)
                   1412:                        cp = "";
1.124     markus   1413:                packet_put_cstring(cp);
1.31      markus   1414:
                   1415:                /* Store window size in the packet. */
                   1416:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
                   1417:                        memset(&ws, 0, sizeof(ws));
1.269     deraadt  1418:                packet_put_int((u_int)ws.ws_row);
                   1419:                packet_put_int((u_int)ws.ws_col);
                   1420:                packet_put_int((u_int)ws.ws_xpixel);
                   1421:                packet_put_int((u_int)ws.ws_ypixel);
1.31      markus   1422:
                   1423:                /* Store tty modes in the packet. */
1.115     stevesk  1424:                tty_make_modes(fileno(stdin), NULL);
1.31      markus   1425:
                   1426:                /* Send the packet, and wait for it to leave. */
                   1427:                packet_send();
                   1428:                packet_write_wait();
                   1429:
                   1430:                /* Read response from the server. */
1.156     markus   1431:                type = packet_read();
1.43      markus   1432:                if (type == SSH_SMSG_SUCCESS) {
1.31      markus   1433:                        interactive = 1;
1.45      markus   1434:                        have_tty = 1;
1.43      markus   1435:                } else if (type == SSH_SMSG_FAILURE)
1.316     djm      1436:                        logit("Warning: Remote host failed or refused to "
                   1437:                            "allocate a pseudo tty.");
1.31      markus   1438:                else
1.316     djm      1439:                        packet_disconnect("Protocol error waiting for pty "
                   1440:                            "request response.");
1.31      markus   1441:        }
                   1442:        /* Request X11 forwarding if enabled and DISPLAY is set. */
1.243     djm      1443:        display = getenv("DISPLAY");
                   1444:        if (options.forward_x11 && display != NULL) {
1.150     stevesk  1445:                char *proto, *data;
1.50      markus   1446:                /* Get reasonable local authentication information. */
1.243     djm      1447:                client_x11_get_proto(display, options.xauth_location,
1.384     djm      1448:                    options.forward_x11_trusted,
1.340     djm      1449:                    options.forward_x11_timeout,
                   1450:                    &proto, &data);
1.50      markus   1451:                /* Request forwarding with authentication spoofing. */
1.316     djm      1452:                debug("Requesting X11 forwarding with authentication "
                   1453:                    "spoofing.");
1.363     djm      1454:                x11_request_forwarding_with_spoofing(0, display, proto,
                   1455:                    data, 0);
1.31      markus   1456:                /* Read response from the server. */
1.156     markus   1457:                type = packet_read();
1.31      markus   1458:                if (type == SSH_SMSG_SUCCESS) {
                   1459:                        interactive = 1;
1.50      markus   1460:                } else if (type == SSH_SMSG_FAILURE) {
1.191     itojun   1461:                        logit("Warning: Remote host denied X11 forwarding.");
1.50      markus   1462:                } else {
1.316     djm      1463:                        packet_disconnect("Protocol error waiting for X11 "
                   1464:                            "forwarding");
1.50      markus   1465:                }
1.31      markus   1466:        }
                   1467:        /* Tell the packet module whether this is an interactive session. */
1.354     djm      1468:        packet_set_interactive(interactive,
                   1469:            options.ip_qos_interactive, options.ip_qos_bulk);
1.31      markus   1470:
                   1471:        /* Request authentication agent forwarding if appropriate. */
1.70      markus   1472:        check_agent_present();
                   1473:
1.31      markus   1474:        if (options.forward_agent) {
                   1475:                debug("Requesting authentication agent forwarding.");
                   1476:                auth_request_forwarding();
                   1477:
                   1478:                /* Read response from the server. */
1.156     markus   1479:                type = packet_read();
1.155     markus   1480:                packet_check_eom();
1.31      markus   1481:                if (type != SSH_SMSG_SUCCESS)
1.191     itojun   1482:                        logit("Warning: Remote host denied authentication agent forwarding.");
1.31      markus   1483:        }
                   1484:
1.70      markus   1485:        /* Initiate port forwardings. */
1.368     djm      1486:        ssh_init_stdio_forwarding();
1.70      markus   1487:        ssh_init_forwarding();
1.305     dtucker  1488:
                   1489:        /* Execute a local command */
                   1490:        if (options.local_command != NULL &&
                   1491:            options.permit_local_command)
                   1492:                ssh_local_cmd(options.local_command);
1.34      markus   1493:
1.318     djm      1494:        /*
                   1495:         * If requested and we are not interested in replies to remote
                   1496:         * forwarding requests, then let ssh continue in the background.
                   1497:         */
1.344     djm      1498:        if (fork_after_authentication_flag) {
                   1499:                if (options.exit_on_forward_failure &&
                   1500:                    options.num_remote_forwards > 0) {
                   1501:                        debug("deferring postauth fork until remote forward "
                   1502:                            "confirmation received");
                   1503:                } else
                   1504:                        fork_postauth();
1.318     djm      1505:        }
1.31      markus   1506:
1.33      markus   1507:        /*
                   1508:         * If a command was specified on the command line, execute the
                   1509:         * command now. Otherwise request the server to start a shell.
                   1510:         */
1.31      markus   1511:        if (buffer_len(&command) > 0) {
                   1512:                int len = buffer_len(&command);
                   1513:                if (len > 900)
                   1514:                        len = 900;
1.316     djm      1515:                debug("Sending command: %.*s", len,
                   1516:                    (u_char *)buffer_ptr(&command));
1.31      markus   1517:                packet_start(SSH_CMSG_EXEC_CMD);
                   1518:                packet_put_string(buffer_ptr(&command), buffer_len(&command));
                   1519:                packet_send();
                   1520:                packet_write_wait();
                   1521:        } else {
                   1522:                debug("Requesting shell.");
                   1523:                packet_start(SSH_CMSG_EXEC_SHELL);
                   1524:                packet_send();
                   1525:                packet_write_wait();
                   1526:        }
                   1527:
                   1528:        /* Enter the interactive session. */
1.119     stevesk  1529:        return client_loop(have_tty, tty_flag ?
                   1530:            options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1.89      markus   1531: }
                   1532:
1.214     djm      1533: /* request pty/x11/agent/tcpfwd/shell for channel */
                   1534: static void
1.337     djm      1535: ssh_session2_setup(int id, int success, void *arg)
1.214     djm      1536: {
1.215     djm      1537:        extern char **environ;
1.243     djm      1538:        const char *display;
                   1539:        int interactive = tty_flag;
1.337     djm      1540:
                   1541:        if (!success)
                   1542:                return; /* No need for error message, channels code sens one */
1.215     djm      1543:
1.248     djm      1544:        display = getenv("DISPLAY");
1.243     djm      1545:        if (options.forward_x11 && display != NULL) {
1.150     stevesk  1546:                char *proto, *data;
1.50      markus   1547:                /* Get reasonable local authentication information. */
1.243     djm      1548:                client_x11_get_proto(display, options.xauth_location,
1.340     djm      1549:                    options.forward_x11_trusted,
                   1550:                    options.forward_x11_timeout, &proto, &data);
1.50      markus   1551:                /* Request forwarding with authentication spoofing. */
1.316     djm      1552:                debug("Requesting X11 forwarding with authentication "
                   1553:                    "spoofing.");
1.363     djm      1554:                x11_request_forwarding_with_spoofing(id, display, proto,
                   1555:                    data, 1);
                   1556:                client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
                   1557:                /* XXX exit_on_forward_failure */
1.80      markus   1558:                interactive = 1;
1.50      markus   1559:        }
                   1560:
1.70      markus   1561:        check_agent_present();
                   1562:        if (options.forward_agent) {
                   1563:                debug("Requesting authentication agent forwarding.");
                   1564:                channel_request_start(id, "auth-agent-req@openssh.com", 0);
                   1565:                packet_send();
1.212     djm      1566:        }
1.369     dtucker  1567:
                   1568:        /* Tell the packet module whether this is an interactive session. */
                   1569:        packet_set_interactive(interactive,
                   1570:            options.ip_qos_interactive, options.ip_qos_bulk);
1.212     djm      1571:
1.214     djm      1572:        client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1.311     djm      1573:            NULL, fileno(stdin), &command, environ);
1.45      markus   1574: }
                   1575:
1.143     markus   1576: /* open new channel for a session */
1.126     itojun   1577: static int
1.143     markus   1578: ssh_session2_open(void)
1.45      markus   1579: {
1.118     markus   1580:        Channel *c;
                   1581:        int window, packetmax, in, out, err;
1.60      markus   1582:
1.62      markus   1583:        if (stdin_null_flag) {
1.93      itojun   1584:                in = open(_PATH_DEVNULL, O_RDONLY);
1.62      markus   1585:        } else {
                   1586:                in = dup(STDIN_FILENO);
                   1587:        }
1.60      markus   1588:        out = dup(STDOUT_FILENO);
                   1589:        err = dup(STDERR_FILENO);
1.45      markus   1590:
                   1591:        if (in < 0 || out < 0 || err < 0)
1.62      markus   1592:                fatal("dup() in/out/err failed");
1.45      markus   1593:
1.69      markus   1594:        /* enable nonblocking unless tty */
                   1595:        if (!isatty(in))
                   1596:                set_nonblock(in);
                   1597:        if (!isatty(out))
                   1598:                set_nonblock(out);
                   1599:        if (!isatty(err))
                   1600:                set_nonblock(err);
                   1601:
1.65      markus   1602:        window = CHAN_SES_WINDOW_DEFAULT;
                   1603:        packetmax = CHAN_SES_PACKET_DEFAULT;
1.164     markus   1604:        if (tty_flag) {
                   1605:                window >>= 1;
                   1606:                packetmax >>= 1;
1.45      markus   1607:        }
1.118     markus   1608:        c = channel_new(
1.45      markus   1609:            "session", SSH_CHANNEL_OPENING, in, out, err,
1.65      markus   1610:            window, packetmax, CHAN_EXTENDED_WRITE,
1.192     markus   1611:            "client-session", /*nonblock*/0);
1.45      markus   1612:
1.143     markus   1613:        debug3("ssh_session2_open: channel_new: %d", c->self);
1.106     markus   1614:
1.122     markus   1615:        channel_send_open(c->self);
1.143     markus   1616:        if (!no_shell_flag)
1.310     djm      1617:                channel_register_open_confirm(c->self,
                   1618:                    ssh_session2_setup, NULL);
1.106     markus   1619:
1.118     markus   1620:        return c->self;
1.106     markus   1621: }
                   1622:
1.126     itojun   1623: static int
1.106     markus   1624: ssh_session2(void)
                   1625: {
1.143     markus   1626:        int id = -1;
1.106     markus   1627:
                   1628:        /* XXX should be pre-session */
1.368     djm      1629:        if (!options.control_persist)
                   1630:                ssh_init_stdio_forwarding();
1.106     markus   1631:        ssh_init_forwarding();
                   1632:
1.344     djm      1633:        /* Start listening for multiplex clients */
                   1634:        muxserver_listen();
                   1635:
                   1636:        /*
1.368     djm      1637:         * If we are in control persist mode and have a working mux listen
                   1638:         * socket, then prepare to background ourselves and have a foreground
                   1639:         * client attach as a control slave.
                   1640:         * NB. we must save copies of the flags that we override for
1.344     djm      1641:         * the backgrounding, since we defer attachment of the slave until
                   1642:         * after the connection is fully established (in particular,
                   1643:         * async rfwd replies have been received for ExitOnForwardFailure).
                   1644:         */
                   1645:        if (options.control_persist && muxserver_sock != -1) {
                   1646:                ostdin_null_flag = stdin_null_flag;
                   1647:                ono_shell_flag = no_shell_flag;
1.359     djm      1648:                orequest_tty = options.request_tty;
1.344     djm      1649:                otty_flag = tty_flag;
                   1650:                stdin_null_flag = 1;
                   1651:                no_shell_flag = 1;
                   1652:                tty_flag = 0;
                   1653:                if (!fork_after_authentication_flag)
                   1654:                        need_controlpersist_detach = 1;
                   1655:                fork_after_authentication_flag = 1;
                   1656:        }
1.368     djm      1657:        /*
                   1658:         * ControlPersist mux listen socket setup failed, attempt the
                   1659:         * stdio forward setup that we skipped earlier.
                   1660:         */
                   1661:        if (options.control_persist && muxserver_sock == -1)
                   1662:                ssh_init_stdio_forwarding();
1.344     djm      1663:
1.143     markus   1664:        if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
                   1665:                id = ssh_session2_open();
1.379     djm      1666:        else {
                   1667:                packet_set_interactive(
                   1668:                    options.control_master == SSHCTL_MASTER_NO,
                   1669:                    options.ip_qos_interactive, options.ip_qos_bulk);
                   1670:        }
1.314     djm      1671:
                   1672:        /* If we don't expect to open a new session, then disallow it */
1.319     markus   1673:        if (options.control_master == SSHCTL_MASTER_NO &&
                   1674:            (datafellows & SSH_NEW_OPENSSH)) {
1.314     djm      1675:                debug("Requesting no-more-sessions@openssh.com");
                   1676:                packet_start(SSH2_MSG_GLOBAL_REQUEST);
                   1677:                packet_put_cstring("no-more-sessions@openssh.com");
                   1678:                packet_put_char(0);
                   1679:                packet_send();
                   1680:        }
1.255     reyk     1681:
                   1682:        /* Execute a local command */
                   1683:        if (options.local_command != NULL &&
                   1684:            options.permit_local_command)
                   1685:                ssh_local_cmd(options.local_command);
1.301     djm      1686:
1.342     djm      1687:        /*
                   1688:         * If requested and we are not interested in replies to remote
                   1689:         * forwarding requests, then let ssh continue in the background.
                   1690:         */
1.344     djm      1691:        if (fork_after_authentication_flag) {
                   1692:                if (options.exit_on_forward_failure &&
                   1693:                    options.num_remote_forwards > 0) {
                   1694:                        debug("deferring postauth fork until remote forward "
                   1695:                            "confirmation received");
                   1696:                } else
                   1697:                        fork_postauth();
1.318     djm      1698:        }
1.327     andreas  1699:
                   1700:        if (options.use_roaming)
                   1701:                request_roaming();
1.31      markus   1702:
1.119     stevesk  1703:        return client_loop(tty_flag, tty_flag ?
                   1704:            options.escape_char : SSH_ESCAPECHAR_NONE, id);
1.72      markus   1705: }
                   1706:
1.126     itojun   1707: static void
1.104     markus   1708: load_public_identity_files(void)
                   1709: {
1.275     djm      1710:        char *filename, *cp, thishost[NI_MAXHOST];
1.306     deraadt  1711:        char *pwdir = NULL, *pwname = NULL;
1.167     markus   1712:        int i = 0;
1.104     markus   1713:        Key *public;
1.275     djm      1714:        struct passwd *pw;
1.335     djm      1715:        u_int n_ids;
                   1716:        char *identity_files[SSH_MAX_IDENTITY_FILES];
                   1717:        Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1.333     markus   1718: #ifdef ENABLE_PKCS11
1.167     markus   1719:        Key **keys;
1.333     markus   1720:        int nkeys;
1.335     djm      1721: #endif /* PKCS11 */
1.104     markus   1722:
1.335     djm      1723:        n_ids = 0;
1.398     tedu     1724:        memset(identity_files, 0, sizeof(identity_files));
                   1725:        memset(identity_keys, 0, sizeof(identity_keys));
1.335     djm      1726:
                   1727: #ifdef ENABLE_PKCS11
1.333     markus   1728:        if (options.pkcs11_provider != NULL &&
1.167     markus   1729:            options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1.333     markus   1730:            (pkcs11_init(!options.batch_mode) == 0) &&
                   1731:            (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
                   1732:            &keys)) > 0) {
                   1733:                for (i = 0; i < nkeys; i++) {
1.335     djm      1734:                        if (n_ids >= SSH_MAX_IDENTITY_FILES) {
                   1735:                                key_free(keys[i]);
                   1736:                                continue;
                   1737:                        }
                   1738:                        identity_keys[n_ids] = keys[i];
                   1739:                        identity_files[n_ids] =
1.333     markus   1740:                            xstrdup(options.pkcs11_provider); /* XXX */
1.335     djm      1741:                        n_ids++;
1.167     markus   1742:                }
1.378     djm      1743:                free(keys);
1.127     markus   1744:        }
1.333     markus   1745: #endif /* ENABLE_PKCS11 */
1.275     djm      1746:        if ((pw = getpwuid(original_real_uid)) == NULL)
                   1747:                fatal("load_public_identity_files: getpwuid failed");
1.307     dtucker  1748:        pwname = xstrdup(pw->pw_name);
                   1749:        pwdir = xstrdup(pw->pw_dir);
1.275     djm      1750:        if (gethostname(thishost, sizeof(thishost)) == -1)
                   1751:                fatal("load_public_identity_files: gethostname: %s",
                   1752:                    strerror(errno));
1.335     djm      1753:        for (i = 0; i < options.num_identity_files; i++) {
1.373     djm      1754:                if (n_ids >= SSH_MAX_IDENTITY_FILES ||
                   1755:                    strcasecmp(options.identity_files[i], "none") == 0) {
1.378     djm      1756:                        free(options.identity_files[i]);
1.335     djm      1757:                        continue;
                   1758:                }
1.275     djm      1759:                cp = tilde_expand_filename(options.identity_files[i],
1.131     millert  1760:                    original_real_uid);
1.306     deraadt  1761:                filename = percent_expand(cp, "d", pwdir,
                   1762:                    "u", pwname, "l", thishost, "h", host,
1.275     djm      1763:                    "r", options.user, (char *)NULL);
1.378     djm      1764:                free(cp);
1.131     millert  1765:                public = key_load_public(filename, NULL);
                   1766:                debug("identity file %s type %d", filename,
                   1767:                    public ? public->type : -1);
1.378     djm      1768:                free(options.identity_files[i]);
1.335     djm      1769:                identity_files[n_ids] = filename;
                   1770:                identity_keys[n_ids] = public;
                   1771:
                   1772:                if (++n_ids >= SSH_MAX_IDENTITY_FILES)
                   1773:                        continue;
                   1774:
                   1775:                /* Try to add the certificate variant too */
                   1776:                xasprintf(&cp, "%s-cert", filename);
                   1777:                public = key_load_public(cp, NULL);
                   1778:                debug("identity file %s type %d", cp,
                   1779:                    public ? public->type : -1);
                   1780:                if (public == NULL) {
1.378     djm      1781:                        free(cp);
1.335     djm      1782:                        continue;
                   1783:                }
                   1784:                if (!key_is_cert(public)) {
                   1785:                        debug("%s: key %s type %s is not a certificate",
                   1786:                            __func__, cp, key_type(public));
                   1787:                        key_free(public);
1.378     djm      1788:                        free(cp);
1.335     djm      1789:                        continue;
                   1790:                }
                   1791:                identity_keys[n_ids] = public;
                   1792:                /* point to the original path, most likely the private key */
                   1793:                identity_files[n_ids] = xstrdup(filename);
                   1794:                n_ids++;
                   1795:        }
                   1796:        options.num_identity_files = n_ids;
                   1797:        memcpy(options.identity_files, identity_files, sizeof(identity_files));
                   1798:        memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
                   1799:
1.398     tedu     1800:        explicit_bzero(pwname, strlen(pwname));
1.378     djm      1801:        free(pwname);
1.398     tedu     1802:        explicit_bzero(pwdir, strlen(pwdir));
1.378     djm      1803:        free(pwdir);
1.214     djm      1804: }
1.352     djm      1805:
                   1806: static void
                   1807: main_sigchld_handler(int sig)
                   1808: {
                   1809:        int save_errno = errno;
                   1810:        pid_t pid;
                   1811:        int status;
                   1812:
                   1813:        while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
                   1814:            (pid < 0 && errno == EINTR))
                   1815:                ;
                   1816:
                   1817:        signal(sig, main_sigchld_handler);
                   1818:        errno = save_errno;
                   1819: }