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

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