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

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