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

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