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

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