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

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